【问题标题】:Error running or compiling this code java...Very confused program wont runjava运行或编译此代码时出错...非常混乱的程序无法运行
【发布时间】:2012-03-17 19:02:30
【问题描述】:

该程序不会在 netBeans 上运行或在终端中编译...我认为我本身没有任何错误.. 这个程序需要显示一个圆的面积 不能有任何无效输入(字母、&^#、..等)

请并感谢您的宝贵时间;)

 **import java.util.Scanner; 


    /**
     *
     * @author Omar Sugule
     */
    public class AreaCircle {


        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
    Scanner sc = new Scanner(System.in); // read the keyboard
    try {
        double r = sc.nextDouble();
    }
    catch( NumberFormatException e ) {
        System.err.println("Invalid Input, please enter a number");
        //put a message or anything you want to tell the user that their input was weird.
    }

    System.out.println("This program will calculate the area of a circle");

    System.out.println("Enter radius:");//Print to screen

    double r = sc.nextDouble(); // Read in the double from the keyboard






    double area = (3.14 *r * r); 
    String output = "Radius: " + r + "\n";
    output = output + "Area: " + area + "\n";
    System.out.println("The area of the circle  is " + area);

        }
    }**

【问题讨论】:

  • 所以您根本没有看到任何编译错误?当你运行它时会发生什么?您可能应该告诉我们更多有关您的问题的重要细节。
  • 当你说它“不会编译”时,你的意思是它给你一个编译错误吗?如果是这样 - 您不认为发布该错误会有所帮助吗?
  • 您似乎忘记发布您收到的错误消息
  • 如果您的代码发布开头和结尾的“**”实际上在您的文件中,那么这就是您的答案。
  • 对我有用,只是在我输入一个数字之前它不会提示输入,该数字被忽略,然后提示输入半径。那么它工作正常。

标签: java terminal


【解决方案1】:

你知道这行不通:

try {
    double r = sc.nextDouble();
}
catch( NumberFormatException e ) {
    System.err.println("Invalid Input, please enter a number");
    //put a message or anything you want to tell the user that their input was weird.
}

由于您在 try 块中声明 r,因此它仅在 try 块内可见,而在其他地方完全不可见(这称为超出“范围”)。

改为:

  • 在try块之前声明double r并将其初始化为0.0:
    double r = 0.0; // corrected as per mfrankli
  • 尝试在try块中获取输入
  • 将所有内容包含在一个while循环中并继续循环直到输入有效
  • 不要在 try 块之后重新声明 r
  • 致力于改进您的代码格式,特别是使您的代码缩进统一。这样做将使您和我们更容易调试代码。
  • 在这里努力提出更好的问题。提供所有必要的信息以帮助您解决最初的问题通常是一个好主意。你的遗漏了很多东西,让我们不得不猜测哪些可能会导致错误或令人困惑的答案。

【讨论】:

  • 我认为您不能将 null 分配给原始双精度数?
【解决方案2】:

我刚刚试用了你的程序,我看到的唯一真正的问题是你在开始时有这个等​​待用户输入的位:

    try {
        double r = sc.nextDouble();
    }
    catch( NumberFormatException e ) {
        System.err.println("Invalid Input, please enter a number");
        //put a message or anything you want to tell the user that their input was weird.
    }

由于该代码出现在程序产生任何输出之前,其效果是程序只是挂起;对于用户来说,他们应该输入一个数字并不明显。 (事实上​​,他们不必太担心他们输入的数字,因为程序稍后会提示他们输入另一个数字:

    double r = sc.nextDouble(); // Read in the double from the keyboard

实际使用的是第二个。)

【讨论】:

    【解决方案3】:

    删除文件开头和结尾的星号。其余的都可以,除了在实际输入之前必须按回车键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      相关资源
      最近更新 更多