2017-09-24 68 views
1

如何收集输入的不同类型(字符串,浮点和整数)的4个变量对像这样的一行:(字符串,浮动,浮动,INT)?的Java:收集与多个变量类型输入在一行

例如:

"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循环吗?

+0

'keyboard.nextLine();'是你的问题。其余的一次收集一行,只要你按回车,你可以收集他们在一行。 – Oleg

+0

我该如何做到这一点,我不需要点击输入,他们都只是在同一行? – Nate123

+0

你的程序如何知道你输入了输入而没有输入? – Oleg

回答

2

变化

employeeID = keyboard.nextLine(); 

employeeID = keyboard.next(); 

人们现在可以用插图中或使用每次输入空格输入输入。

您可能还必须将println语句更改为打印语句。当多个物品收集时,println有时会抛弃Scanner类。

+0

谢谢!我修好了,它工作:) – Nate123

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()); 
     } 
    } 
} 
+0

哇!这看起来很酷!谢谢! – Nate123