简体   繁体   English

读取用户使用Java输入的行

[英]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): 用户输入如下(输入是通过Java编辑程序而不是命令提示符):

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). 字段数量已知(11个:2个名称,9个标记),但学生数量未知(每行一个学生)。

I know I can determine the number of students by counting the number of lines using a while loop. 我知道我可以通过使用while循环计算行数来确定学生数。 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. 我正在考虑以某种方式声明每行是一个数组,然后说arrayx [0] =名字,arrayx [1] =姓等等,然后进行所需的计算,然后针对每行/学生进行循环。 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. 如果每个数据令牌都由空格分隔,则可以使用String的split(...)方法轻松地将String令牌放入数组中。 perhaps via split(" ") if you know it's one space always or split("\\\\s+") if you don't. 如果您知道它始终是一个空格,则可以通过split(" ")如果您不知道,则可以通过split(" ") split("\\\\s+")进行。

eg, 例如,

while (myScanner.hasNextLine()) {

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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