使用 try catch 在一个 while 循环中 (Java)

huangapple go评论74阅读模式
英文:

using try catch in a while loop (java)

问题

import java.util.InputMismatchException;
import java.util.Scanner;

public class Numbers {
    public static void main(String[] args){
        number();
    }
    
    public static int number() {
        System.out.print("Enter a number: ");
        Scanner readLine = new Scanner(System.in);
        boolean isInteger = false;
        
        while (!isInteger) {
            try {
                int numbers = readLine.nextInt();
                System.out.println(numbers);
                isInteger = true;
            } catch (InputMismatchException e) {
                System.err.println("Not a valid input. Error: " + e.getMessage());
            }
        }

        return 0;
    }
}
英文:

I wanted to write a simple program that asks for a number, if the user inputs a number it will end, otherwise it will print an error and ask again for a number. The problem is that my program just keeps printing the error message ("Not a valid input. Error :null") and never asks for a number again.

import java.util.InputMismatchException;
import java.util.Scanner;


public class Numbers {
    public static void main(String[] args){
        number();

    }
    public static int number() {
        System.out.print("Enter a number: ");
        Scanner readLine = new Scanner(System.in);
        boolean isInteger = false;
        while (!isInteger) {
            try {
                int numbers = readLine.nextInt();
                System.out.println(numbers);
                isInteger = true;
            } catch (InputMismatchException e) {
                System.err.println("Not a valid input. Error :" + e.getMessage());
            }

        }

        return 0;
    }
}

答案1

得分: 1

        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            if (sc.hasNextInt()) {
                int number = sc.nextInt();
                System.out.println(number);
            } else {
                System.err.println("不是有效的输入。错误:" + sc.next());
            }
        }
英文:
    Scanner sc = new Scanner(System.in);
    while (sc.hasNext()) {
        if (sc.hasNextInt()) {
            int number = sc.nextInt();
            System.out.println(number);
        } else {
            System.err.println("Not a valid input. Error :" + sc.next());
        }
    }

huangapple
  • 本文由 发表于 2020年10月16日 19:19:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/64388140.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定