2016-10-14 7 views
-1

だから、人が年齢を入力したくない場合、プログラムは別の答えを表示します。しかし、私はこれを行うと、文字列のエラーが表示されます。私は//これを使ってint型の答えが再生されなかったので、それはうまくいきました。私はそれをどのようにして正確にして、両方が同じ質問のために働くのでしょうか?私は答えを探しましたが、私はそれを見つけることができませんでした。ありがとう!異なる変数を持つ2つの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あなたのコメントと少し混乱します。文字列と整数の両方に1つの質問に対して別々の変数があると言っていますか? –

+0

ああ、申し訳ありませんが、2番目の部分で 'String'を使用する場所は間違っています。 [この質問をチェックする、それは関連する必要があります](http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – SomeJavaGuy

+0

@NateCraftヘイネイト'user_imput_int'を持つコードの2番目の部分を削除したようです。 – kbunarjo

答えて

1

あなたは、後者の、user_imput_string1user_imput_int、しかし、あなたのコードを見て、あなたはすでに二つの異なる変数を持っているように思われる30の値を比較するためにint型に文字列を変換する必要がありますまだストリングです。ここで

あなたは正しくint型に文字列から変換するために使用できるサンプルコードです:

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

また、サイドノートとして、あなたは間違っ入力をスペルしています。あなたは以下のコードはある例外

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

ありがとう、トンの男。また、私は入力を綴ることができないことについてあまりにも笑っている –

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

を引くことによってこれを行うことができ

+0

ありがとう。 Haventはまだ私のレッスンでinteger.parseIntになっていますが、知っておくと良いです=) –

関連する問題