2015-10-30 246 views
0

我需要檢查用戶是否正在輸入java中的數值。我一直試圖使用hasNextDouble,但使用hasNextDouble方法得到奇怪的錯誤,我不確定這是執行此檢查的方式。檢查數字輸入java

請注意我不能使用while循環或任何其他高級方法,除非。

import java.util.Scanner; 
import java.lang.Math; 
public class CentimeterInch 
{ 
    public static void main (String [] args) 
    { 
     final int MAX=100, feet=12, meter=100; 
     final double inch=2.54; 
     Scanner scan = new Scanner (System.in); 
     System.out.println ("This program converts distances. "); 
     System.out.println ("Enter distance and unit (e.g. 37 1 or 100 2):"); 
     double distance=scan.nextDouble(); 
     if (!scan.hasNextDouble()) 
      { 
       System.out.println ("please enter a numeric value"); 
       distance=scan.nextDouble(); 
      } 
     int unitType = scan.nextInt(); 
     if (distance<0) 
      { 
       System.out.println ("Please enter a non negative distance"); 
      } 
.... 

我固定的錯字,但它仍然不能正常工作,當我例如輸入「A」,它崩潰。對於我來說,在將值放入'double distance'變量後調用hasNextDouble也沒有意義,但是我還沒有找到其他方法。 我只有一個雙變量來檢查,'int'不需要驗證。編輯: 我提前了一下。現在它在崩潰之前顯示錯誤。我如何讓它不會崩潰,但再次接受變量?

if(!scan.hasNextDouble()) 
    System.out.println ("please enter a numeric value"); 
distance=scan.nextDouble(); 

謝謝!

+1

你的「怪異錯誤」是什麼? – Rehman

+2

錯字:'if(!scan.hasNextDouble())' – Reimeus

+0

我修正了錯字,但它仍然沒有運行,當我輸入例如25a它崩潰。對於我來說,在將值放入'double distance'變量後調用hasNextDouble也沒有意義,但是我還沒有找到其他方法。我只有一個雙變量來檢查。謝謝! – tamir

回答

0

它應該是scan.hasNextDouble()重點在D雙。

0

錯別字之外,你消費nextDouble後調用hasNextDouble

在一行中取兩者最簡單的方法是:

if (scan.hasNextDouble()) { 
    // TODO something 
    double foo = scan.nextDouble(); // this consumes the first double 
} 
else { // TODO exit with error } 
if (scan.hasNextDouble()) { 
    // TODO something else 
    double bar = scan.nextDouble(); // this consumes the second double 
} 
else { // TODO exit with error } 

如果你想在兩個服務(即用戶按下輸入兩次),你可以消耗scan.next()兩次,並在兩個String使用Double.parseDouble,而捕獲一個NumberFormatException的格式錯誤。