简体   繁体   中英

Reading a line that is inputted by the user using Java

For my assignment, I am required to write a program that calculates final marks and prints them. The user input would be as follows (inputs are through the java editing program and not the command prompt):

Firstname Lastname ExamMark MidtermMark etc.  

There is a known number of fields(11: 2 names, 9 marks) but an unknown number of students (one student per line).

I know I can determine the number of students by counting the number of lines using a while loop. But then I want to be able to section each part of the line to the corresponding variable. (saying that the first word in the line is equal to the first name etc). I am not entirely sure how to do this. I was thinking of somehow stating that each line is an array and then saying arrayx [0] = first name and arrayx [1] = last name etc and then do the required calculation and then loop that for each line/student. But I have no idea how to make the inputted line an array. Is there a simple way to do this?

If each data token is separated by a space, then you can easily put the String tokens into an array using String's split(...) method. perhaps via split(" ") if you know it's one space always or split("\\\\s+") if you don't.

eg,

while (myScanner.hasNextLine()) {

    String line = myScanner.nextLine();
    String[] tokens = line.split("\\s+");

    // now iterate through your array of tokens    
    //....
}

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