I want to compare three couples of input from Scanner
(just a quick test)
by using the Compare
method.
When I run this program, it returns false
for all three inputs even though there should be a true
in between. When I remove Scanner
and put in a String
myself, I get the correct result
First I thought that it's caused by the extra "Enter" button that stays in the buffer, but when I debugged it, there's nothing unwanted in the buffer and an extra call for input won't do any help.
import java.util.Scanner;
public class MainSector {
String Primary, Secondary;
MainSector(String Primary, String Secondary){
this.Primary = Primary;
this.Secondary = Secondary;
}
MainSector(int Primary, int Secondary) {
this.Primary = String.valueOf(Primary);
this.Secondary = String.valueOf(Secondary);
}
boolean Compare(MainSector x){
return (x.Primary == Primary && x.Secondary == Secondary );
}
}
public class Test {
public static void main(String[] args) {
Scanner u = new Scanner(System.in);
Scanner y = new Scanner(System.in);
System.out.println("Enter String:");
MainSector Sector1 = new MainSector(u.nextLine(),y.nextLine());
System.out.println("Enter String:");
MainSector Sector2 = new MainSector(u.nextLine(),y.nextLine());
System.out.println("Enter Integer:");
MainSector Sector3 = new MainSector(u.nextInt(),y.nextInt());
System.out.println(Sector1.Compare(Sector2));
System.out.println(Sector1.Compare(Sector3));
System.out.println(Sector2.Compare(Sector3));
}
}
It returns false
three times here even if the first two inputs are exactly the same. For example, I get the correct result with this:
System.out.println("Enter String:");
MainSector Sector1 = new MainSector("aa","bb");
System.out.println("Enter String:");
MainSector Sector2 = new MainSector("aa","bb");
System.out.println("Enter Integer:");
MainSector Sector3 = new MainSector(45,65);
It returns:
true
false
false