簡體   English   中英

如何獲取用戶輸入的int數並同時存儲用戶的輸入?

[英]how to take the number of an int input from the user and at the same time store the user's input?

該程序是一個神奇的日期程序(日期時間month =“ year作為兩位數的數字”),例如06 \\ 10 \\ 60 ...我想做一個條件...如果輸入的日期或月份或年份是大於或小於2位數應顯示一條錯誤消息...我嘗試過

 System.out.println("Please enter the day as a two digit Number");
 day=key.nextInt();
 day1=day.length();

但是它沒有用...所以我嘗試了這個:

System.out.println("Please enter the month as a two digit Number");
month1=key.next().length();
month=key.nextInt();

但是當我運行程序時...它需要兩個輸入而不是一個所以請幫幫我

只是:

day = key.nextInt();
int dayAbs = Math.abs(day);      // to handle negatives
if(dayAbs >= 10 && dayAbs <= 99) {
    // ...
}

問題是您使用的是nextInt()但是您想要兩位數字,例如06 ,這不是有效的整數。

最好:

  1. 將輸入掃描為字符串。 String day = scan.nextLine();

  2. 使用day.matches("\\\\d{2}")驗證輸入是否正確
    (這將僅匹配[0-9]的任何配對,而不必擔心其他字符)

  3. 如果它驗證,則可以獲取Integer: Integer realDay = Integer.valueOf(day);

  4. 進行進一步驗證以測試范圍(天數為1-31)(月數為1-12)(2月為1-28或1-29,具體取決於年份)等。

您可以簡單地通過將int轉換為字符串,然后檢查字符串的長度來做到這一點。

String s = Integer.toString(day);
if(s.length() <= 2 && !(s.length() < 1)){
    System.out.println("Good");
}else
    System.out.println("Bad"); 

測試int原語中的位數

int number = ...;
// or however you get the number

int length = (int)(Math.log10(number)+1);

if(length!=2) {
    // no!
} else {
    // yuss!
}

除了使用int使用字符串,然后檢查輸入的長度。 此代碼僅是基礎。 它存儲在結果中。 然后在檢查后使用Integer.parseInt(result);

System.out.println("Please enter two digits:");
    Scanner scan = new Scanner(System.in);
    String result = scan.next();
     if(result.length()>2 || result.length()<2)
         System.out.println("ERROR");
     else
         System.out.println("Success");

實際上,似乎您想強制執行字符串的長度,以便用戶必須鍵入06而不是6

如果是這樣的話:

String dayString = key.next();
if(dayString.length() != 2) {
    // throw error
}
int day = Integer.parseInt(dayString);
int day=key.nextInt();
String dayString = "";
if(day> 30 || day <0){ System.out.println("Error1");}
else if(day<10 ){ dayString = "0" + String.valueOf(day);}
else{dayString = String.valueOf(day);}

在這里,您的一天以2位數字作為字符串,更易於操作。 您還可以嘗試Date類(java.util.Date)

我不明白為什么您要使用密鑰,但是我認為Buffer reader可以解決您的問題,這里就是示例!

int month=0,length=0;
        String len=null;
        BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Please enter the month as a two digit Number");
        len=bf.readLine();
        length=len.length();
        month=Integer.parseInt(len);
        if(length==2)
        {
            System.out.println("Here you go month is two digit!");
        }
        else
        {
           //inform user that month is not 2 digits!
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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