[英]Java: Collecting input with multiple variable types on a single line
如何在一行中收集4个不同类型的变量(字符串,浮点数和整数),如下所示:( string,float,float,int)?
例如:
"joey" 17.4 39.9 6
这就是我的代码现在的样子。 它可以工作,但它一次只收集一行变量。
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();
}
}
我需要使用for
循环吗?
更改
employeeID = keyboard.nextLine();
至
employeeID = keyboard.next();
人们现在可以在中间输入空格或者每次使用输入。
您可能还必须将println语句更改为print语句。 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.