What is wrong in this Code?

0 Rajesh Tekumulla · April 28, 2015
import java.util.Scanner;
class practice {
    public static void main(String args[]) {
        Scanner hell = new Scanner(System.in);
        String rajesh;
        System.out.println("Enter idiot : ");
        rajesh = hell.next();
        while (rajesh != "idiot") {
            System.out.println("So you are afraid of typing! Try again.");
        }
        System.out.println("So you are an Idiot!");
    }
}


Post a Reply

Replies

Oldest  Newest  Rating
0 Emil Peters · April 28, 2015
What do you mean whats wrong? The code works perfectly fine. The only thing is you're aswer is a string that keeps repeating because you're using a while loop.

Try using an if statement



if(rajesh != "idiot") {
System.out.println("So you are afraid of typing! Try again.");
}else{
System.out.println("So you are an Idiot!");
}
+1 Tera Java · April 28, 2015
While loop need an exit. If you don't specify, it will keep repeat the same code and become endless loop
+3 steven kitchener · April 28, 2015
Hi Rajesh,

The reason your code is not working is because the while loop doesnt wait for the user to enter another string after the initial one. This means that you are only ever checking the first string entered, resulting in an endless loop.

To fix this use the following code

Scanner hell = new Scanner(System.in);
String rajesh="";
System.out.println("Enter idiot : ");
while (rajesh != "idiot") {
rajesh = hell.next();
System.out.println("So you are afraid of typing! Try again.");
}
System.out.println("So you are an Idiot!");

Firstly we need to initialise the original String variable, you can just set it to an empty string as i have done above. This is done so that the while loop starts correctly.

Secondly we need to move the line rajesh = hell.next(); into the while loop. This is because we want the program to wait for some input before moving on with the rest of the code. Using the code above allows the user to enter a string and then the program will run its checks and either exit the loop or wait for some more input. 

However, the code as it is will never work correctly and this is because of how you are comparing Strings. When comparing Strings you should always use the .equals() method. == and != just will not work. So change the loop conditions to 
while(!rajesh.equals("idiot"){

and youll have a working program. If you are wondering what the ! mark at the beginning means it just means the opposite of what the method returns.... so in this case in plain English it means while rajesh does not equal "idiot". 

Hope this helps,

Steven
  • 1

Java / Android Development

107,231 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator