【问题标题】:Generating multiplication questions in Java用Java生成乘法问题
【发布时间】:2017-04-01 16:11:38
【问题描述】:

代码应该输出华氏温度和摄氏温度的表格

public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |",          temp);
            double sum = (temp + (9.0/5.0)) * 32;   
            System.out.printf("%5d", (int)sum );
            System.out.println();

【问题讨论】:

  • 你遇到了什么错误?
  • 您是否收到此错误java: variable answer is already defined in method main(java.lang.String[])
  • 线程“main”java.lang.Error中的异常:未解决的编译问题:重复的局部变量答案@ samarth感谢您顺便回答。
  • 顺便说一句,即使解决了重复变量问题,您的代码也无法按预期工作。
  • 正如@Samarth 指出的那样,错误是因为您两次启动 int 答案一次int answer = input.nextInt(); 和一次int answer = input.nextInt()。此外,您正在比较 question == yes 这意味着您正在有效地检查 question==null 您是否应该使用带有条件 question=="yes"do while 循环而不是 if 语句。

标签: java loops if-statement for-loop while-loop


【解决方案1】:

您需要添加一个do while() 循环来继续提问,例如:

static Scanner input;
static Scanner scanner;
static String question;

public static void main(String[] args) {
    do {
        int number1 = (int) (Math.random() * 10);
        int number2 = (int) (Math.random() * 10);
        input = new Scanner(System.in);
        System.out.print("What is " + number1 + " * " + number2 + "? ");
        int answer = input.nextInt();
        while ((number1 * number2) != answer) {
            System.out.print("Incorrect. Please try again. What is "
                    + number1 + " * " + number2 + "? ");
            answer = input.nextInt();
        }
        if ((number1 * number2) == answer) {
            System.out.println("Correct. Nice work!");
            System.out.println("Want more questions yes or no? ");
            scanner = new Scanner(System.in);
            question = scanner.next();
        }
    } while (question.toLowerCase().equals("yes") ||
            question.toLowerCase().equals("y"));
}

【讨论】:

    【解决方案2】:

    最简单的方法是while循环。示例:

    do{
        // What you want to repeat and make sure to change have way to get out of loop like this:
        System.out.print("Want more questions yes or no? ");
        question = scanner.next();
    }while(question.equals("yes") || question.equals("y"));
    

    【讨论】:

      【解决方案3】:

      您的代码中有一些错误,但我建议您从阅读输入的简单案例开始,直到用户输入“n”:

          String input = "";
          Scanner scanner = new Scanner(System. in); 
      
          while (!input.equals("n")) {
              System.out.println("continue y/n?");
              input = scanner.nextLine();
          }
      

      在 while 循环体中添加随机整数的生成、检查答案等。确保在比较两个字符串时使用 equals 而不是 ==

      【讨论】:

        猜你喜欢
        • 2011-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-30
        • 2017-03-02
        • 2023-03-09
        • 1970-01-01
        相关资源
        最近更新 更多