如何在不使用零的情况下终止用户输入?

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

How can I terminate user input without using zero?

问题

public static double[] input()
{
    double[] arr = new double[100];
    
    for(int i = 0; i < arr.length; i++)
    {
        System.out.print("插入一个数字,或者输入零以停止:");
        double input = scan.nextDouble();
        arr[i] = input;

        if(input == 0)
        {
            break;
        }
    }
    return arr;
}
英文:

Basically I'm trying to make an method that would return an array so that I can use this list later down the line, only problem is I cant find a way to terminate user input other than using 0. I've tried to take in user input using a string then parsing it into an int but that only results in an error when a non-number character is used.

public static double[] input()
{
    double[] arr = new double[100];
    //int count = 1;

    for(int i = 0; i &lt; arr.length; i++)
    {
        System.out.print(&quot;Insert a number or Zero to stop: &quot;);
        double input = scan.nextDouble();
        arr[i] = input;

        if(input == 0)
        {
            break;
        }
        count++;
    }
    return arr;
}

答案1

得分: 0

我认为,与其使用条件 for(int i = 0; i &lt; arr.length; i++),你可以简单地询问用户希望输入多少位数字,然后将该值传递给 for 循环,以执行类似 for(int i = 0; i &lt; length; i++) 的操作,其中 length 是用户期望的数组大小。

如果你不想询问用户,那么可以将数字作为单个字符输入,而不是作为字符串输入,然后在将其解析为整数之前,只需检查输入的字符是否是转义序列(\n 或 \r) arr[index]=&#39;\n&#39; or&#39;\r&#39;,然后你可以终止输入过程。

注意:此过程仅适用于整数输入,如果用户输入一个字符,程序会将其接受,只需确保输入的字符是一个数字。

我建议将打印语句放在 for 循环之外,因为它将在 for 循环运行的同时重复执行,重复显示这些指令并不好看。

英文:

I think that instead of the condition for(int i = 0; i &lt; arr.length; i++) you could simply ask the user how many digits he/she wishes to enter and then pass that value to the for loop to execute lie for(int i = 0; i &lt; length; i++) where length is the user desired size of array.

If you do not want to ask the user then do this accept the numbers as single characters instead of a string then before parsing it into int just check if the entered character is an escape sequence(\n or \r) arr[index]=&#39;\n&#39; or&#39;\r&#39; then you can terminate the input process.

Note: this process is only for integer input if the user enters a character it accepts it just make sure that the entered character is a number.

I suggest you put the print statement out of the for loop as it will be repeated as long as the for loop runs, it is not nice to have those instructions displayed again and again.

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

发表评论

匿名网友

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

确定