刚开始学JAVA,这是我遇到的第一个问题。
这个程序是判断输入的两个数是否相同,这里比较了三种数据类型,用了方法重载。
public class second_item {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入两个整数进行比较:");
int num1 = sc.nextInt();
int num2 = sc.nextInt();
System.out.println("输入两个长整型进行比较:");
long num3 = sc.nextLong();
long num4 = sc.nextLong();
System.out.println("输入两个双精度进行比较:");
double num5 = sc.nextDouble();
double num6 = sc.nextDouble();
boolean f1 = compare(num1,num2);
System.out.println(f1);
boolean f2 = compare(num3,num4);
System.out.println(f2);
boolean f3 = compare(num5,num6);
System.out.println(f3);
}
public static boolean compare(int a,int b) {
return a==b;
}
public static boolean compare(long a,long b) {
return a==b;
}
public static boolean compare(double a,double b) {
return a==b;
}
}
我的错误,先是 long num3 = sc.nextLong(); 这里的nextLong我写的nextInt(),因为我不知道有nextLong(),我以为输入语句都是nextInt()。
改正之后,还是不行,我记得长整型后面是带“l”或“L”的,我输入带L的数就会报错,不带L就OK。
在网上看一哥们儿说的:“Scans the next token of the input as a long”。意思就是不用自己加L,它会自己扫描为长整型。