rog*_*hat 3 java input java.util.scanner
这可能是非常非常基本的,或者可能是我完全缺少的东西。我已经开始在在线频道上做一些竞争性的节目。我必须读取逗号分隔的字符串并对其进行一些操作,但问题是我不知道输入的行数。下面是输入示例
输入1
John,Jacob
Lesley,Lewis
Remo,Tina
Brute,Force
Run Code Online (Sandbox Code Playgroud)
输入2
Hello,World
Java,Coder
........
........
//more input lines
Alex,Raley
Michael,Ryan
Run Code Online (Sandbox Code Playgroud)
我正在尝试读取输入并在遇到行尾时中断,但没有运气。这就是我一直在尝试的
//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;
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
要通过键盘进行测试,请null从键盘模拟:
按Ctrl+ D。它将跳出while上面的循环。
| 归档时间: |
|
| 查看次数: |
7349 次 |
| 最近记录: |