这可能是非常非常基本的,也可能是我完全缺少的东西。我已经开始在在线 channel 上做一些有竞争力的节目。我必须读取逗号分隔的字符串并对其进行一些操作,但问题是我不知道输入的行数。下面是输入示例
输入 1
John,Jacob
Lesley,Lewis
Remo,Tina
Brute,Force
输入 2
Hello,World
Java,Coder
........
........
//more input lines
Alex,Raley
Michael,Ryan
我正在尝试读取输入并在遇到行尾时中断但没有运气。这是我一直在尝试的
//1st method
Scanner in = new Scanner(System.in);
do{
String relation = in.nextLine();
//do some manipulation
System.out.println(relation);
}while(in.nextLine().equals("")); //reads only first line and breaks
//2nd method
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String relation = in.next();
System.out.println(relation);
if(relation.equals("")){
break;
}
}
//3rd method
Scanner in = new Scanner(System.in);
while(true){ //infinite loop
String relation = in.nextLine();
System.out.println(relation);
if(relation.equals("")){
break;
}
}
有人可以帮忙吗
PS:请不要评判。尽管我知道如何在 Java 中获取用户输入以及 next() 和 nextLine() 之间的区别,但我是竞争性编程的新手。
最佳答案
我不会写为什么你不应该使用 Scanner
.有很多文章为什么你不应该使用 Scanner
在竞争性编程中。而是使用 BufferedReader
.
在竞争性编程中,他们将输入从文件重定向到您的代码。
它的工作原理类似于 ./a.out > output.txt < input.txt
例如。
如此读取直到在while循环中检测到null。
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
while((s = br.readLine()) != null)
{
//System.out.println(s);
}
}
通过键盘进行测试,模拟 null
从你的键盘:
按 Ctrl+D。它会突破while
循环以上。
关于Java:在不知道输入行数的情况下读取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46434391/