简体   繁体   English

在for循环中循环执行else语句?

[英]Looping an else statement inside a for loop?

In this script, the user must input 5 numbers separated by new lines. 在此脚本中,用户必须输入5个数字,并用新行分隔。 The purpose is to check whether the input is an integer or not, and if it isn't, then it should theoretically loop, asking the user to input a valid integer . 目的是检查输入是否为整数,如果不是,则理论上应进行循环,要求用户输入有效的integer

The first part works - if the user inputs a value which isn't an integer, it throws the error and asks them to input a valid integer. 第一部分有效-如果用户输入的值不是整数,则会引发错误并要求他们输入有效的整数。 But if they enter an invalid integer again, it throws an exception, which I don't want it to do. 但是,如果他们再次输入无效的整数,则会引发异常,我不希望这样做。 I want it to loop the else statement until the input is an integer. 我希望它循环else语句,直到输入为整数为止。

I tried embedding a while loop within the else statement but it started getting messy and I couldn't figure out how to work it. 我试图在else语句中嵌入一个while循环,但是它开始变得混乱,无法弄清楚该如何使用它。 Any help would be appreciated. 任何帮助,将不胜感激。

import java.util.*; 
import java.util.concurrent.TimeUnit;
public class NumbersArray
{
    int[] numbers = new int[5]; // Defines new array string with length of 5 characters
    Scanner sc = new Scanner(System.in);
    int length = numbers.length; // Defines length int, calculates how many in numbers int

    public void inputToNumbers()
    {
        for(int i=0; i<length; i++) // Declares i as 0, while i less than length loop runs. Increments each time
        {
            System.out.println("Input five whole numbers, separated by new lines:" + " (" + (i+1) + "/5)");
            String inputtedNums; // Declares inputtedNums string
            inputtedNums = sc.nextLine(); // Inserts input
            if (inputtedNums.matches("[0-9]+")) // Checks if the input is numbers only
            {
                numbers[i] = Integer.parseInt(inputtedNums); // Parses string input into integer numbers
            }
            else
            {
                System.out.println("Error! You inputted an invalid number, try again." + " (" + (i+1) + "/5)");
                inputtedNums = sc.nextLine(); // Takes user input
                numbers[i] = Integer.parseInt(inputtedNums); // Parses string input into integer numberS        
            }
        }
    }

    public void printTheNumbers()
    {
        for(int x=0; x<length; x++)
        {
            System.out.println(numbers[x]);
        }
    }

    public static void main(String[] args)
    {
        NumbersArray na = new NumbersArray();
        na.inputToNumbers();
        na.printTheNumbers();
    }
}

I think this will work fine. 我认为这会很好。

public void inputToNumbers()
    {
        for(int i=0; i<length; i++) // Declares i as 0, while i less than length loop runs. Increments each time
        {
            System.out.println("Input five whole numbers, separated by new lines:" + " (" + (i+1) + "/5)");
            String inputtedNums; // Declares inputtedNums string
            inputtedNums = sc.nextLine(); // Inserts input
            while (inputtedNums.matches("^-?[^\\d]+$")) // Checks if the input is not number 
            {
                System.out.println("Error! You inputted an invalid number, try again." + " (" + (i+1) + "/5)");
                inputtedNums = sc.nextLine();

            }
            numbers[i] = Integer.parseInt(inputtedNums);
            // Parses string input into integer numbers
        }
    }

My concern is that whether negative integers are allowed or not? 我担心的是是否允许使用负整数? I have included an optional negative number case. 我包括一个可选的负数案例。 See working code here : https://ide.geeksforgeeks.org/fzy9sHCGtz 在此处查看工作代码: https : //ide.geeksforgeeks.org/fzy9sHCGtz

Regex Test : https://regex101.com/r/KKrpUu/1 正则表达式测试: https : //regex101.com/r/KKrpUu/1

To expand on my comment, you can simplify your code this way: 为了扩展我的评论,您可以通过以下方式简化代码:

Create an other method just to read a number from the console input and you can then call it again until you get an actual number. 创建另一个方法只是从控制台输入中读取数字,然后可以再次调用它,直到获得实际数字为止。 This replaces looping with recursion 这将循环替换为递归

public void inputToNumbers()
{
    int[] numbers = new int[5];
    for(int i=0; i<numbers.length; i++) {
        System.out.println("Input five whole numbers, separated by new lines:" + " (" + (i+1) + "/5)");
        numbers[i] = readNextnumber();
    }
}

private int readNextnumber() {
    Scanner sc = new Scanner(System.in);
    String inputtedNum = sc.nextLine();
    if(!inputtedNum.matches("[0-9]+")) {
        System.out.println("Error! You inputted an invalid number, try again.");
        return readNextnumber();
    } else {
        return Integer.parseInt(inputtedNum);
    }
}

Courtesy of @Bentaye, I added the following to my else statement: 感谢@Bentaye,我在else语句中添加了以下内容:

        else
        {
            while(!inputtedNums.matches("[0-9]+"))
            {
                System.out.println("Error! You inputted an invalid number, try again." + " (" + (i+1) + "/5)");
                inputtedNums = sc.nextLine(); // Takes user input
            }
            numbers[i] = Integer.parseInt(inputtedNums); // Parses string input into integer numberS        
        }

And this worked perfectly. 这完美地工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM