PDA

View Full Version : Simple java help :s.



kaos
January 31st, 2011, 21:07
I am starting to learn java now properly so it might get me somewhere in life :D. I know next to nothing except


Adding
Subtracting
Multiplying
variables
what boolean means


I have this script



import java.util.Scanner;

public class myNumberInput {
static String username;
public static void main (String args[]){
do {
System.out.println("***Login***");
Scanner read = new Scanner(System.in);
System.out.println("Enter username");
username = read.next();
if (username == "Ian"){
System.out.println("Welcome back Ian");
}else{
System.out.println("Get out!");
}
}while (username != "Ian");
}
}


Could someone tell me what is wrong? It always prints out Get out! never welcome back :s.

THanks

the god father
January 31st, 2011, 21:09
System.out.println("Welcome back Ian");
}else{
System.out.println("Get out!");
thats your problem.. i think you can just delte it and recompile?

Steve
January 31st, 2011, 21:10
You're comparing objects with ==, try username.equals("Ian")) { and it should work.

kaos
January 31st, 2011, 21:16
And what do i change the do part to?

Steve
January 31st, 2011, 21:18
lolwat? Just change this,

if (username == "Ian"){

to this



if (username.equals("Ian")){

kaos
January 31st, 2011, 21:19
Sorted it thanks :D.

iiNarbz
January 31st, 2011, 21:26
Heres my copy of your code:


import java.util.Scanner;

public class Login {
static String username;
public static void main (String args[]){
do {
System.out.println("**Login**");
Scanner read = new Scanner(System.in);
System.out.println("Enter username");
username = read.next();
if (username.equals("Ian")){
System.out.println("Welcome back Ian");
}else{
System.out.println("Get out!");
}
}while (username != "Ian");

}
}

Trey
January 31st, 2011, 22:14
Heres my copy of your code:


import java.util.Scanner;

public class Login {
static String username;
public static void main (String args[]){
do {
System.out.println("**Login**");
Scanner read = new Scanner(System.in);
System.out.println("Enter username");
username = read.next();
if (username.equals("Ian")){
System.out.println("Welcome back Ian");
}else{
System.out.println("Get out!");
}
}while (username != "Ian");

}
}

Your while condition is still wrong.



Understand that == compares whether or not both variables point to the same object, not whether they are logically "equal". This is why Object has the equals method, of which you're supposed to override when you need to be able to compare instances of that class. By the way, you should always override both equals and hashCode appropriately when defining classes. Just remember to use the equals method when comparing object instances rather than ==.