【问题标题】:why loop iteration range given by keyboard count itself as an iteration?为什么键盘给出的循环迭代范围本身算作一次迭代?
【发布时间】:2018-07-19 13:20:51
【问题描述】:
public class P7 {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int range=scanner.nextInt();
        for(int i=1;i<=range;i++){
            String stringInput =scanner.nextLine();
            String[] total =stringInput.split("\\s");
            int length=total.length;
            System.out.println(length);
        } 
    }
}

如果您输入范围为 3,它将打印其长度为 1。但第一次迭代应在获取 stringInput 后​​打印长度。 此外,当您将范围输入为字符串时,您会得到 InputMismatchException。哪个是对的。那么问题出在哪里? 谢谢。

【问题讨论】:

标签: java string loops split iteration


【解决方案1】:

Scanner.nextInt() 只消耗您输入的数字并将“\n”留在扫描仪缓冲区中。您可以在调用Scanner.nextInt() 后立即使用Scanner.next() 清除该缓冲区。

import java.util.Scanner;

public class StackOverflow {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int range=scanner.nextInt();
        scanner.next();

        for(int i=1;i<=range;i++){
            String stringInput =scanner.nextLine();
            String[] total =stringInput.split("\\s");
            int length=total.length;
            System.out.println(length);
        }

        scanner.close();
    }
}

结果:

3
The asdfj
2
asldkja sfaslkj asdfljk
3
asdfjk asdfjlkasdf alksjdf asdflkj
4

【讨论】:

    猜你喜欢
    • 2017-10-13
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多