2016-11-22 70 views
-4

我有這個任務我必須做..我不知道如何解決這個問題,以便我的程序能夠正常工作。我不知道如何解決這個問題

import java.util.Scanner; 
public class Work6{ 

    public static void main (String[] args){ 
     String x; 
     String y; 
     Scanner in = new Scanner(System.in); 
     System.out.println("Number 1: "); 
     x = in.nextLine(); 
     System.out.println("Number 2: "); 
     y = in.nextLine(); 

    if (x > y){ 
      System.out.println("Bigger number: " + x); 

     } 
     else if (y > x){ 
      System.out.println("Bigger number: " + y); 
     } 
    } 

} 

基本上我必須寫一個程序,要求兩個數字,然後告訴我哪一個更大。你能告訴我我做錯了什麼嗎?

感謝,伊娃

+4

你比較'字符串',而你應該在這裏比較'int'。 – SomeJavaGuy

+2

做'int x; int y'而不是'String x; String y;'而不是'in.nextLine()'做'Integer.parseInt(in.nextLine())'。 – Gendarme

+0

我實際上看到代碼甚至不會編譯相應的錯誤消息。 –

回答

0

變化x和y爲int:

import java.util.Scanner; 
public class Work6{ 

    public static void main (String[] args){ 
    int x; 
    int y; 
    Scanner in = new Scanner(System.in); 
    System.out.println("Number 1: "); 
    x = in.nextInt(); 
    in.nextLine(); 
    System.out.println("Number 2: "); 
    y = in.nextInt(); 
    in.nextLine(); 

if (x > y){ 
     System.out.println("Bigger number: " + x);` 

    } 
    else if (y > x){ 
     System.out.println("Bigger number: " + y); 
    } 
} 

} 
0

您掃描的字符串,然後你比較它的存儲位置,看看哪一個更大?

你需要做的是,掃描數不是字符串,並它將工作:

import java.util.Scanner; 
public class Work6{ 

    public static void main (String[] args){ 
    int x; 
    int y; 
    Scanner in = new Scanner(System.in); 
    System.out.println("Number 1: "); 
    x = in.nextInt(); 
    System.out.println("Number 2: "); 
    y = in.nextInt(); 

if (x > y){ 
     System.out.println("Bigger number: " + x);` 

    } 
    else if (y > x){ 
     System.out.println("Bigger number: " + y); 
    } 
} 

} 

你應該閱讀更多關於原語和對象以及如何比較它們。

編輯

它也可以更短:

public static void main (String[] args){ 
     int x; 
     Integer y; 
     Scanner in = new Scanner(System.in); 
     System.out.println("Number 1: "); 
     x = in.nextInt(); 
     System.out.println("Number 2: "); 
     y = in.nextInt(); 
     System.out.println(x > y ? "Bigger number: " + x : 
       x == y ? "They are equal" : "Bigger number: " + y); 
     } 

編輯2:

,您仍然可以使用字符串,如果你想要的,但你需要創建整出來的它:

 String x; 
     String y; 
     Scanner in = new Scanner(System.in); 
     System.out.println("Number 1: "); 
     x = in.nextLine(); 
     System.out.println("Number 2: "); 
     y = in.nextLine(); 
     int xInt = new Integer(x); 
     int yInt = new Integer(y); 
     System.out.println(xInt > yInt ? "Bigger number: " + x : x == y ? "They are equal" : "Bigger number: " + y); 

這段代碼做了什麼,它會讀取行,然後嘗試從中創建Integer。如果它不是一個有效的Integer,則會拋出異常,因此請小心。另外,它的unboxed int,我會建議你閱讀更多關於它。

0

只需使用in.nextInt()代替in.nextLine()。它會返回一個int而不是一個字符串!