1

Sorry if this question has been asked before I haven't seen it asked on stack overflow. The code prompts the user for their name and module mark and then prints the names and module marks to the user at the end.

public class Main
{
  public static void main( String args[] )
  {
      String name_array[] = new String[4];
      int mark_array[] = new int[4];
      System.out.println("Please enter in your name");
      String name = BIO.getString();
      System.out.println("Please enter in your module mark");
      int mark = BIO.getInt();

      name_array[0] += name;
      mark_array[0] += mark;

      int i = 1;
      int z = 1;
      while ( ! name.equals("END"))
      {
          while ( ! name.equals("END"))
          {
              System.out.println("Please enter in your name");
              name = BIO.getString();

              name_array[i] += name;
              ++i;
              break;
          }
          while ( ! name.equals("END"))
          {
              System.out.println("Please enter in your module mark");
              mark = BIO.getInt();

              mark_array[z] += mark;
              ++z;
              break;
          }
          if (i == name_array.length)
          {
              break;
          }
      }
      for (int y = 0; y < name_array.length; ++y)
      {
          System.out.println(name_array[y] + ' ' + mark_array[y]);
      }
  }
}

The code prints null before my string which is entered. If I enter Harry Houdini as the name, nullHarry Houdini will be printed.

How do I avoid this?

1
  • 1
    because if you have a string initialized as null and you are using += to append something to it, it will cast the null to be "null" and append the following value to "null", which finally results in something like "nullA" for example. Commented Nov 10, 2015 at 10:46

2 Answers 2

4

You are appending a value to the default value of a String[] element.

The default value for String is null, and your array is initialized with default values: String name_array[] = new String[4];.

Therefore, you get null[the name] as a value.

Here is a self-contained example:

String[] foo = new String[1];
foo[0] += "bar";
System.out.println(foo[0]);

Output

nullbar

Also worth of notice, the String literal for null is "null", e.g. System.out.println((String)null); will literally print null.

You may want to try assigning the value instead of appending it: name_array[0] = name;

Sign up to request clarification or add additional context in comments.

Comments

1

Change name_array[0] += name; to name_array[0] = name; in the beginning.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.