Java新秀火箭科学家

时间:2014-05-04 22:14:11

标签: java

我开始学习Java了。我有其他语言的经验。有了一些毅力,这将是许多问题中的第一个。我正在为我的Java应用程序寻找输入方法。

以下代码是本课程的第一个示例:

public static void main(String)[] args) {
    int num;
    System.out.println("Write a number: "); 
    num = Entrada.entero();
  }
}

它在“Entrada”中给出了编译错误。我认为它正在等一个班级,虽然在我正在讲的教科书中没有对这类课程的描述。

2 个答案:

答案 0 :(得分:2)

看起来Entrada应该是实用程序类,以便更容易从控制台捕获输入(与其他语言相比,Java使这项任务变得非常困难)。如果教科书完全不错,它应该在某处包含该类的源(代码)(例如附带的CD)。

只有导入Java类时才能使用它们。只有少数类(例如来自java.lang包)在没有明确import语句的情况下引用和使用。这就是为什么教科书应该包括他们提供的任何实用程序类的来源,以及如何将它们包含在项目中的说明。

你可以通过自己编写输入捕获来获得这样一个简单的程序。

package testeroo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {
        int num;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Write a number:");

        // Read a number from input (not handling any errors that might occur)
        num = Integer.parseInt(in.readLine());

        // Echo the number back to the console
        System.out.println("You entered " + num);
    }

}

如果你想编写一个实用程序类来捕获整数,你可以通过自己编写这样一个类来重构(更新)你的代码(例如一个静态内部类,简化类路径)。

package testeroo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static class Entrada {

        public static int entero() throws IOException {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            int num = Integer.parseInt(in.readLine());
            return num;
        }

    }

    public static void main(String[] args) throws IOException {
        System.out.println("Write a number:");

        // Read a number from input (not handling any errors that might occur)
        int num = Entrada.entero();

        // Echo the number back to the console
        System.out.println("You entered " + num);
    }

}

但实际上,就像其他人所说的那样,你应该找到一本书(或其他什么),这些书在前几页中并没有让你陷入困境。那里有很多优秀的Java资源。祝你好运!

答案 1 :(得分:0)

您需要一个名为Entrada的类,该类应该有一个名为entreo()的静态方法。它应该是这样的:

public class Entrada {
     public static int entero() {
     ...
     }
}

尝试查找教科书,看看它是否提供了这样的课程。否则,你可能需要弄清楚Entrada和entreo实际上做了什么。