[英]System.out.print() reads Scanner incorrectly
我試圖為我的一個班級編寫該程序,但我的輸出出現了問題。 應該讀取我在“ Scanner
輸入中鍵入的內容。 但是,輸出會跳過第一個單詞,我不確定為什么。 您可以忽略main方法中的大多數變量聲明。 這些僅對程序的其余部分有用。
public static void main(String[] args) {
String fullName;
int anniversaryM;
int anniversaryY;
int periodHours;
String jobTitle;
double payRate;
int monthsWorked;
double vacationHours;
double grossPay;
double retirement;
double taxWithholding;
double netPay;
Scanner in = new Scanner(System.in);
fullName = inputLine(in, "Enter your full name:");
System.out.print(fullName);
}
public static double inputNumber(Scanner input, String prompt) {
Scanner in = new Scanner(System.in);
in.nextDouble();
return in.nextDouble();
}
public static String inputLine(Scanner input, String prompt) {
Scanner in = new Scanner(System.in);
System.out.println(prompt);
in.next();
return in.next();
}
public static double calcPercentage(double grossPay, double retirement) {
Scanner in = new Scanner(System.in);
in.nextDouble();
return in.nextDouble();
}
輸出:
輸入您的全名:
約翰·杜
母鹿
您有兩次調用in.next()
。 只需將其刪除,就可以了。 此外,請注意,您要將Scanner
傳遞給方法,因此不應在方法內部創建新的方法:
public static String inputLine(Scanner input, String prompt) {
System.out.println(prompt);
return input.nextLine();
}
我認為您的問題是in.next(); return in.next();
in.next(); return in.next();
。 在這種情況下,如果要返回in.next();
的值,它將調用讀取器兩次in.next();
您應該將其放入容器中並返回該容器,或者直接return in.next();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.