Tom Lenc
Tom Lenc

Reputation: 765

Why is this code keep being "terminated"?

I have this code in Eclipse:

package test;

import java.util.Scanner;

class test{
    public static void main(String args[]){
        Scanner Input = new Scanner(System.in);
        if (Input.equals("payday2")){
        System.out.println(Input);
        }
    }           
}

Now when I try to start the code/aplication, it terminates itself.

Any ideas why that happens?

Upvotes: 1

Views: 89

Answers (3)

Reimeus
Reimeus

Reputation: 159754

You never read input from the Scanner instance so the application doesnt block

String text = input.nextLine(); 
if ("payday2".equals(text)) {
  ...

Upvotes: 1

Jean-François Savard
Jean-François Savard

Reputation: 21004

You instantiate the Scanner as a variable named Input but never try to read.

Your condition

if (Input.equals("payday2")){

will only check if the Scanner object is equals to the string "payday2" which will always be false, hence the program terminate.

If you want to read, you need to do Input.nextLine().

I dont know about eclipse, but Netbeans would give a warning "equals on incompatible type" with this line.

Also, you should not name your variable with a capital letter as by convention, only class name should start with a capital.

So your fixed program would be

Scanner input = new Scanner(System.in);
String value = input.nextLine();
if ("payday2".equals(value)) {
    System.out.println(value);
} 
  • Notice that I kept the string in a variable to display it as displaying input would call toString of the Scanner object which is probably not what you expected.
  • Notice that I also compared the string in reverse order which is a good practice to avoid NPE even if not really needed here.

Upvotes: 3

John
John

Reputation: 3797

I think you mean to do:

String in = Input.nextLine();
if(in.equals("payday2"))
{
    System.out.println(in);
}

Note: in Java 7 you can do the following:

String in = Input.nextLine();
switch(in)
{
    case "payday2":
        System.out.println(in)
        break;
    case "payday the heist":
        //...
        break;
}

Which makes it much easier to manage different input cases.

Upvotes: 0

Related Questions