Loop 和 Try/Catch 内的 Scanner.nextLine 跳过询问输入

在尝试这些读取 int 输入的建议后,扫描仪在使用 next() 或 nextFoo() 之后跳过 nextLine() 吗?

无法弄清楚输入为什么不消耗换行符。

这是运行jdk 11的linux。

import java.util.Scanner;


public class NumbFile {


    public static void main(String[] args) throws Exception {

        int i = 100;

        int powerNumber;

        boolean status = true;


            do {

                try {

                    System.out.print("Type a number: ");

                    Scanner sc = new Scanner(System.in);

                    powerNumber = Integer.parseInt(sc.nextLine());

                    System.out.println(i * powerNumber);

                    sc.close();

                } catch (NumberFormatException exc) {

                    exc.printStackTrace();

                    status = false;

                }


            } while(status);

    }

}

这应该仅在没有 int 输入的情况下停止循环。


大话西游666
浏览 161回答 1
1回答

暮色呼如

删除sc.close();. 这会关闭你的Scanner(应该在循环之前声明一次),但它也会关闭System.in(你不能重新打开它)。int i = 100;boolean status = true;Scanner sc = new Scanner(System.in);do {    try {        System.out.print("Type a number: ");        int powerNumber = Integer.parseInt(sc.nextLine());        System.out.println(i * powerNumber);    } catch (NumberFormatException exc) {        exc.printStackTrace();        status = false;    }} while (status);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java