这回我不按空格隔开输入了,我要每行输入一个,怎么结束循环呢?
哎,只能每行当做字符串输入,最后一行碰到输入的那一行为空,结束循环。这样造成的结果就是最后会留出一个空行然后结束。尴尬也没办法。
// 每行输入一个字符串,输入多个字符串
public static void inputStr() {
Scanner scanner = new Scanner(System.in);
String nextLine = scanner.nextLine();
while (nextLine != null && !nextLine.equals("")) {
System.out.println(nextLine);
nextLine = scanner.nextLine();
}
System.out.println("end of input string");
}
那么比赛时这个就不适用了,可能是因为算法题目中用的是流的方式进行输入,最后不会输入多一个换行符,因而无法正确的结束输入而导致答案错误。
那么比赛请这么做吧,
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(in.hasNext()){
String str = sc.nextLine();
System.out.println(str);
}
}
}
最后想说一下nextInt、nextFloat方法不会接收回车符(13)、换行符(10),因此如果在nextInt()后增加nextLine()方法,对于nextInt()输入时的回车符(13)、换行符(10)会被nextLine()接收。造成可能你想用nextLine接收一个你想要的串,结果却接收到了\r\n。详细请看:https://blog.youkuaiyun.com/claram/article/details/52057562