0

I'm new in Java and I find it very complicated because of the errors that I come across with. So I have a problem with this piece of code:

Main Class:

public class Main {

  public static void main(String[] args){

     Answer a = new Answer();

     String ans = null;

     while(ans != "A"){

        ans = a.create();

        System.out.print(ans + "\n");

     }

  }

}

Answer class:

import java.util.Scanner;

public class Answer {

  public String create(){

    Scanner s = new Scanner(System.in);

    return s.next();

  }

}

I want the program to allow me to write something. Then, if what I've written hasn't been the letter A, the program must allow me to write something else, otherwise has to stop. But, even though I write "A", the program is still keeping on, allowing me to write something else. What's wrong with the code?

Arnau
  • 177
  • 10

1 Answers1

2

String can't be compared properly using the != operator. Instead you should use while(!ans.equals("A")). Secondly, try not to recreate the Scanner object in the create method. This is a resource waste.

Daman Arora
  • 87
  • 2
  • 6
  • Exception in thread "main" java.lang.NullPointerException at Main.main(Main.java:14) ( In line 14 I have while(!ans.equals("A")) ) – Arnau Feb 08 '15 at 12:17
  • This is because initially value of ans is null. You should set it to something which is not "A" – Daman Arora Feb 08 '15 at 12:20
  • Okay. It works! Although I don't understand why I got an error if I set ans = null – Arnau Feb 08 '15 at 12:28
  • The value of ans was not "null"(which is a String). It was null which means that it is nothing. When we use a method on a null object(like ans was) a NullPointerException is given. – Daman Arora Feb 08 '15 at 12:31