Scanner获取键盘输入总是出错,比如我输入"英语",debug里显示的值有时是"yingyuying英语",有时候又是正常的"英语",请问是源码哪里有问题吗?
package Library;
import java.util.Scanner;
public class Test03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Book [] bookForBorrow={new Book(1,"高数"),new Book(2,"线代"),new Book(3,"工数")
,new Book(4,"电路"),new Book(5,"模电"),new Book(6,"数电"),
new Book(7,"英语"),new Book(8,"毛概")};
System.out.println("欢迎使用图书馆借书系统!输入:1-按名称查找书籍 2-按序号查找书籍");
Scanner sc=new Scanner(System.in);
int i=sc.nextInt();
try{
if(i!=1 && i!=2){
throw new BadCommand("输入有误!请按提示输入数字命令");
}
if(i==1){
System.out.println("请输入图书名称:");
String name=sc.next();//就是这里总是出错!
int f=0;
for(Book book:bookForBorrow){
if(book.getBookname().equals(name)){
f=1;
String fName="book:"+name;
System.out.println(fName);
break;
}
}
if(f==0){
throw new NoExist("图书不存在!");
}
}else if(i==2){
System.out.println("请输入图书序号:");
int k=sc.nextInt();
int m=0;
for(int a=0;a<bookForBorrow.length;a++){
if(bookForBorrow[a].getOrderNum()==k){
String fname="book:"+bookForBorrow[a].getBookname();
System.out.println(fname);
m=1;
break;
}
}
if(m==0){
throw new NoExist("图书不存在!");
}
}
}catch(BadCommand e1){
System.out.println(e1.getMessage());
}
catch(NoExist e2){
System.out.println(e2.getMessage());
}
}
}
//测试
package Library;
import java.util.Scanner;
public class Test02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("请输入:");
String name=sc.next();//这里接收到的字符串又是对的。
Book [] bookForBorrow={new Book(1,"高数"),new Book(2,"线代"),new Book(3,"工数")
,new Book(4,"电路"),new Book(5,"模电"),new Book(6,"数电"),
new Book(7,"英语"),new Book(8,"毛概")};
for(int i=0;i<bookForBorrow.length;i++){
/*if(book.getBookname().equals(name)){
String fName="book:"+name;
System.out.println(fName);
break;*/
if(bookForBorrow[i].getBookname().equals(name)){
String fName="book:"+name;
System.out.println(fName);
break;
}
}
System.out.println("over!");
}
}补充一个我测试的代码,这个接收到的又是对的




