2016-10-14 5 views
-1

그렇기 때문에 사람이 나이를 입력하지 않으려면 프로그램이 다른 대답을 인쇄합니다. 그러나, 내가 할 때 그것은 문자열에 대한 오류를 제공합니다. 나는 // 그것을 사용하여 int 답변이 연주되지 않았고, 그때 작동했습니다. 내가 정확히 같은 질문을하기 위해 정확히 둘 다 만들 것인가? 나는 대답을 찾았지만 찾을 수없는 것 같아서 링크가 있다면 링크 해주세요. 감사!변수가 다른 두 개의 if 문

System.out.println("So how old are you?"); 

    TimeUnit.SECONDS.sleep(2); 

    System.out.println("If you dont want to answer you dont have to. "); 

    Scanner scan4 = new Scanner (System.in); 
    String user_imput_string1 = scan.nextLine(); 

    if (user_imput_string1.equals("I dont know")) { 
     System.out.println("Ah thats cool. You look great regardless of your age anyway"); 
    } else { 
     System.out.println("Ah thats cool. You look great regardless of your age anyway"); 
    } 
+0

@KevinEsche 귀하의 의견과 약간 혼동 스럽습니다. 내가 문자열과 int를 모두 가질 수 없다는 말은 하나의 질문에 대해 별도의 변수가 있습니까? –

+0

오, 죄송합니다. 두 번째 부분에서 '문자열'을 사용하는 곳에서 읽어보십시오. [이 질문을 확인, 관련이 있어야합니다] (http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – SomeJavaGuy

+0

@NateCraft 안녕 네이트 ,'user_imput_int'를 가진 코드의 두 번째 부분을 삭제 한 것 같습니다. – kbunarjo

답변

1

, 당신은 두 개의 서로 다른 이미 변수 user_imput_string1user_imput_int, 후자를 갖고있는 것 같다 당신은 당신의 코드를 찾고, 그러나 (30)로 값을 비교하기 위해 int 형으로 문자열을 변환 할 필요가있는의 여전히 String입니다. 또한

int result = Integer.parseInt(user_imput_int); 
if (result > 30){ 
// do whatever 
} 

, 보조 노트로, 맞춤법하는 입력 잘못된 : 여기

가 올바르게 int로 문자열로 변환하기 위해 사용할 수있는 샘플 코드입니다.

+0

고맙습니다. 또한 입력을 철자하는 나의 무능력에 대해 너무 많이 웃고있는 im는 –

0

당신이 코드는 다음과 같습니다 예외를

public static void main(String[] args) { 
    Scanner scanner = new Scanner(System.in); 
    System.out.print("So how old are you? "); 
    String age = scanner.next(); //Read string by default 
    try{ 
     int actualAge = Integer.parseInt(age); 
     //do your stuff with age 
    }catch(Exception e){ //Raises NumberFormatException if it's not a number 
     //e.printStackTrace(); 
     System.out.println("Ah thats cool. You look great regardless of your age anyway"); 
    } 
    } 
0

를 잡는하여이 작업을 수행 할 수 있습니다, 나는 당신을 도울 수 있기를 바랍니다.

 System.out.println("So how old are you?"); 
     TimeUnit.SECONDS.sleep(2); 
     System.out.println("If you dont want to answer you dont have to. "); 
     Scanner scan = new Scanner(System.in); 
     String user_imput_int = scan.next(); 
     if ("I dont know".equals(user_imput_int)) { 
      System.out.println("Ah thats cool. You look great regardless of your age anyway"); 
     } else { 
      try { 
       int age = Integer.parseInt(user_imput_int); 
       if(age > 30) 
       { 
        System.out.println("Oh wow you look so good"); 
       } 
       else { 
        System.out.println("Oh thats ok. You look great regardless"); 
       } 
      } catch (Exception e) { 
       System.out.println("your input is either 'I dont know' or int number"); 
      } 
     } 
+0

고맙다. 꽤 정수에 도착한 Havent. parseInt는 나의 수업에서 아직 알고있다. =) –