2015-02-05 1 views
1

이것은 간단한 계산기 프로그램입니다. 내 배열을 검사하고 내 프로그램이 입력 된 두 개의 인수를 계속 추가하기 전에 그 안에있는 문자를 막을 수있는 무언가가 필요합니다. 입력은 명령 행에서 가져옵니다. java adder 1 2배열에 글자가 입력되지 않았는지 어떻게 확인할 수 있습니까?

public class Adder { 
    public static void main(String[] args) { 
     //Array to hold the two inputted numbers 
     float[] num = new float[2]; 
     //Sum of the array [2] will be stored in answer 
     float answer = 0; 

     /* 
      some how need to check the type of agruments entered... 
     */ 

     //If more than two agruments are entered, the error message will be shown 
     if (args.length > 2 || args.length < 2){ 
      System.out.println("ERROR: enter only two numbers not more not less"); 
     } 

     else{ 
     //Loop to add all of the values in the array num 
      for (int i = 0; i < args.length; i++){ 
       num[i] = Float.parseFloat(args[i]); 
       //adding the values in the array and storing in answer 
       answer += Float.parseFloat(args[i]); 
      } 

      System.out.println(num[0]+" + "+num[1]+" = "+answer); 
     } 
    } 
} 
+0

문제가 아니라,하지만 당신은 직접'처음에 경우'문 등이 조건을 작성할 수 있습니다!'args.length을 = 2' 대신 쓸데없이 중복 이중 검사를 사용하여 지금 사용하고 있습니다. – sjaustirni

+0

정규식을 사용할 수 있습니다. 자세한 내용은 http://www.vogella.com/tutorials/JavaRegularExpressions/article.html –

+1

@Dundee args.length이어야합니다. = 2 – PeerNet

답변

2

나는 아마 값을 구문 분석을 시도 할 것이다 그런 다음 예외를 처리하십시오.

public class Adder { 
    public static void main(String[] args) { 
     //Array to hold the two inputted numbers 
     float[] num = new float[2]; 
     //Sum of the array [2] will be stored in answer 
     float answer = 0; 

     /* 
      some how need to check the type of agruments entered... 
     */ 

     //If more than two agruments are entered, the error message will be shown 
     if (args.length > 2 || args.length < 2){ 
      System.out.println("ERROR: enter only two numbers not more not less"); 
     } 

     else{ 
      try { 
       //Loop to add all of the values in the array num 
       for (int i = 0; i < args.length; i++){ 
        num[i] = Float.parseFloat(args[i]); 
        //adding the values in the array and storing in answer 
        answer += Float.parseFloat(args[i]); 
       } 

       System.out.println(num[0]+" + "+num[1]+" = "+answer); 
      } catch (NumberFormatException ex) { 
       System.out.println("ERROR: enter only numeric values"); 
      } 
     } 
    } 
} 
+0

완벽하게 작동합니다. 감사. – GladL33

2

패턴을 확인하기 위해 정규 표현식을 사용할 수 있습니다.

String data1 = "d12"; 
String data2 = "12"; 
String regex = "\\d+"; 
System.out.println(data.matches(regex)); //result is false 
System.out.println(data.matches(regex)); //result is true 
6

사용자가 문자를 입력하지 못하게 할 수는 있지만 문자를 처리 할 수 ​​있도록 코드를 작성할 수 있습니다. 다음은이 작업을 수행하는 몇 가지 방법입니다.

1) 글자를 파싱하고 찾을 수있는 경우 파기하십시오.

2) 문자에 대한 구문 분석, 당신은 어떤을 발견하면, 오류 메시지를 반환하고 다시

3) 번호에 대한 구문 분석 시도하도록 요청하고, 던져 NFE (NumberFormatException이)를 잡아, 이 while 루프에서 실행되도록 다음 오류 메시지를 반환하고 보조 노트에 다시

try { 
    // your parsing code here 
} catch (NumberFormatException e) { 
    // error message and ask for new input 
} 

시도하는 사용자에게, 나는 아마 입력을 위해 스캐너 객체를 사용하여 해당 프로그램을 다시 작성합니다. 그렇게하면 명령을 추가 할 때마다 java를 사용하여 프로그램을 실행할 필요가 없으며 프로그램을 한 번만 실행하고 사용자가 종료 할 때까지 입력을 받아 들일 수 있습니다. 난 당신이 정규 표현식에 대한 자세한 내용은 정규 표현식

// One or more digits 
Pattern p = Pattern.compile("\d+"); 
if(!p.matcher(input).matches()) 
    throw new IllegalArgumentException(); 

를 사용하는 것이 좋습니다 볼

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 

    while (true) { 
     // ask for input 
     System.out.println("insert 2 numbers separated by a space or quit to quit:") 
     //scanner object to take input, reads the next line 
     String tempString = scan.nextLine(); 
     // break out of the loop if the user enters "quit" 
     if (tempString.equals("quit") { 
      break; 
     } 
     String[] tempArray = tempString.split(" "); 
     // add the values in tempArray to your array and do your calculations, etc. 
     // Use the Try/catch block in 3) that i posted when you use parseFloat() 
     // if you catch the exception, just continue and reloop up to the top, asking for new input. 

    } 
} 
+0

"NFE"란 무엇입니까? ? –

+0

@Aify 감사합니다. – GladL33

+0

@ThufirHawat NumberFormatException – Aify

0

루프 필요가 없습니다 : 여기

public static void main(String[] args) { 
    // length must be 2 
    if (args.length != 2) { 
     System.out.println("we need 2 numbers"); 
     // regex to match if input is a digit 
    } else if (args[0].matches("\\d") && args[1].matches("\\d")) { 
     int result = Integer.valueOf(args[0]) + Integer.valueOf(args[1]); 
     System.out.println("Result is: " + result); 
     // the rest is simply not a digit 
    } else { 
     System.out.println("You must type a digit"); 
    } 
} 
+0

나는 입력 된 도구의 – GladL33

+0

System.out.println ("결과 :"+ args [0] + args [1])을 합산하기 위해 루프를 가지고 있습니다; 이것은 반복하지 않고 같은 효과를냅니다 :) – RichardK

+0

그냥 인자 0과 1을 출력합니다. 실제로 인자를 추가하지 않습니다. – GladL33

관련 문제