Jonathan Baxevanidis
Jonathan Baxevanidis

Reputation: 119

How to read User input word by word from one line with scanner?

I am trying to learn java and more specifically scanners. So I tried to create an simple program that gets as input the Student’s code Course1 course1Degree course2 course2Degree and so on until the user inputs the word end. When the user inputs end it’s time to enter the same information for another student. More detailed input is shown below:

061125 Programming1 6,1 DB1 7,0 Math1 5,5 end[enter]
071234 DB2 5,5 Java 7,3 end[enter]
012343 end[enter]

After the user inputs end[enter] the average score of the current student should be displayed.
The program ends when the user inputs for the Student’s code 0000[enter].

My problem is that I can never read the correct input what ever I have tried in order to calculate the average score of each student. Also it doesn’t seem to understand when [end] is inputted and after the first input what ever I do when input 0000 the program doesn’t stop. This is what I have till now.

package test;

import java.util.Scanner;

public class Test {
    
    public static void main(String[] args) {
       readline();
    }
    
    static void readline(){
        Scanner scanner = new Scanner(System.in).useDelimiter("\\s");
        String course = "";
        String code = "";
        float mark = 0;
        
        System.out.println("Enter student details: ");
        
        while(!course.equals("end")){
            
            code = scanner.nextLine();
            
            if (code.equals("0000")) {
                System.exit(0);
            } else {
                
                course = scanner.next();
                float sum = 0; 
                while (!scanner.equals("end")){
                    mark += scanner.nextFloat();
                    sum += mark;
                    System.out.println("sum:  " + sum);
                    
                }
            }
        }
        
        System.out.println("Final creds: " + " id: "+ code + " course: " + course + " mark: " + mark);
    } 
}

Upvotes: 0

Views: 1357

Answers (1)

FairOPShotgun
FairOPShotgun

Reputation: 125

Here is the answer to your question:

import java.util.Scanner;
public class Test {
  static String course;
  static double mark;
  static int id;
  static int times = 1;
  static double avgmark;
  static void readline(){    
    System.out.println("Enter student details in the format:  [Final creds] [ID] [Course]"); 
    while(true){
      Scanner scanner = new Scanner(System.in);
      String userInput = scanner.nextLine();
      if (userInput.equals("y")){
        times++;
        System.out.println("Type in your next mark:");
        Double nextMark = scanner.nextDouble();
        mark += nextMark;
        System.out.println("Would you like to add another mark? [y/n]");
        continue; 
      } else if (userInput.equals("n")){
        break;
      } else if (userInput.matches("^(\\S+(?:\\h+\\S+)*)$")) {
        String[] parts = userInput.split(" ");
        mark = Integer.parseInt(parts[0]);
        id = Integer.parseInt(parts[1]);
        course = parts[2];
        System.out.println("Would you like to add another mark? [y/n]");
        continue; 
      }    
    }       
    avgmark = mark/times;
    avgmark *= 100;
    avgmark = Math.round(avgmark);
    avgmark /= 100;
    System.out.println("\nStudent Information: \nID: #"+ id + "\nCourse: " + course + " \nTotal Marks: " + mark +"\nAvg. Mark: "+avgmark + "%");
  }
  public static void main(String[] args) {
    readline();
  }   
}

Output:

Output

Here is how it works:

In order to scan a line of input with a Scanner, you need to use a regex (or a REGular EXpression). I use the regex matcher ^(\\S+(?:\\h+\\S+)*)$ More info about it here and here! After checking if the userInput is the correct format, split it with the .split(" ") function. This will turn the entire input (EX: 568 Pro 123) into an Array... String[] parts = userInput.split(" ");[568, Pro, 123]. Once the userInput is an Array, you can assign it with variables... String name = parts[1]. This line of code will assign 'Pro' to the variable 'name'. From there, you can use it alongside the other variables that you assign. double gamescore = Integer.parseInt(parts[0]); This line of code assigns '568' to the variable 'gamescore'. Integer.parseInt() is a command that turns a String into a number, so the String 'parts[0]' is turned into a number that can be assigned to a 'double variable'.

Upvotes: 1

Related Questions