【问题标题】:Creating a program to read through Integers and Strings in Java创建一个程序来读取 Java 中的整数和字符串
【发布时间】:2017-04-11 11:46:13
【问题描述】:

我正在尝试创建一个程序,该程序将读取格式如下的 .txt 文件:

学生总数
名称
得分1
分数2
得分3
名称
得分1
等等

我目前的代码是这样的:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.*;
public class Project5 {

public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter file name: ");
    String filename = in.nextLine();
    File filetest = new File(filename);
    Scanner imp = new Scanner(filetest);
    List<String> studentList = new ArrayList<String>();
    List<Integer> studentScores = new ArrayList<Integer>();
    String total = imp.nextLine();
    int i = 0;
    try {
        while (imp.hasNext()) {
            if (imp.hasNextInt()) {
                studentScores.add(imp.nextInt());
            } else {
                studentList.add(imp.nextLine());
            i++;
            }
        }
    } finally {
        System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
        System.out.println("-------------------------------------------------------");
        System.out.println(total);
        System.out.println(studentList.get(0) + "\t" + studentScores.subList(0, 3));
        System.out.println(studentList.get(2) + studentScores.subList(3, 6));
        System.out.println(studentList.get(4) + studentScores.subList(6, 9));
        System.out.println(studentList.get(6) + studentScores.subList(9, 12));
        imp.close();
        in.close();
    }

}
}

我想在控制台中显示的格式是列出姓名,然后是学生收到的三个分数,然后重复一遍,但现在它是硬编码的,只是针对当前学生的数量,而且无论有多少学生,我都需要它能够创建输出。

当前输出:

总计
名称 [score1 score2 score3]
等等

期望的输出:

总计
名称 score1 score2 score3 (而不是用 [] )
等等

非常感谢任何帮助。

【问题讨论】:

    标签: java text-files java.util.scanner


    【解决方案1】:

    更结构化的方式来做到这一点:

    public class Project5 {
    
        static class Student {
    
            private String name;
            private final List<Integer> scores;
            private int total;
    
            public Student() {
                scores = new ArrayList<>();
                total = 0;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public void addScore(int score) {
                scores.add(score);
                total += score;
            }
    
            public String getName() {
                return name;
            }
    
            public List<Integer> getScores() {
                return scores;
            }
    
            public int getTotal() {
                return total;
            }
    
            @Override
            public String toString() {
                StringBuilder sb = new StringBuilder(name).append('\t').append(total);
                for (Integer score : scores) {
                    sb.append('\t').append(score);
                }
                return sb.toString();
            }
    
        }
    
        public static void main(String[] args) throws IOException {
            Scanner in = new Scanner(System.in);
            System.out.println("Enter file name: ");
            String filename = in.nextLine();
            in.close();
    
            File filetest = new File(filename);
            Scanner imp = new Scanner(filetest);
            int total = Integer.parseInt(imp.nextLine());
    
            System.out.println("Name\tTotal\tScore 1\tScore 2\tScore 3");
    
            for (int i = 0; i < total && imp.hasNextLine(); i++) {
                Student student = new Student();
                student.setName(imp.nextLine());
                while (imp.hasNextInt()) {
                    student.addScore(imp.nextInt());
                }
                if (imp.hasNext()) {
                    imp.nextLine();
                }
                System.out.println(student);
            }
            imp.close();
        }
    
    }
    

    【讨论】:

    • 是否有关于如何为每个学生的三个分数创建总分的建议?抱歉,我对这个话题有点无知,我对 java 整体还是很陌生。我会使用 .parseInt 来识别三个分数并将它们相加吗?我对从那里去哪里有点困惑。
    • @steelersrawk1 加总分
    【解决方案2】:

    ListtoString 方法将以该格式返回它。如果您想要不同的格式,可以使用Stream

    System.out.println(studentList.get(2) + studentScores.subList(3, 6).stream().collect(Collectors.joining(" ");
    

    健康警告:如果这是针对使用Streams 可能会被指控抄袭的学校作业,那么您需要自己将这些元素串联起来。

    【讨论】:

      【解决方案3】:

      这是使用StringBuilder 而不使用Lists 的有效解决方案。 StringBuilder 基本上是一个帮助你构建字符串的类。很简单。

      // 1024 means that the initial capacity of sb is 1024
      StringBuilder sb = new StringBuilder(1024);
      try {
          while (imp.hasNext()) {
              if (imp.hasNextInt()) {
                  // add the scores and "tab" character to the string
                  sb.append("\t").append(imp.nextInt());
              } else {
                  // add the name to the string
                  sb.append("\n").append(imp.nextLine());
                  i++; // btw.. why are you doing this i++ ??
              }
          }
      } finally {
          System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
          System.out.println("-------------------------------------------------------");
          System.out.println(total);
          System.out.println(sb.toString());
          imp.close();
          in.close();
      }
      

      如果你确实想使用数组列表,那么我建议像数组一样遍历数组列表并打印出分数。

      【讨论】:

      • 感谢您的建议,至于 i++ 我刚刚意识到它在里面(感谢您指出这一点!)由于我使用 (i) 的声明,我最初在里面有它作为我已经删除的另一个循环的限制。
      • 有没有办法抓取sb里面的数字?就像如果我想计算总数,将个人的三个分数相加得出一个总数?
      • 不,没有。但如果这是你想要的,那么看看@AshrafulIslam 的实现。
      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      相关资源
      最近更新 更多