簡體   English   中英

掃描儀和方法的Java異常問題

[英]Java Exception problem with scanner and method

我在 java 中遇到了一些問題,在 while 循環中將掃描儀放在輸出之后。 掃描器掃描要使用的方法,然后當它回到循環開始時重置變量。

我已經嘗試過這個,但沒有找到任何可以理解的解決方案(我對 Java 真的很陌生,這對我來說很難),或者自己解決。 這是完整的代碼(我知道代碼效率不高):

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int con = 1;
        System.out.println("Hey!,welcome to my games!");
        Scanner scanner = new Scanner(System.in);
        String game;
        while (con == 1) {
            System.out.println(
                    "Here Some games i have(Enter the text for the one you want):\nto stop=0\n1)calculator=1\n2)!Soon! Random numbers");
            game = scanner.nextLine();
            calculator();
            scanner.reset();
            System.out.println(game);
//          if(game.equals("0")) {
//              con=0;
//          }
//          else if(game.equals("1")) {

//              System.out.println("Welcome Back!");
//          }
//          else {
//              System.out.println("There is a mistake in your text");
//          }

        }
        scanner.close();
    }

    static void calculator() {
        int num1, num2, con = 1, stop = 1;
        String op, ad = "add", su = "sub", mul = "multi", di = "div";
        Scanner af = new Scanner(System.in);
        while (con == 1) {
            stop = 1;
            System.out.println("Write number 1");
            num1 = af.nextInt();
            System.out.println("Write number 2");
            num2 = af.nextInt();
            System.out.println(
                    "Write an operation (one of these):\nAddition=add\nSubtraction=sub\nMultiplication=multi\nDivision=div");
            op = af.next();
            op = op.toLowerCase();
            int minus = num1 - num2;
            int plus = num1 + num2;
            if (op.equals(ad)) {
                System.out.println("The Operation is:Addition\n" + num1 + "+" + num2 + "=" + plus);
            } else if (op.equals(su)) {
                System.out.println("The Operation is:Subtraction\n" + num1 + "-" + num2 + "=" + minus);
            } else if (op.equals(mul)) {
                System.out.println("The Operation is:Multiplication\n" + num1 + "*" + num2 + "=" + num1 * num2);
            } else if (op.equals(di)) {
                System.out.println("The Operation is:Division\n" + num1 + "/" + num2 + "=" + num1 / num2);
            } else {
                System.out.println("Um,Did you make a mistake in your text?\nDo you want the calculator again?");
                String yn = af.next();
                yn = yn.toLowerCase();
                if (yn.equals("yes") || yn.equals("yep")) {
                    stop = 0;
                }
            }
            if (stop == 1) {
                con = 0;
            }
        }
        af.close();
    }
}

        

如您所見,我嘗試自己解決它,甚至對一些代碼進行了注釋,但是當它運行到該方法並返回時,它失敗了,因為掃描儀認為在我寫一些東西之前有一些東西要掃描。 這是例外-

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1478)
    at Main.main(Main.java:12)
  1. 如果輸入無效,您需要一種回送機制(即要求用戶再次輸入數據)。 最常見的方法之一是使用do-while循環,它保證至少執行一次其主體。 查看本教程以了解更多信息。
  2. 使用Scanner::nextLine而不是Scanner::nextScanner::nextInt等,因為它們不使用輸入中通過按Enter鍵創建的換行符。 查看此討論以了解更多信息。
  3. 最后但並非最不重要的一點是,永遠不要關閉System.inScanner ,因為它也會關閉System.in並且無法在不重新啟動 JVM 的情況下再次打開它。 注意:如果您使用Scanner掃描File ,請確保關閉它以釋放資源。

演示:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int option;
        boolean valid;
        Scanner input2 = new Scanner(System.in);
        do {
            valid = true;
            System.out.println("Choose an option:\n" + "1-Addition\n" + "2-Subtraction\n" + "3-Exit");
            try {
                option = Integer.parseInt(input2.nextLine());
                if (option < 1 || option > 3) {
                    throw new IllegalArgumentException();
                }
                // ...Place here the rest of code (which is based on the value of option)
            } catch (IllegalArgumentException e) {
                System.out.println("This is an invalid entry. Please try again.");
                valid = false;
            }
        } while (!valid);
    }
}

示例運行:

Choose an option:
1-Addition
2-Subtraction
3-Exit
x
This is an invalid entry. Please try again.
Choose an option:
1-Addition
2-Subtraction
3-Exit
10.5
This is an invalid entry. Please try again.
Choose an option:
1-Addition
2-Subtraction
3-Exit
1

你記得導入 java.util.Scanner 嗎? 或者你如何編譯你的源文件? 用 gradle 編譯時我有同樣的錯誤消息,我在 gradle 構建文件中遺漏了一小行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM