2016-11-22 66 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而不是一个字符串!