【问题标题】:Why does my program give a '.class' expected error? [closed]为什么我的程序会给出“.class”预期错误? [关闭]
【发布时间】:2017-10-30 00:46:21
【问题描述】:

我不知道问题出在我的代码中。

int a 小于int b 时,它不应该一直循环吗?

任何帮助将不胜感激,因为我正在努力学习,这让我很困惑。

我的代码:

import java.util.Scanner;

public class TwoNumbers {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        // Keep prompting the user until the input is correct
        do {
            System.out.println("Enter two positive integers, the first smaller than the second.");
            System.out.print("First: ");
            int a = in.nextInt();
            System.out.print("Second: ");
            int b = in.nextInt();
        }while(int a > int b);
        // Only print this when the input is correct
        System.out.println("You entered " + a + " and " + b);
    }
}

【问题讨论】:

  • 请 1) 显示完整的错误消息。 2) 展示如何编译和调用此代码。 3)不要将您的整个问题作为块引用发布,因为这不是此选项的用途,并且会减损您的问题。
  • 请先修复编译错误...

标签: java


【解决方案1】:

您收到错误消息,因为您同时声明了 ab,因此它们与您的 do 块中的不同。

要让它们在dowhile 的范围内,你必须在do-while 之外声明它们,但在main 方法中(像这样):

import java.util.Scanner;

public class TwoNumbers {

public static void main(String[] args) {
    int a;
    int b;
    Scanner in = new Scanner(System.in);

    // Keep prompting the user until the input is correct
    do {
        System.out.println("Enter two positive integers, the first smaller than the second.");
        System.out.print("First: ");
        a = in.nextInt();
        System.out.print("Second: ");
        b = in.nextInt();
    }
    while(a > b);
    // Only print this when the input is correct
    System.out.println("You entered " + a + " and " + b);
}
}

【讨论】:

  • 方法局部变量会更好。
【解决方案2】:

您在 while 中声明了这些变量,因此它们与您的 do 块中的变量不同。此外,它不应该编译,所以我不确定它会如何循环。

要使它们在 while 范围内,您必须在 do 之外声明它们。

【讨论】:

  • 有什么办法可以让它们一样吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 2013-04-05
  • 1970-01-01
  • 2014-03-23
  • 2021-01-11
  • 2021-03-30
  • 2014-03-31
相关资源
最近更新 更多