簡體   English   中英

教我為什么此代碼無法檢查我的輸入是否為int,以及如何解決它

[英]Teach me why this code fails to check if my input is a int, and how I can fix it

import java.util.Scanner;

public class HelloWorld {
public static int num;
public static Scanner scan;
  public static void main(String[] args) {
    System.out.println("Hello World");
        /* This reads the input provided by user
         * using keyboard
         */
         scan = new Scanner(System.in);
        System.out.print("Enter any number: ");

        // This method reads the number provided using keyboard

        check();

        // Closing Scanner after the use


        // Displaying the number 
        System.out.println("The number entered by user: "+num);

  }
  public static void check(){


  try{
  num = scan.nextInt();


  }
  catch (Exception e){
  System.out.println("not a integer, try again");
  check();
  }

  }
}

我是編碼的新手,今年暑假將自學一些基本知識。 我想知道是否有人可以建議我如何創建此方法以接收int,並檢查輸入以確保多數民眾贊成在其內。 如果輸入的不是整數,我想重新運行。

簡單。 假設您有如下所示的內容。

NumberThing.isNumber(myStringValue);

.isNumber()確定您的字符串是否為數字值(即數字)。 至於將代碼置於循環中以繼續詢問用戶輸入是否無效,請使用while循環。 就像是 。

while (. . .) {
    // use something to exit the loop
    // depending on what the user does
}

您可能考慮將用戶請求代碼移至check方法。 同樣,在輸入有效數字后,使用break語句退出while循環。

while ( true )
{
    System.out.println( "Enter an integer."); 
    try
    {
        num = scan.nextInt();
        break; 
    }
    catch (Exception e)
    {
        System.out.println("not a integer"); 
    }
}

暫無
暫無

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

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