简体   繁体   中英

How do I pull information form a .txt file in Java?

I currently have some code that can take console input, but I need to make it recognize a list of names and test scores. Code that I currently have:

import java.io.*;
import utils.io.*;

class student
{
   String name;
   double sResult[];
   int result;
   double sum;

   void getdata()
   {
      System.out.println("Enter name:");
      Name = (string) system.in.read();
      int index=0;

      for (int counter=1; counter<=5; counter++)
      {
         System.out.println("Enter result for subject"+counter+":");
         sResult[count] = (double) system.in.read();
      }
   }

   public static void CalculateAverage()
   {
      sum = 0;
      for (int i=1;i<=5;i++)
      {
         sum += sResult[i];
      }
      return (int) Math.round(sum/(values.length-1));
   }

   Public static char calculateGrade()
   {
      result=sum;
      if (result>=0 && result <=59)
      {
         return ('F');
      }
      else
      if (result >=60 && result<=69)
      {
         return ('E');
      }
      else
      if (result>=0 && result<79)
      {
         return ('D');
      }
      else
      if (result >=70 && result<=79)
      {
         return ('C');
      }
      else
      if (result>=80 && result<=89)
      {
         return ('B');
      }
      else
      if (result>=90 && result<=100)
      {
         return ('A');
      }
   }
}

and class test

public class test
{
   public static void main(String[] args)
{
   Student std;
   do
   {
      std=new Student();
      std.getdata();
      System.out.println("Student Name:"+std.Name);
      System.out.println("Average for"+std.Name+" "+"is:"+std.average());
      System.out.println("Grade for"+std.Name+" "+"is:"+std.gradecal());
      System.out.println("Want to continue (1-Yes,2-No");
   }
   while(System.in.read()==1);
}

The text document format is name score1 score2 score3 score4 score5

I only need help figuring out how to import the values, and then I can probably figure out how to rewrite the .txt using PrintWriter.

Thanks in advance for any help!

Firstly, you should not have variable names starting with a capital, namely:

string Name;

Only class names should start with a capital.

Also, I'm not even sure if your code compiles. Everywhere you have system.out.println should be System.out.println . Notice that System is a class, so the first letter is a capital

To read data, you can use BufferedReader and to write, you can use BufferedWriter . Usage:

BufferedReader in = new BufferedReader(new FileReader("FileName.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("OutputFileName.txt"));

in.readLine(); //This reads a single line from the text file
out.write("Your Output Text");
in.close(); // Closes the file input stream
out.close(); // Closes the file output stream

Since you are reading in the format:

name score1 score2 score3 score4 score5

you can use the some String functions to get each field.

String inputLine = in.readLine();
String [] fields = inputLine.split(" "); // Splits at the space
System.out.println(fields[0]); //prints out name
System.out.println(fields[1]); //print out score1
...

Here's how you do it with Scanner .

Scanner inputFile = new Scanner(new File("inputfile.txt"));
while(inputFile.hasNext()){ //if there is still something to read
     String name = inputFile.next();
     int score1 = inputFile.nextInt();    
     ....
     int score5 = inputFile.nextInt();
     //Do something here with the scores
     inputFile.next(); //Read the new line character and prepare for the next iteration 
}

For writing back to file, you can check Davy's answer and use a Buffered Writer. Note that the write() method works just like System.out.println() but you need to print \\n on your own to go to the new line.

public static void main(String... args) throws IOException {
    Scanner s = new Scanner(new BufferedReader(new FileReader("textfile.txt")));
    while(s.hasNext()){
        Student student = new Student(s.next(), s.nextDouble(), s.nextDouble(),
                                      s.nextDouble(), s.nextDouble(), s.nextDouble() ));
        // Do something with student
        s.next() // consume endline
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM