您的位置:首页 > 编程语言 > Java开发

JAVA中使用Scanner连续输入int和String错误的解决方案

2016-03-30 12:19 555 查看
在这段代码中,输入成员ID后并添加后,跳转到一下个循环后,没有输入a,b就输出登陆错误,原因是因为nextInt()只读取了int的数值却没有读取到了换行符。
共有两种解决方案:
一、在nextInt()后再读取一个nextLine(),不做任何的处理
二、用readLine()读取,并用Integer.parseInt()将读取到的字符串转为int型。
<pre name="code" class="java">package test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Scanner;

public class homework {
public static void main(String[] args) {
Collection<registe> allMem = new ArrayList<registe>();
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);//获取键盘输入的是A还是B
while(true){
System.out.println("请输入:A 注册    B  登陆");
String register = sc.nextLine();
/*
* 输入是A就注册,是B就登陆,都不是就返回错误。
*/
if("A".equalsIgnoreCase(register) == true ){
System.out.println("请输入新成员名字:");
String name = sc.nextLine();
System.out.println("请输入新成员ID:");
int id = sc.nextInt();
System.out.println("开始添加 ");
registe newMem = new registe(id,name);//创建一个新的成员对象
newMem.addAndPrint(allMem);//将成员对象添加到集合中

}else if("B".equalsIgnoreCase(register) == true){

}else{
System.out.println("输入错误");
}
}
}
}
class registe{
int id;
String name;
public registe(int id, String name) {
super();
this.id = id;
this.name = name;
}
public void addAndPrint(Collection<registe> c){
c.add(this);
System.out.println("添加成功");
Object[] allMem = c.toArray();
System.out.println("集合中共有如下成员:");
for(int i =0;i<allMem.length;i++){//遍历集合并打印
System.out.println("成员名字:   "+((registe)allMem[i]).name+"成员ID:  "+((registe)allMem[i]).id);
}
}
}




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息