[英]Reading multiple lines in java using scanner
I am trying to read in a sample input: 我正在尝试阅读示例输入:
3 //amount of games
//Game 1
2 2 //questions lies
bird 1 s //bird 1 a swan?
yes //answer
bird 2 d //bird 2 a duck?
no //answer
3 1
total d 4 and total g 7
yes
bird 1 s and bird 2 d and bird 3 s
yes
bird 1 g or bird 4 g
yes
2 0
total d 1
yes
bird 6 s or bird 1 d
yes
How can I read this input in terms of based on the integer there are 3 Games that we are going to do. 我将如何阅读基于整数的输入,我们将要做3个游戏。 I need to store everything and then go from there. 我需要存储所有内容,然后从那里去。
This is what I have so far, I am hoping I am on the right track 这是我到目前为止所拥有的,希望我走在正确的轨道上
public class Solution {
public static void main(String[] arg){
Scanner input = new Scanner(System.in);
int Games = Integer.parseInt(input.nextLine());
for(int i = 0; i == Games; i++){
//go through game 1 and store them
//repeat until game 3
}
}
}
I would recommend using Scanner.next()
instead of Scanner.nextLine()
so you can read single word/number at a time. 我建议使用Scanner.next()
而不是Scanner.nextLine()
以便您一次可以读取单个单词/数字。 Your for loop is wrong you need to change it to: 您的for循环是错误的,您需要将其更改为:
for (int i = 0; i < Games; i++)
// or you can also use
while (Games-- > 0)
I prefer the while loop because you don't want to keep track of the loop number. 我更喜欢while循环,因为您不想跟踪循环号。
For example: 例如:
public class Solution {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in))
int games = Integer.parseInt(input.next());
// loop for games
while (games-- > 0) {
int questions = Integer.parseInt(input.next());
int lie = Integer.parseInt(input.next());
// loop for questions
while (questions-- > 0) {
// do whatever logic you want to do and print the answer
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.