问题描述:
String another = "y";
Scanner scan = new Scanner(System.in);
while (another.equalsIgnoreCase("y")) {
System.out.println("请输入年份:");
int year = scan.nextInt();
System.out.println("是否再次测试(Y/N)");
another=scan.nextLine();System.out.println(another+"测试");}
当我这样写输出是否再次测试(Y/N)可是我却无法输入任何东西,于是输出变量another ,发现变量改变,此时another="\n";
解决方法:
.nextLine();不能放在in.nextInt();代码段后面
否则.nextLine();会读入"\n"字符,但"\n"并不会成为返回的字符,将\n认为键入的字符!!!
方案一:
在another前加一个变量ch用于接收"\n"
String ch=scan.nextLine();
System.out.println("是否再次测试(Y/N)");
another=scan.nextLine();
方案二:
使用.next()
System.out.println("是否再次测试(Y/N)");another=scan.next();next();这个函数会扫描从有效字符起到空格,Tab,回车等结束字符之间的内容并作为String返回。nextLine();这个函数在你输入完一些东西之后按下回车则视为输入结束,输入的内容将被作为String返回。
next();这个函数与之不同在于,next();什么都不输入直接敲回车不会返回,而nextLine()即使不输入东西直接敲回车也会返回。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// abc 123 def 456
String str1 = scan.nextLine();System.out.println("str1: "+str1);
String str2 = scan.next();
System.out.println("str2: "+str2);
}