這段代碼不起作用,每當我作為用戶首先輸入字串資料然后輸入 int 資料時,它只接受輸入而不列印資料。如果我改變:
String name = input.nextLine();
int age = input.nextInt();
這兩個代碼塊的位置,先輸入 int ,然后輸入 String 作為第二個值,然后它很高興地列印第一個 int 數字,然后是 String。請幫忙看看如何解決。我想先有姓名和姓氏,然后才有年齡。
package package1;
import java.util.Scanner;
public class experiment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.println("Please enter your age and name: ");
String name = input.nextLine();
int age = input.nextInt();
System.out.println("Your age is: " age);
System.out.println("Your name is: " name);
} finally {
input.close();
}
}
}
我的輸入是:
Aks Eyeless 2022
uj5u.com熱心網友回復:
您是否嘗試過使用 input.next() 而不是 input.nextLine();
uj5u.com熱心網友回復:
第一件事:歡迎來到 StackOverflow :D
你的問題
您似乎以錯誤的方式提供輸入。我在本地進行了測驗,效果很好,但是您必須注意輸入資料的方式。
nextLine()將從 StandardOutput 讀取,直到它到達\n又名換行符。另一方面nextInt()將讀取下一個 Integer 直到它到達一個空格。所以會發生什么:你在一行(fe stackoverflow 2022)中輸入你的資料,由一個空格分隔,然后按回車鍵。這將保存在您的變數中name。然后,控制臺等待您的整數輸入。如果您輸入一些數字,它將成功列印出姓名 ( stackoverflow 2022) 和年齡。
解決方案
如果你只是想讓你的代碼作業:
輸入名稱后按回車鍵,然后輸入數字:您的代碼有效!
如果您 100% 必須在一行中提供輸入:
- 使用
next()代替nextLine()。這將一直讀到一個空格,但要小心:如果您輸入的名稱包含空格,則其余的將被解釋為整數,您可能會遇到InputMismatchException-s
一般建議:
您可以通過要求用戶專門輸入他們的姓名和年齡來嘗試使您的程式更具互動性。
另一個重要的變化是一些更好的例外處理,例如當用戶被提示輸入一個整數時,他/她提供了一個字串。
請隨時在評論中討論您的更改/問題/想法/想法:D
uj5u.com熱心網友回復:
單獨的姓名和年齡宣告,更容易理解。你可以用資源寫試試
try (Scanner input = new Scanner(System.in)) {
System.out.println("Please enter your name: ");
String name = input.nextLine();
System.out.println("Please enter your age: ");
int age = input.nextInt();
System.out.println("Your age is: " age);
System.out.println("Your name is: " name);
}
uj5u.com熱心網友回復:
以下是在一行中輸入姓名和年齡的方法。
Please enter your name and age: Gilbert Le Blanc 66
Your age is: 66
Your name is: Gilbert Le Blanc
您執行一個Scanner nextLine方法,然后從名稱中決議(分離)年齡。該字串類有許多用于決議字串有用的方法。
這是修改后的代碼。
import java.util.Scanner;
public class Experiment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.print("Please enter your name and age: ");
String text = input.nextLine();
int endIndex = text.lastIndexOf(' ');
String name = text.substring(0, endIndex);
int age = Integer.valueOf(text.substring(endIndex 1));
System.out.println("Your age is: " age);
System.out.println("Your name is: " name);
} finally {
input.close();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/403641.html
標籤:
上一篇:為什么我的字串沒有被正確列印?
