我嘗試撰寫關于讀取數字的值 o 符號的編碼,并且我必須將空格作為輸入,我可以讀取并識別數字的值,但我可以讀取空白輸入并給出錯誤(例外在執行緒“主”java.lang.numberformatexception:輸入字串:“)
import java.util.Scanner;
public class CheckingSign {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter floating point value: ");
String number = scanner.nextLine();
int n = Integer.parseInt(number);
if ( n > 0 ) {
System.out.print("DEBUG:the user input is < " number " >");
System.out.println("DEBUG:the trimed input is <" number ">");
System.out.println("The sign of the input is 1");
} else if ( n < 0 ) {
System.out.print("DEBUG:the user input is < " number " >");
System.out.println("DEBUG:the trimed input is <" number ">");
System.out.println("The sign of the input is -1");
} else {
System.out.print("DEBUG:the user input is < " number " >");
System.out.println("DEBUG:the trimed input is <" number ">");
System.out.println("Encountered blank input.");
}
}
}
uj5u.com熱心網友回復:
parse用try-catch陳述句包圍
Scanner scanner = new Scanner(System.in);
System.out.print("Enter floating point value: ");
String number = scanner.nextLine();
try {
float n = Float.parseFloat(number);
if ( n > 0 ) {
System.out.print("DEBUG:the user input is < " number " >");
System.out.println("DEBUG:the trimed input is <" number ">");
System.out.println("The sign of the input is 1");
} else if ( n < 0 ) {
System.out.print("DEBUG:the user input is < " number " >");
System.out.println("DEBUG:the trimed input is <" number ">");
System.out.println("The sign of the input is -1");
}
} catch (Exception e) {
System.out.print("DEBUG:the user input is < " number " >");
System.out.println("DEBUG:the trimed input is <" number ">");
System.out.println("Encountered blank input.");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/523568.html
標籤:爪哇空行
