阅读名称和成绩值java

时间:2015-09-08 13:55:49

标签: java java.util.scanner delimiter

我目前正在尝试为家庭作业程序编写程序,该程序将以

形式读取值

“John Q. Woodcutter | 75 | 82 | 2 | 0 | 15 | 57 | 55 | 56 | 10 | 25 | 48”其中第一个值是学生姓名,其他值是各种标记出来的术语。标记的顺序是因为位置决定它们是什么标记,例如第一个是他们的考试,第二个是他们的期中考试。我在实际阅读数据时遇到了麻烦,所以任何帮助都会很棒。这就是我所拥有的

import java.util.Scanner;
import java.lang.Math;
public class A1
{
   public static void main(String [] args)
   {
      float ex, mid, bonus, cheat, a1, a2, a3, a4, a5, a6, a7, grade,A; 
      float Jb=0;
      String name, letGr;
      Scanner scanner = new Scanner(System.in);
      System.out.println("Please input grades");
      scanner.useDelimiter("|");
      name = scanner.next();
      ex = scanner.nextFloat();
      mid = scanner.nextFloat();
      bonus = scanner.nextFloat();
      cheat = scanner.nextFloat();
      a1 = scanner.nextFloat();
      a2 = scanner.nextFloat();
      a3 = scanner.nextFloat();
      a4 = scanner.nextFloat();
      a5 = scanner.nextFloat();
      a6 = scanner.nextFloat();
      a7 = scanner.nextFloat();

其余代码只是一系列用于进行实际成绩计算的if语句。另外,如果我希望程序从命令行接受带有测试用例的文本文件并运行到文件末尾,那么最好的方法是什么,因为我实际上并没有用程序打开文件?

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您好,您可以尝试这样

public static void main(String[] args) throws Exception {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        String str ;
        while ((str = reader.readLine())!=null) {

            Scanner scanner = new Scanner(str);

            float ex, mid, bonus, cheat, a1, a2, a3, a4, a5, a6, a7, grade,A; 
            float Jb=0;
            String name, letGr;
            System.out.println("Please input grades");
            scanner.useDelimiter("|");
            name = scanner.next();
            ex = scanner.nextFloat();
            mid = scanner.nextFloat();
            bonus = scanner.nextFloat();
            cheat = scanner.nextFloat();
            a1 = scanner.nextFloat();
            a2 = scanner.nextFloat();
            a3 = scanner.nextFloat();
            a4 = scanner.nextFloat();
            a5 = scanner.nextFloat();
            a6 = scanner.nextFloat();
            a7 = scanner.nextFloat();
        }
    }

答案 1 :(得分:0)

只是一个建议,但您可以使用扫描仪只是读取每行,然后将行分为" |",这样你就可以在每行上有任意数量的等级:

Scanner scanner = new Scanner(System.in);
System.out.println("Please input grades");

String line = scanner.nextLine();

while ( line.length() > 0 ) // quit when user enters no data
{
  String[] data = line.split("|"); // store the data in an array
  name = data[0];
  // use a for-loop to iterate from index 1 to data.length to see all the grades
  ...
  line = scanner.nextLine();
}

如果您希望扫描仪读取直至EOF:

Scanner scanner = new Scanner(new File("/path/to/file.txt"));
while ( scanner.hasNextLine() )
{
  String line = scanner.nextLine()
  ... // parsing code in here
}