关于input.next()输入问题
我在MyEclipse里面调用String s1=input.next();当输入:语文+空格+回车;得到的s1确是:yu语文;不知道怎么回事呀?好像有的时候能得到正确结果
我在MyEclipse里面调用String s1=input.next();当输入:语文+空格+回车;得到的s1确是:yu语文;不知道怎么回事呀?好像有的时候能得到正确结果
2017-03-25
package 模拟借书系统; //包名一般用英文字母小写,倒写域名加模块名加功能名,用"."分割成四级
import java.util.Scanner;
import java.util.InputMismatchException;
public class rendBook { //类名命名遵从大驼峰原则,首字母要大写,应为RendBook
public static void main(String[] args) throws Exception { //不是很明白为什么要在这里抛异常
// TODO Auto-generated method stub
String[] book={"语文","数学","英语","政治","历史","地理"};
boolean x=true; //见第51行
do{
Scanner input=new Scanner(System.in); //建议把input放到循环外面,并在循环结束后关闭input,input.closed()
System.out.println("请输入命令:1-按照名称查找图书;2-按照序号查找图书");
try{
int order=input.nextInt();
if(order!=1&&order!=2)
throw new Exception("请按提示输入数字"); //括号内不必写入内容
if(order==1){
System.out.println("请输入图书名称:");
String s1=input.next();
System.out.println(s1);
for(int i=0;i<book.length;i++){
if(book[i].equals(s1)){
System.out.println("有这本书:"+book[i]);
break;
}
if(i==book.length-1)
System.out.println("图书不存在!");
}
}
else{
System.out.println("请输入图书序号:");
int num=input.nextInt();
if(num>book.length){
System.out.println("图书不存在!");
}
else{
System.out.println("有这本书:"+book[num-1]);
}
}
break;
}
catch(InputMismatchException e){
System.out.println("输入有误,请重新输入!");
//input.next();
}
catch(Exception e){
System.out.println("请按提示输入数字,谢谢合作!");
}
}while(x); //while(true)就行,第10行可以省略
}
}
//还有一些空格缩进问题,写完最好ctrl+shift+f格式化一下在eclipse控制台输入一般换行输入
https://yq.aliyun.com/articles/69327
这是阿里的编程规范,你可以下载参考下
package 模拟借书系统;
import java.util.Scanner;
import java.util.InputMismatchException;
public class rendBook {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String[] book={"语文","数学","英语","政治","历史","地理"};
boolean x=true;
do{
Scanner input=new Scanner(System.in);
System.out.println("请输入命令:1-按照名称查找图书;2-按照序号查找图书");
try{
int order=input.nextInt();
if(order!=1&&order!=2)
throw new Exception("请按提示输入数字");
if(order==1){
System.out.println("请输入图书名称:");
String s1=input.next();
System.out.println(s1);
for(int i=0;i<book.length;i++){
if(book[i].equals(s1)){
System.out.println("有这本书:"+book[i]);
break;
}
if(i==book.length-1)
System.out.println("图书不存在!");
}
}
else{
System.out.println("请输入图书序号:");
int num=input.nextInt();
if(num>book.length){
System.out.println("图书不存在!");
}
else{
System.out.println("有这本书:"+book[num-1]);
}
}
break;
}
catch(InputMismatchException e){
System.out.println("输入有误,请重新输入!");
//input.next();
}
catch(Exception e){
System.out.println("请按提示输入数字,谢谢合作!");
}
}while(x);
}
}举报