Java.util.Scanner.nextInt(int radix) 方法



描述

java.util.Scanner.nextInt() 方法將輸入的下一個標記掃描為一個 int 型別的值。如果下一個標記不能像下面描述的那樣轉換為有效的 int 值,則此方法將丟擲 InputMismatchException 異常。如果轉換成功,掃描程式將跳過匹配的輸入。

宣告

以下是 java.util.Scanner.nextInt() 方法的宣告

public int nextInt(int radix)

引數

radix − 用於將標記解釋為 int 值的基數

返回值

此方法返回從輸入中掃描的 int 值

異常

  • InputMismatchException − 如果下一個標記與 Integer 正則表示式不匹配,或者超出範圍

  • NoSuchElementException − 如果輸入已耗盡

  • IllegalStateException − 如果此掃描程式已關閉

示例

以下示例顯示了 java.util.Scanner.nextInt() 方法的使用。

package com.tutorialspoint;

import java.util.*;

public class ScannerDemo {
   public static void main(String[] args) {

      String s = "Hello World! 3 + 3.0 = 6.0 true ";

      // create a new scanner with the specified String Object
      Scanner scanner = new Scanner(s);

      // find the next int token and print it
      // loop for the whole scanner
      while (scanner.hasNext()) {

         // if the next is a int, print found and the int with radix 4
         if (scanner.hasNextInt()) {
            System.out.println("Found :" + scanner.nextInt(4));
         }
         // if no int is found, print "Not Found:" and the token
         System.out.println("Not Found :" + scanner.next());
      }

      // close the scanner
      scanner.close();
   }
}

讓我們編譯並執行上述程式,這將產生以下結果:

Not Found :Hello
Not Found :World!
Found :3
Not Found :+
Not Found :3.0
Not Found :=
Not Found :6.0
Not Found :true
java_util_scanner.htm
廣告

© . All rights reserved.