【问题标题】:do while loop with try catch [duplicate]用try catch做while循环[重复]
【发布时间】:2016-10-22 12:30:22
【问题描述】:

我的代码有什么问题?我正在尝试请求提示用户输入一个数字,如果它不在 1 和 6 之间,或者它应该说无效并提示另一个尝试。用户可能只有 3 次尝试。

import java.util.Scanner;

public class Game {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] numbers = new int[6];

    System.out.println("Enter a number on a die from 1-6:");
    String dieinput = input.next();
    int invalidcount = 0;
    System.out.println("Your number is: " + dieinput);



    do{
    try
    {
      // the String to int conversion
      int dienum = Integer.parseInt(dieinput.trim());
      int dienumOE = 0;
      int count=0;

      //test number input
      if ((dienum >= 1) && (dienum<= 6))
            System.out.println("number is " + dienum + oddoreven(dienum));
      else
            System.out.println("Invalid number, please enter a number 1-6");
            count++;
            System.out.println("Count" + count);
      }
    catch (NumberFormatException nfe){
        System.out.println("Invalid number, please enter a number 1-6");
        System.out.println("Count" + count);
        }
    while (count <= 3 && count >=0);
    }
    }





// Check if odd or even
public static String oddoreven(int num) {
    String result;

    if (num % 2 == 0)
        result = "even";
    else
        result = "odd";
    return result;
}
}

【问题讨论】:

  • 无限循环。您在每个循环开始时将计数设置为 0。请参阅下面的答案,但也不要在循环内将此变量设置为零。
  • 请发布一个完整的示例 - 您的源代码甚至无法编译。
  • 我更改了 int 计数器,但 do-while 仍在正常工作。有什么建议吗?

标签: java try-catch do-while


【解决方案1】:

您的问题是“错误”的作用域:您不能在 try 块的范围内声明的 catch 块中使用变量!

换句话说;你需要:

int counter = 0;
try { ...
} catch (... 

如果您想在 both 中使用计数器,请尝试 catch!

“规则”非常简单:变量仅在关闭它所在的“块”的 } 之前可见。

这会阻止您实际编译代码!

所以,这里真正的课更像是:不要写100行代码来然后运行编译器。只写尽可能少的行 - 每次你认为:这“足够”编译..然后编译。然后修复报告给您的错误。 java 编译器非常擅长给你特定的消息,告诉你你做错了什么;但是你写的越乱码越难!

郑重声明:SO 不是一个“远程”编译器服务,您应该使用它来编译凌乱的代码!

【讨论】:

  • 记录一下:SO 不是一个“远程”编译器服务,你应该使用它来编译你的杂乱代码!这很有趣,因为你就是这样做的.这些问题有重复,无需再回答。
猜你喜欢
  • 2017-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-24
  • 2014-09-11
  • 1970-01-01
相关资源
最近更新 更多