【问题标题】:Inf While Loop when given incorrect input输入不正确时的 Inf While 循环
【发布时间】:2021-11-09 00:36:08
【问题描述】:

程序概述:向用户询问短语,询问用户一个索引,其中一个打乱将旋转短语,直到索引处的字母是字符串的第一个索引 (0)。要求一个整数,直到给出一个整数。词组打乱后要求再打乱。如果是,则打乱输入的索引,如果不是,打印最终结果结束程序。

代码:

import java.util.Scanner;


public class PJ {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String phrase;
        String phraseMut;
        int index = 0;

        System.out.println("Enter your word or phrase: ");
        phrase = scan.nextLine();
        phraseMut = phrase;
        System.out.println();

        while (true) {
            System.out.println("Enter an Integer: ");
            if (scan.hasNextInt()) {
                index = scan.nextInt();
                scan.nextLine();
                break;
            } else if (index > phraseMut.length()) {
                System.out.println("Error: Index is out of bounds.");
                System.out.println("Please enter an integer value.");
            } else {
                System.out.println("Error: Index is not Integer.");
            }
        }

        System.out.println();
        System.out.println("Rotating phrase to bring index "+index+" to the front. . .");

        int count =0;
        for(int i = 0; i < index; i++){
            phraseMut = phraseMut.substring(1,phrase.length())+""+phraseMut.substring(0,1);
            count++;
            System.out.println(phraseMut);
        }
    }

}

问题:while 循环无限运行,但我需要它做的是检查它是否为整数,如果是,则离开循环并继续。如果它不是一个整数,则继续请求输入,直到它成为一个整数,如果整数在索引范围内,则与此相同。

【问题讨论】:

    标签: java loops


    【解决方案1】:

    扫描仪实际上并不是为键盘输入而设计的,但您可以使用它。当您调用hasNextInt(),并且下一个标记是“hello”时,hasNextInt() 会完全按照它在其 javadoc 中所说的那样:它断定下一个标记不是 int,并告诉您。 就是这样。它确实消耗那个“你好”,所以,如果hasNextInt()返回一次false,它会永远这样做,至少直到你'消耗'令牌。

    其次,您希望通过单次回车键将键盘输入分开,但扫描仪没有为此开箱即用地正确配置。通过不时调用scan.nextLine(),您正在严重破解它。这是不好的;这意味着如果用户曾经触摸空格键(你知道,键盘上最大的键),所有的地狱都会崩溃,因为你现在在这些下一行不同步,并且也无法读取空白输入。

    that 的修复方法是告诉扫描仪您正在使用它进行键盘输入 - 您希望条目由输入键分隔。为此,在制作扫描仪后立即调用.useDelimiter("\\R")(即:换行符,在正则表达式中)。然后,永远不要调用.nextLine() - 要读取整行,调用.next()。所有输入都是整行(在输入相同的数字后按“回车”)。

    因此:

    • 致电.useDelimiter("\\R")
    • 删除所有 nextLine() 呼叫您插话。
    • 如果你想要一个实际的线路,使用.next(),而不是nextLine()
    • 如果 hasNextInt() 返回 false,则通过调用 .next() 并忽略其返回值来使用令牌。

    【讨论】:

      猜你喜欢
      • 2013-01-17
      • 2013-09-06
      • 2016-01-11
      • 2020-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多