1

How do I collect 4 variables of different types (string, float and integer) of input on a single line like this: (string, float, float, int)?

For example:

"joey" 17.4 39.9 6

This is what my code looks like now. It works but it only collects the variables one line at a time.

import java.util.Scanner;

public class EmployeePay{

    public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);
    String employeeID = "";
    double hrsWorked;
    double wageRate;
    int deductions;

    System.out.println("Hello Employee! Please input your employee ID, hours worked per week, hourly rate, and deductions: ");
    employeeID = keyboard.nextLine();
    hrsWorked = keyboard.nextFloat();
    wageRate = keyboard.nextFloat();
    deductions = keyboard.nextInt();
    }
}

Do I need to use a for loop?

8
  • keyboard.nextLine(); is your problem. The rest are collected one line at a time only if you hit enter, you can collect them on one line. Commented Sep 24, 2017 at 17:01
  • How would I make it so that I don't need to click enter and all of them just go on the same line? Commented Sep 24, 2017 at 17:11
  • How would your program know that you finished entering the input without hitting enter? Commented Sep 24, 2017 at 17:13
  • I don't know... Is there a way to make the program know that each space separates a different variable in the input? Commented Sep 24, 2017 at 17:17
  • In a way it does, how will it know that you finished entering 6 and that it's not 636? Commented Sep 24, 2017 at 17:20

2 Answers 2

2

Change

employeeID = keyboard.nextLine();

to

employeeID = keyboard.next();

People can now enter the input with spaces inbetween or by using enter each time.

You may also have to change the println statement to a print statement. println sometimes throws off the Scanner class when theres more than one item to collect.

Sign up to request clarification or add additional context in comments.

Comments

1
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println( " enter i/p ");
    while (scan.hasNext()) { // This will loop your i/p.
        if (scan.hasNextInt()) { // if i/p int 
            System.out.println(" Int " + scan.nextInt());
        } else if (scan.hasNextFloat()) { // if i/p float
            System.out.println(" Float " + scan.nextFloat());
        } 
        else { // if i/p String
            System.out.println( " String " + scan.next());
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.