使用扫描仪在Java中读取多行

时间:2018-09-02 23:51:54

标签: java input java.util.scanner

我正在尝试读取示例输入:

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

我该如何阅读基于整数的输入,我们将要做3个游戏。我需要存储所有东西,然后从那里去。

这是我到目前为止所拥有的,希望我走在正确的轨道上

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
        }

    }
}

1 个答案:

答案 0 :(得分:0)

我建议您使用Scanner.next()而不是Scanner.nextLine(),以便您一次可以读取一个单词/数字。您的for循环是错误的,您需要将其更改为:

for (int i = 0; i < Games; i++)
// or you can also use
while (Games-- > 0)

我更喜欢while循环,因为您不想跟踪循环号。

例如:

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
            }
        }
    }
}