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

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

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

问题

  1. import java.util.Scanner;
  2. public class Array {
  3. public static void main(String args[]) {
  4. int z = 1;
  5. do {
  6. try {
  7. Scanner scanner = new Scanner(System.in);
  8. double[] myArr1 = new double[10]; // 创建数组
  9. System.out.println("");
  10. System.out.println("输入 10 个元素:");
  11. System.out.println("");
  12. for (int x = 0; x < myArr1.length; x++) {
  13. myArr1[x] = scanner.nextDouble(); // 获取用户输入
  14. } // 循环结束
  15. double sum1 = 0;
  16. for (double x = 0; x < myArr1.length; x++) {
  17. sum1 += myArr1[(int) x]; // 计算 sum1
  18. } // 循环结束
  19. double[] myArr2 = new double[10]; // 创建数组
  20. System.out.println("输入 10 个元素:");
  21. System.out.println("");
  22. for (int y = 0; y < myArr2.length; y++) {
  23. myArr2[y] = scanner.nextDouble(); // 获取用户输入
  24. } // 循环结束
  25. double sum2 = 0;
  26. for (double y = 0; y < myArr2.length; y++) {
  27. sum2 += myArr2[(int) y];
  28. } // 循环结束
  29. System.out.println("前 10 个元素的和为:" + sum1); // 打印前 10 个元素的和
  30. System.out.println("后 10 个元素的和为:" + sum2); // 打印后 10 个元素的和
  31. }/*try 结束*/ catch (Exception e) { // 捕捉用户输入错误
  32. System.out.println("无效的输入。请重试:");
  33. System.out.println("");
  34. } // 捕捉结束
  35. } // do 结束
  36. while (z == 1);
  37. return;
  38. }
  39. }
英文:

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.

  1. import java.util.Scanner;
  2. public class Array {
  3. public static void main(String args[]) {
  4. int z = 1;
  5. do {
  6. try {
  7. Scanner scanner = new Scanner(System.in);
  8. double[] myArr1 = new double[10]; //Creates array
  9. System.out.println(&quot;&quot;);
  10. System.out.println(&quot;Enter 10 elements: &quot;);
  11. System.out.println(&quot;&quot;);
  12. for (int x=0; x&lt;myArr1.length; x++) {
  13. myArr1[x] = scanner.nextDouble(); //Gets user input
  14. } //end of for
  15. double sum1 = 0;
  16. for(double x=0; x&lt;myArr1.length; x++) {
  17. sum1 += myArr1[(int) x]; //Defines sum1
  18. } //end of for
  19. double[] myArr2 = new double[10]; //Creates array
  20. System.out.println(&quot;Enter 10 elements: &quot;);
  21. System.out.println(&quot;&quot;);
  22. for (int y=0; y&lt;myArr2.length; y++) {
  23. myArr2[y] = scanner.nextDouble(); //Gets user input
  24. } //end of for
  25. double sum2 = 0;
  26. for (double y=0; y&lt;myArr2.length; y++) {
  27. sum2 += myArr2[(int) y];
  28. } //end of for
  29. System.out.println(&quot;Sum of first 10 elements is: &quot; + sum1); //Prints sum of first 10 elements
  30. System.out.println(&quot;Sum of second 10 elements is: &quot; + sum2); //Prints sum of last 10 elements
  31. }/*end of try*/catch (Exception e) { //Catches errors in user input
  32. System.out.println(&quot;Invalid input. Try again: &quot;);
  33. System.out.println(&quot;&quot;);
  34. } //end of catch
  35. }//end of do
  36. while(z==1);
  37. return;
  38. }
  39. }

答案1

得分: 1

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

  1. public static void main(String[] args) {
  2. Scanner input = new Scanner(System.in);
  3. double v = nextDouble(input, "请输入一个值:", "类型不正确,请重试:");
  4. System.out.println(v);
  5. }
  6. public static double nextDouble(Scanner input, String prompt, String error) {
  7. System.out.print(prompt);
  8. // 无限循环
  9. for (;;) {
  10. try {
  11. double v = input.nextDouble();
  12. return v;
  13. } catch (InputMismatchException ie) {
  14. input.nextLine(); // 清空输入缓冲区
  15. System.out.print(error);
  16. }
  17. }
  18. }

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

  1. Scanner scanner = new Scanner(System.in);
  2. String prompt = "请输入一个数字:";
  3. String error = "输入无效,请重试";
  4. double[] myArr1 = new double[10]; // 创建数组
  5. System.out.println("");
  6. System.out.println("输入10个元素:");
  7. System.out.println("");
  8. for (int x = 0; x < myArr1.length; x++) {
  9. myArr1[x] = nextDouble(scanner, prompt, error);
  10. } // 结束循环
  11. double sum1 = 0;
  12. for (double x = 0; x < myArr1.length; x++) {
  13. sum1 += myArr1[(int) x]; // 定义sum1
  14. } // 结束循环

移除你现有的 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.

  1. public static void main(String[] args) {
  2. Scanner input = new Scanner(System.in);
  3. double v = nextDouble(input, &quot;Please enter a value: &quot;, &quot;Improper type, try again: &quot;);
  4. System.out.println(v);
  5. }
  6. public static double nextDouble(Scanner input, String prompt, String error) {
  7. System.out.print(prompt);
  8. // loop forever
  9. for(;;) {
  10. try {
  11. double v = input.nextDouble();
  12. return v;
  13. } catch (InputMismatchException ie) {
  14. input.nextLine(); // clear input buffer
  15. System.out.print(error);
  16. }
  17. }
  18. }

Here is an example from your code.

  1. Scanner scanner = new Scanner(System.in);
  2. String prompt = &quot;Please enter a number: &quot;;
  3. String error = &quot;Invalid input, try again&quot;;
  4. double[] myArr1 = new double[10]; // Creates array
  5. System.out.println(&quot;&quot;);
  6. System.out.println(&quot;Enter 10 elements: &quot;);
  7. System.out.println(&quot;&quot;);
  8. for (int x = 0; x &lt; myArr1.length; x++) {
  9. myArr1[x] = nextDouble(scanner, prompt, error);
  10. } // end of for
  11. double sum1 = 0;
  12. for (double x = 0; x &lt; myArr1.length; x++) {
  13. sum1 += myArr1[(int) x]; // Defines sum1
  14. } // 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 循环和布尔值来获取一个数字

  1. Scanner scanner = new Scanner(System.in);
  2. boolean bool = true;
  3. double d; // = scanner.nextDouble();
  4. while (bool) {
  5. try {
  6. scanner = new Scanner(System.in);
  7. d = scanner.nextDouble();
  8. bool = false;
  9. } catch (InputMismatchException e) {
  10. System.err.println("无效输入");
  11. }
  12. }
英文:

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

  1. Scanner scanner = new Scanner(System.in);
  2. boolean bool = true;
  3. double d ;//= scanner.nextDouble();
  4. while(bool){
  5. try{
  6. scanner = new Scanner(System.in);
  7. d = scanner.nextDouble();
  8. bool = false;
  9. }catch(InputMismatchException e){
  10. System.err.println(&quot;invalid input&quot;);
  11. }
  12. }

答案3

得分: 0

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

  1. import java.util.Scanner;
  2. public class Array {
  3. public static void main(String[] args) {
  4. double[] array = new double[20]; //创建数组
  5. boolean on = true; //设置值为“on”
  6. while (on) { //开始while循环
  7. System.out.println("输入20个数字:");
  8. System.out.println("");
  9. for (int i = 0; i < array.length; i++) { //创建用户输入提示
  10. Scanner input = new Scanner(System.in); //获取用户输入
  11. try {
  12. array[i] = input.nextDouble(); //将用户输入赋值给array[i]
  13. } catch (Exception e) { //捕捉无效输入
  14. System.err.println("无效输入。请重试:");
  15. i = i - 1; //减少重新输入数字的索引
  16. }
  17. }
  18. double x = 0;
  19. for (int z = 0; z < 10; z++) {
  20. x += array[z];
  21. }
  22. System.out.println("前10个数字的总和 = " + x); //将数组中前10个数字相加并赋值给x
  23. System.out.println("");
  24. double y = 0;
  25. for (int z = 10; z < 20; z++) {
  26. y += array[z];
  27. }
  28. System.out.println("后10个数字的总和 = " + y); //将数组中后10个数字相加并赋值给y
  29. on = false; //退出while循环
  30. }
  31. }
  32. }
英文:

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.

  1. import java.util.Scanner;
  2. public class Array {
  3. public static void main(String[] args) {
  4. double[] array = new double[20]; //creates array
  5. boolean on = true; //sets value &quot;on&quot;
  6. while (on) { //starts while loop
  7. System.out.println(&quot;Enter 20 numbers: &quot;);
  8. System.out.println(&quot;&quot;);
  9. for (int i = 0; i &lt; array.length; i++) { //creates user input prompt
  10. Scanner input = new Scanner(System.in); //gets user input
  11. try {
  12. array[i] = input.nextDouble(); //assigns user input to array[i]
  13. }/*end of try*/ catch (Exception e) { //catches invalid input
  14. System.err.println(&quot;Invalid Input. Try again: &quot;);
  15. i = i - 1; //decrements index of re-entered number
  16. } //end of catch
  17. } //end of for
  18. double x = 0;
  19. for (int z = 0; z &lt; 10; z++) {
  20. x += array[z];
  21. } //end of for
  22. System.out.println(&quot;Sum of first 10 numbers = &quot; + x); //adds first 10 numbers in array and assigns them to x
  23. System.out.println(&quot;&quot;);
  24. double y = 0;
  25. for (int z = 10; z &lt; 20; z++) {
  26. y += array[z];
  27. } //end of for
  28. System.out.println(&quot;Sum of last 10 numbers = &quot; + y); //adds last 10 numbers in array and assigns them to y
  29. on = false; //breaks while loop
  30. } //end of while
  31. }
  32. }

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:

确定