我必须完成这项任务..而且我不知道如何解决问题,以便我的程序能够正常运作。
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);
}
}
}
基本上我必须写一个程序,要求两个数字,然后告诉我哪一个更大。你能告诉我我做错了吗?
谢谢,伊娃
答案 0 :(得分: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,我建议你阅读更多关于它的内容。
答案 1 :(得分: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);
}
}
}
答案 2 :(得分:0)
只需使用in.nextInt()
代替in.nextLine()
。它将返回int
而不是字符串!