當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.util.Scanner.nextShort()用法及代碼示例


描述

這個java.util.Scanner.nextShort(int radix)方法掃描輸入的下一個標記作為短。如果下一個標記無法轉換為有效的短值,則此方法將拋出 InputMismatchException,如下所述。如果翻譯成功,掃描器將通過匹配的輸入。

聲明

以下是聲明java.util.Scanner.nextShort()方法

public short nextShort(int radix)

參數

radix- 用於將標記解釋為短值的基數

返回值

此方法返回從輸入掃描的短路

異常

  • InputMismatchException- 如果下一個標記與整數正則表達式不匹配,或者超出範圍

  • NoSuchElementException- 如果輸入用盡

  • IllegalStateException- 如果此掃描儀已關閉

示例

下麵的例子展示了 java.util.Scanner.nextShort() 方法的用法。

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 short token and print it
      // loop for the whole scanner
      while (scanner.hasNext()) {

         // if the next is a short, print found and the short with radix 4
         if (scanner.hasNextShort()) {
            System.out.println("Found:" + scanner.nextShort(4));
         }

         // if no short 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.nextShort() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。