[英]Java: Collecting input with multiple variable types on a single line
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)? 如何在一行中收集4个不同类型的变量(字符串,浮点数和整数),如下所示:( 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? 我需要使用
for
循环吗?
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语句更改为print语句。 println sometimes throws off the Scanner class when theres more than one item to collect.
println有时会在收集多个项目时抛出Scanner类。
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());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.