2013-04-29 2 views
0

프로그램에서 복식의 유효성을 올바르게 검사하는 데 어려움이 있습니다. 사용자는 계좌에 입금 할 금액을 입력 할 수 있습니다. 두 배가되어야합니다 (사용해야하는 것이 아니지만 양도 지침의 일부 임). 이론적으로 사용자는 £ 30뿐만 아니라 £ 15.23과 같은 금액을 입금 할 수 있어야합니다. 이것은 숫자를 허용하지만 많은 문제를 일으키는 정류장의 입력을 방지하는 현재의 유효성 확인입니다. 여기 (단순해야 함) double double validation

내가 지금까지 가지고있는 코드 :

public static String getBalanceValidation() 
{ 
    //Allow user input capabilities 
    Scanner input = new Scanner (System.in); 
    //Declare variables needed for validation 
    double dblInput = 0; //dblInput is set as 0 
    String strNumber = ""; //strNumber is blank 
    boolean bolSuccessful, bolNumeric; 
    int intCount; 
    char charLetter; 


    do 
    { 
     //set bolSuccessful and bolNumeric as true 
     bolSuccessful = true; 
     bolNumeric = true; 

     try //try user input 
      { 
       System.out.println("Enter the balance to be deposited: "); //User prompt 
       strNumber = input.next(); //User input as string 
       dblInput = Double.parseDouble(strNumber) ; //String input converted to double 


      }// end of try 

     catch (NumberFormatException e) //NumberFormatException disallows letters or symbols in value 
      { 
       System.out.println("Deposit value cannot contain letters!"); //Error message 
       bolSuccessful = false; //set bolSuccessful as false 

       continue; //Return to try 
      }//end of number format catch 


      //create for loop which checks each character throughout the string 
      for (intCount = 0; intCount < strNumber.length(); intCount++) 
       { 
        charLetter = strNumber.charAt(intCount); //charLetter is the alphanumeric value of a character in the string at the point dictated by intCount 


        if (!(charLetter >= '0') && (charLetter <= '9') //if charLetter is not between 0 and 9 
          || (charLetter == '.')) //or charLetter is not a full stop 
         { 
          bolNumeric = false; //Set bolNumeric as false 
         }//end of if construct 
       }//end of for loop 

      if (!bolNumeric) //if bolNumeric is false 
       { 
        System.out.println("Incorrect input format! The balance must be numbers only!"); //Error message 
        bolSuccessful = false; //Set bolSuccessful as false 
       }//end of if construct 

    }while (!bolSuccessful); //While bolSuccessful is false, return to top 


    return strNumber; //return strNumber to be used in main method 
    //end of do method 
}//end of getBalanceValidation method 

내가이없는 NumberFormatException을 사용한 적이 있기 때문에인지 확실하지 않다 (두 배에 뭔가가있다?)

많은 감사

+1

'여러 가지 문제'를 정의하십시오. 어떤 것이 * 때문에 ... 있는지 확실하지 않습니다 ...? 진짜 질문이 아닙니다. – EJP

+0

변수가 'true'로 설정되었다는 코멘트를 정말 싫어합니다. : // set bolSuccessful and bolNumeric to true. – Henrik

+0

나는 의견을 너무 싫어하지만 내가 말했던 것처럼 그것은 할당을위한 것입니다. 나는 방금 미친 듯이 말하라는 말을 들었다. –

답변

0

당신은 당신의 부울 표현식에서 2 오류가 있습니다

if (!(charLetter >= '0') && (charLetter <= '9') || (charLetter == '.')) 

if (!((charLetter >= '0') && (charLetter <= '9')) || (charLetter == '.')) 
:

if ((charLetter < '0') || (charLetter == '.')) 

는 그래서 ! 표현식의 처음 두 부분에 적용되어야한다 단순화 될 수

if ((charLetter < '0') && (charLetter <= '9') || (charLetter == '.')) 

:

이 조건에 해당

또한 .은 숫자가 아니므로이 표현식은 같습니다. 당신은 아마 ||&&을하지 의미

if (!((charLetter >= '0') && (charLetter <= '9'))) 

:에 t

if (!((charLetter >= '0') && (charLetter <= '9')) && (charLetter != '.')) 

할 수 있습니다 double number = input.nextDouble(); 대신 strNumber = input.next();if(not_a_number AND not_a_full-stop)

+0

대우를 받으십시오 - 대단히 감사합니다. 그것이 또는이 경우가 아니라는 것을 알고 있었음에 틀림없지 만, 나는 주로 이름을 검증하는 작업을하고있었습니다. 감사! –

0

을 의미한다. 이렇게하면 대신 을 직접 double으로 입력 할 수 있습니다.

catch 블록에 InputMismatchException을 처리해야합니다. .의 포함 여부를 확인하기 위해 확인할 필요가 없습니다.

0

그것은 정규식을 사용하여 훨씬 쉬울 것 :

bolNumeric = strNumber.matches("[1-9][0-9]*(\\.[0-9]{1,2})?"); 

설명 : 첫 번째 숫자는 1-9 이내이어야한다. 그런 다음 원하는만큼 많은 숫자를 추가 할 수 있습니다. 선택적으로 점 다음에 하나 이상, 최대 2 자리 이상이옵니다.

관련 문제