Java:在一行上收集多个变量类型的输入

时间:2017-09-24 16:57:49

标签: java

如何在一行上收集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循环?

2 个答案:

答案 0 :(得分:2)

更改

employeeID = keyboard.nextLine();

employeeID = keyboard.next();

人们现在可以输入中间有空格的输入或每次使用输入。

您可能还需要将println语句更改为print语句。 println有时会在收集多个项目时抛出Scanner类。

答案 1 :(得分: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());
        }
    }
}