编辑:
谢谢大家。
我正在使用 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();
因为,您想从类 NumberFormat
调用静态方法
getPercentInstance。
此外(正如Pshemo所说),
NumberFormat
类是抽象,所以你不能用new
关键字实例化它。
从以下位置删除新内容:
NumberFormat fmt = new NumberFormat.getPercentInstance();
您正在调用静态方法。
删除行中的
new
关键字
NumberFormat fmt = new NumberFormat.getPercentInstance();
NumberFormat
是 abstract
类,这意味着您无法创建它的实例。
您需要扩展它的类的实例,您可以通过
getPercentInstance
方法获得此类实例。