Nooby Java程序员对输出感到困惑(构造函数)

时间:2014-06-23 10:00:00

标签: java input compiler-construction io case

我是一名相当新的Java程序员,我目前正在进行在线教程以提高我的技能。我在教程中找到了以下代码示例,它看起来应该运行但是当我在Eclipse中运行代码时遇到了一些错误。

这是我的第一个使用案例的程序但是我很确定我有正确的语法也许有人可以指出我的错误?另外,我很惊讶编译器抱怨该行" System.out.println("你确定(是 - 是,否 - 否)?");"

我在第3,4,7,8,10,11,15行遇到错误。请有人告诉我为什么我的程序不能运行?

class Certainty  
{
    System.out.println ("Are you sure (y - yes, n - no)?");
    int ch = System.in.read ();
    switch (ch)
    {
       case 'Y':
       case 'y': System.out.println ("I am sure.");
                break;
       case 'N':
       case 'n': System.out.println ("I am not sure.");
                 break;
       Default : System.out.println ("Incorrect choice.");
    }
}

/ *感谢所有有用的回复,我慢慢开始了解Java并且我非常喜欢它,并且热爱我的问题解答得很快你们很棒。** /

2 个答案:

答案 0 :(得分:4)

  

这是我使用案例的第一个程序但是我很确定我的语法正确可能有人可以指出我的错误吗?

大多数案例的实际语法都是正确的,除了它是default:而不是Default:(大写很重要)。

但是你的班级会立即在课程内部逐步编写代码。你不能这样做。它必须是内部初始化器或(更常见的)构造函数和/或方法。

另外,System.in.read()可能会抛出IOException,你必须声明你的方法抛出或捕获。在下面的例子中,我抓住它,只是说它发生了。通常你会做一些比这更有用的事情,但这对于这种快速测试来说很好。

import java.io.IOException;  // <=== Tell the compiler we're going to use this class below
class Certainty  
{
    public static final void main(String[] args) {
        try {                      // `try` starts a block of code we'll handle (some) exceptions for
            System.out.println ("Are you sure (y - yes, n - no)?");
            int ch = System.in.read ();
            switch (ch)
            {
               case 'Y':
               case 'y': System.out.println ("I am sure.");
                        break;
               case 'N':
               case 'n': System.out.println ("I am not sure.");
                         break;
               default : System.out.println ("Incorrect choice.");
            }
        }
        catch (IOException e) {    // <== `catch` says what exceptions we'll handle
            System.out.println("An exception occurred.");
        }
    }
}

在那里,我已将您的代码移动到与命令行Java应用程序一起使用的标准main方法,并修复了Default

答案 1 :(得分:1)

您应该将这些行放在main方法或任何其他方法中 例如:

class Certainty  
{
    public static void main (String[] args)
    {
    System.out.println ("Are you sure (y - yes, n - no)?");
        try
        { 
        int ch = System.in.read ();
        switch (ch)
        {
           case 'Y':
           case 'y': System.out.println ("I am sure.");
                    break;
           case 'N':
           case 'n': System.out.println ("I am not sure.");
                     break;
           default : System.out.println ("Incorrect choice.");
        }
       }//try
      catch (IOException e)
      {
        System.out.println("Error reading from user");
      }//catch

    }//end of main
 }