簡體   English   中英

Java:在一行上收集多個變量類型的輸入

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM