Reputation: 153
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?
Upvotes: 1
Views: 2107
Reputation: 48404
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;
Upvotes: 4
Reputation: 3457
Change name_array[0] += name;
to name_array[0] = name;
in the beginning.
Upvotes: 1