java - 为什么我编译时得到 "cannot find symbol"?

标签 java compiler-construction syntax-error number-formatting

编辑:

  1. 你们回答得真快。我喜欢它。
  2. 我不敢相信我错过了这样一个事实:当我之前使用它时,我尝试实例化 NumberFormat 类,但我没有这样做。我也盯着这段代码看了好久。看来在密切关注细节方面我还有很多东西要学。

谢谢大家。

我正在使用 NumberFormat 类(或方法,我仍在习惯术语),但是当我编译程序时,我得到一个“找不到符号”,指向“NumberFormat.getPercentInstance()”中的小数点;”但我不明白为什么。代码如下:

import java.util.Scanner; 
import java.text.NumberFormat;

public class StudentAverages
{
//----------------------------------------------------------------  
// Reads a grade from the user and prints averages accordingly. 
//----------------------------------------------------------------  
public static void main (String [] args)
{
    Scanner scan = new Scanner(System.in);
    NumberFormat fmt = new NumberFormat.getPercentInstance();

    System.out.print("Enter the name of the first student: ");
    String name1 = scan.nextLine();

    int lab1, lab2, lab3, min = 0;

    System.out.print("Enter the lab assignment grades of "+name1+": ");
    lab1 = scan.nextInt();
    lab2 = scan.nextInt();
    lab3 = scan.nextInt();

    System.out.print("Enter the project grades of "+name1+": ");
    int proj1 = scan.nextInt();
    int proj2 = scan.nextInt();

    System.out.print("Enter the midterm grade of "+name1+ ": ");
    double mid1 = scan.nextDouble();

    System.out.print("Enter the final grade of "+name1+": ");
    double fin1 = scan.nextDouble(); // fin used so as to not confuse with CONSTANT final

    double avgLab1 = (lab1 + lab2 + lab3) / 3;
    double avgProj1 = (proj1 + proj2) / 2;

    double grade1 = (25 * avgLab1 + 40 * avgProj1 + 15 * mid1 + 20 * fin1) / 10000;

    System.out.println();

    System.out.println("Student's name " + name1);
    System.out.println("Lab average for "+name1+": " + avgLab1);
    System.out.println("Project average for "+name1+": " + avgProj1);
    System.out.println("Total grade for "+name1+": " + fmt.format(grade1));

编码新手。谢谢你的帮助。我交叉引用了我正在使用的书中的语法,并且结果正确。我什至检查了以前的代码,我没有做任何不同的事情,或者至少没有做任何我可以看到的事情。那么为什么编译器会说找不到该符号呢?

最佳答案

而不是:

NumberFormat fmt = new NumberFormat.getPercentInstance();

应该是:

NumberFormat fmt = NumberFormat.getPercentInstance();

因为,你想调用静态方法getPercentInstance来自类(class)NumberFormat .

此外(正如Pshemo所说),NumberFormat类是抽象,因此您无法使用new实例化它。关键字。

关于java - 为什么我编译时得到 "cannot find symbol"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22535868/

相关文章:

java - 如何在android代码中创建MongoID?

Java泛型,获取泛型参数的Class<T>

java - 为什么 matcher.group 给我一个错误?

java - 将非 Java 源代码转换为 Java 源代码的工具

python - 获取语​​法错误: future feature google_type_annotations is not defined

python - 使用Python 3安装Django 1.5时发生错误

java - 当我初始化扩展 fragment 时,如何停止调用父 fragment 的 onActivityCreated ?

java - 为什么 gax 中缺少 PropertiesProvider?

java - 为什么java找不到JUnit框架?

ruby - 编写Ruby类方法并获得意外的 token kEND错误