如何使 while 循环正常工作?

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

How can have the while loop working properly?

问题

public static int userInput() {
    Scanner scanner = new Scanner(System.in);

    int enteredValue = -8;
    while (enteredValue != 8) {
        try {
            enteredValue = scanner.nextInt();
            if (enteredValue < 0) {
                throw new InputMismatchException();
            }
        } catch (InputMismatchException e) {
            System.out.println("Invalid interger entered");
            enteredValue = -8;
        }
        break;
    }
    scanner.nextLine();
    return enteredValue;
}
英文:
public static int userInput() {
    Scanner scanner = new Scanner(System.in);

	int enteredValue = -8;
	while (enteredValue !=8) {
	    try {
		    enteredValue = scanner.nextInt();
		    if (enteredValue &lt; 0) {
			    throw new InputMismatchException();
		    }
	    } catch (InputMismatchException e) {
		    System.out.println(&quot;Invalid interger entered&quot;);
			enteredValue = -8;
	    }
        break;
    }
	scanner.nextLine();
	return enteredValue;
}

答案1

得分: 0

如果像billjamesdev建议的那样,目的是让用户输入一个非负整数,那么代码可以变得更简单。

不需要使用-8的那些奇技淫巧,

public static int userInput() {
    Scanner scanner = new Scanner(System.in);

    int enteredValue = -8; // 仅用于启动循环
    while (enteredValue < 0) {
        try {
            enteredValue = scanner.nextInt();
            if (enteredValue < 0)
                System.out.println("输入了负整数");
        }
        catch (InputMismatchException ex) {
            System.out.println("输入了无效的整数");
            scanner.nextLine(); // 清除输入
       }
    }
    scanner.nextLine();
    return enteredValue;
}

注意:与其在负数输入时抛出异常,我选择直接报告错误,因为这使我能够使用更具体的消息。

一个微妙之处在于,如果抛出了异常,那么enteredValue上就不会发生赋值,因此它仍然是负数,因为它与循环顶部的值保持不变。

使用do-while循环似乎并没有在可读性方面增加太多好处,所以我将其保留为while循环。

英文:

If, as billjamesdev suggests, the point is to get the user to enter a non-negative integer, the code can be made simpler.

None of that magic with -8 is needed, and

public static int userInput() {
    Scanner scanner = new Scanner(System.in);

    int enteredValue = -8; // just to get loop started
    while (enteredValue &lt; 0) {
        try {
            enteredValue = scanner.nextInt();
            if (enteredValue &lt; 0)
                System.out.println(&quot;Negative integer entered&quot;);
        }
        catch (InputMismatchException ex) {
            System.out.println(&quot;Invalid integer entered&quot;); 
            scanner.nextLine(); // clear input
       }
    }
    scanner.nextLine();
    return enteredValue;
}

Note: rather than throwing an exception on negative input, I chose to just report the error directly, since this allows me to use a more specific message.

A subtlety is that if the exception is thrown, then no assignment to enteredValue can have occurred, and therefore it is still negative, since it is unchanged from the top of the loop.

Using a do-while loop didn't seem to add much to readability, so I left it as a while-loop.

huangapple
  • 本文由 发表于 2020年9月20日 03:00:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63972394.html
匿名

发表评论

匿名网友

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

确定