How to use try catch to replace invalid data of user input array instead of restarting code in Java?

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

How to use try catch to replace invalid data of user input array instead of restarting code in Java?

问题

import java.util.Scanner;

public class Array {
  public static void main(String args[]) {
    int z = 1;
    do {
      try {
        Scanner scanner = new Scanner(System.in);

        double[] myArr1 = new double[10];  // 创建数组
        System.out.println("");
        System.out.println("输入 10 个元素:");
        System.out.println("");

        for (int x = 0; x < myArr1.length; x++) {
          myArr1[x] = scanner.nextDouble();  // 获取用户输入
        }  // 循环结束

        double sum1 = 0;
        for (double x = 0; x < myArr1.length; x++) {
          sum1 += myArr1[(int) x];  // 计算 sum1
        }  // 循环结束

        double[] myArr2 = new double[10];  // 创建数组
        System.out.println("输入 10 个元素:");
        System.out.println("");

        for (int y = 0; y < myArr2.length; y++) {
          myArr2[y] = scanner.nextDouble();  // 获取用户输入
        }  // 循环结束

        double sum2 = 0;
        for (double y = 0; y < myArr2.length; y++) {
          sum2 += myArr2[(int) y];
        }  // 循环结束
        System.out.println("前 10 个元素的和为:" + sum1);  // 打印前 10 个元素的和
        System.out.println("后 10 个元素的和为:" + sum2);  // 打印后 10 个元素的和

      }/*try 结束*/ catch (Exception e) {  // 捕捉用户输入错误
         System.out.println("无效的输入。请重试:");
         System.out.println("");
      }  // 捕捉结束
    }  // do 结束
    while (z == 1);
    return;
  }
}
英文:

Whenever invalid input is entered, such as a letter, the code starts from the beginning. How do I get it so that it keeps rebuilding the code from where invalid input was entered. I want it to kick out the invalid input, and prompt the user to re-enter a valid input, and keep building it.

import java.util.Scanner;
public class Array {
public static void main(String args[]) {
int z = 1;
do {
try {  
Scanner scanner = new Scanner(System.in);
double[] myArr1 = new double[10];  //Creates array
System.out.println(&quot;&quot;);
System.out.println(&quot;Enter 10 elements: &quot;);
System.out.println(&quot;&quot;);
for (int x=0; x&lt;myArr1.length; x++) {
myArr1[x] = scanner.nextDouble();  //Gets user input
}  //end of for
double sum1 = 0;
for(double x=0; x&lt;myArr1.length; x++) {
sum1 += myArr1[(int) x];  //Defines sum1
}  //end of for
double[] myArr2 = new double[10];  //Creates array
System.out.println(&quot;Enter 10 elements: &quot;);
System.out.println(&quot;&quot;);
for (int y=0; y&lt;myArr2.length; y++) {
myArr2[y] = scanner.nextDouble();  //Gets user input
}  //end of for
double sum2 = 0;
for (double y=0; y&lt;myArr2.length; y++) {
sum2 += myArr2[(int) y];
}  //end of for
System.out.println(&quot;Sum of first 10 elements is: &quot; + sum1);  //Prints sum of first 10 elements
System.out.println(&quot;Sum of second 10 elements is: &quot; + sum2);  //Prints sum of last 10 elements
}/*end of try*/catch (Exception e) {  //Catches errors in user input
System.out.println(&quot;Invalid input. Try again: &quot;);
System.out.println(&quot;&quot;);
}  //end of catch
}//end of do
while(z==1);
return;
}
}

答案1

得分: 1

你可以为输入编写一个辅助方法。它将不断使用提供的消息提示,直到输入正确的类型为止。当需要从程序中的不同位置获取输入时,这通常会非常方便。

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    double v = nextDouble(input, "请输入一个值:", "类型不正确,请重试:");
    System.out.println(v);
}

public static double nextDouble(Scanner input, String prompt, String error) {
    System.out.print(prompt);
    // 无限循环
    for (;;) {
        try {
            double v = input.nextDouble();
            return v;
        } catch (InputMismatchException ie) {
            input.nextLine(); // 清空输入缓冲区
            System.out.print(error);
        }
    }
}

这是你代码中的一个示例。

Scanner scanner = new Scanner(System.in);
String prompt = "请输入一个数字:";
String error = "输入无效,请重试";

double[] myArr1 = new double[10]; // 创建数组
System.out.println("");
System.out.println("输入10个元素:");
System.out.println("");

for (int x = 0; x < myArr1.length; x++) {
    myArr1[x] = nextDouble(scanner, prompt, error);
} // 结束循环

double sum1 = 0;
for (double x = 0; x < myArr1.length; x++) {
    sum1 += myArr1[(int) x]; // 定义sum1
} // 结束循环

移除你现有的 try/catch 块。我不知道为什么你有一个 do/while,因为你不需要循环超过一次。

英文:

You can craft a helper method for input. It will continually prompt with the messages provided until a correct type is entered. This tends to come in handy when inputs need to be taken from different locations within the program.

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double v = nextDouble(input, &quot;Please enter a value: &quot;, &quot;Improper type, try again: &quot;);
System.out.println(v);
}
public static double nextDouble(Scanner input, String prompt, String error) {
System.out.print(prompt);
// loop forever
for(;;) {    
try {
double v = input.nextDouble();
return v;
} catch (InputMismatchException ie) {
input.nextLine(); // clear input buffer
System.out.print(error);
}
}
}

Here is an example from your code.

Scanner scanner = new Scanner(System.in);
String prompt = &quot;Please enter a number: &quot;;
String error = &quot;Invalid input, try again&quot;;
double[] myArr1 = new double[10]; // Creates array
System.out.println(&quot;&quot;);
System.out.println(&quot;Enter 10 elements: &quot;);
System.out.println(&quot;&quot;);
for (int x = 0; x &lt; myArr1.length; x++) {
myArr1[x] = nextDouble(scanner, prompt, error);
} // end of for
double sum1 = 0;
for (double x = 0; x &lt; myArr1.length; x++) {
sum1 += myArr1[(int) x]; // Defines sum1
} // end of for

Get rid of your existing try/catch blocks. And I don't know why you have a do/while since you aren't looping more than once.

答案2

得分: 0

或者您可以使用 while 循环和布尔值来获取一个数字

Scanner scanner = new Scanner(System.in);
boolean bool = true;
double d; // = scanner.nextDouble();
while (bool) {
    try {
        scanner = new Scanner(System.in);
        d = scanner.nextDouble();
        bool = false;
    } catch (InputMismatchException e) {
        System.err.println("无效输入");
    }
}
英文:

or you can using while loop and a boolean value to get a number

Scanner scanner = new Scanner(System.in);
boolean bool = true;
double d ;//= scanner.nextDouble();
while(bool){
try{ 
scanner = new Scanner(System.in);
d = scanner.nextDouble();
bool = false; 
}catch(InputMismatchException e){
System.err.println(&quot;invalid input&quot;);
}
}

答案3

得分: 0

我已经弄清楚了。我必须创建一个布尔变量,同时减少数组索引的值,这个数组是坏输入被放置的地方(i = i-1)。我还将它只设置为一个数组,并将前10个值设置为x,最后10个值设置为y,以使它变得更简单。

import java.util.Scanner;

public class Array {
    public static void main(String[] args) {
        double[] array = new double[20];  //创建数组
        boolean on = true;  //设置值为“on”

        while (on) {  //开始while循环
            System.out.println("输入20个数字:");
            System.out.println("");

            for (int i = 0; i < array.length; i++) {  //创建用户输入提示
                Scanner input = new Scanner(System.in);  //获取用户输入

                try {
                    array[i] = input.nextDouble();  //将用户输入赋值给array[i]
                } catch (Exception e) {  //捕捉无效输入
                    System.err.println("无效输入。请重试:");
                    i = i - 1;  //减少重新输入数字的索引
                }
            }

            double x = 0;
            for (int z = 0; z < 10; z++) {
                x += array[z];
            }
            System.out.println("前10个数字的总和 = " + x);  //将数组中前10个数字相加并赋值给x

            System.out.println("");

            double y = 0;
            for (int z = 10; z < 20; z++) {
                y += array[z];
            }
            System.out.println("后10个数字的总和 = " + y);  //将数组中后10个数字相加并赋值给y

            on = false;  //退出while循环
        }
    }
}
英文:

I've figured it out. I had to create a boolean, but also decrement the index of the array of where the bad input was being placed (i = i-1). I also made it just one array and set the first 10 values to x and the last 10 to y to make it a little bit simpler.

import java.util.Scanner;
public class Array {
public static void main(String[] args) {
double[] array = new double[20];  //creates array
boolean on = true;  //sets value &quot;on&quot;
while (on) {  //starts while loop
System.out.println(&quot;Enter 20 numbers: &quot;);
System.out.println(&quot;&quot;);
for (int i = 0; i &lt; array.length; i++) {  //creates user input prompt
Scanner input = new Scanner(System.in);  //gets user input
try {
array[i] = input.nextDouble();  //assigns user input to array[i]
}/*end of try*/ catch (Exception e) {  //catches invalid input
System.err.println(&quot;Invalid Input. Try again: &quot;);
i = i - 1;  //decrements index of re-entered number
}  //end of catch
}  //end of for
double x = 0;
for (int z = 0; z &lt; 10; z++) {
x += array[z];
}  //end of for
System.out.println(&quot;Sum of first 10 numbers = &quot; + x);  //adds first 10 numbers in array and assigns them to x
System.out.println(&quot;&quot;);
double y = 0;
for (int z = 10; z &lt; 20; z++) {
y += array[z];
}  //end of for
System.out.println(&quot;Sum of last 10 numbers = &quot; + y);  //adds last 10 numbers in array and assigns them to y
on = false;  //breaks while loop
}  //end of while
}
}

huangapple
  • 本文由 发表于 2020年9月29日 22:28:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64121700.html
匿名

发表评论

匿名网友

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

确定