Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

input number to array --not displaying right item [code included]

 
Benjamin Mulder
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi:

I'm learning java on my own. I'm on arrays now.

This program is supposed to ask the user to input numbers. As soon as you hit zero (0) the program prints the largest item entered and then quits.

BUG: for some reason, the code sometimes works, sometimes it doesn't. More likely a logical error somewhere I can't see.

For example, you enter 9,3,4,5,7 sometimes it prints out 9. Sometimes it prints 7. It is always the first number or the last one.

Any ideas what's up? many thanks in advance.


[ June 26, 2004: Message edited by: Benjamin Mulder ]
 
sander hautvast
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>>//added number to array. What if user enters 1? off-by-one error avoided by adding 1
>>list = new int[ number + 1 ] ;

you don't add anything here. you create a new array of length [number]

rewrite your program and add values to an array using:
list[index]=number

and
>>int[] list = new int[ 0 ] ; //array initialiazed to zero length
doesn't make sense. initialiaze it to some other length

and
>>String inputNumber = "0" ; //initialized to zero
is not as good as
String inputNumber = null; //no reference yet

good luck
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic