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?
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.
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());
}
}
}
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.