473,416 Members | 1,656 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,416 software developers and data experts.

Store the numbers in a array in Java

shashankraj1231
I am trying to write a Java program in which we would take input from the user until
the user enters -1. The input would be integers and has to be stored in a integer array.

I am a newbie in Java and i am trying to self study here. Please tell me what am i doing wrong. It would be of great help.

Expand|Select|Wrap|Line Numbers
  1. class storearray{
  2.     public static void main(String args[]) throws IOException
  3.     {
  4.         BufferedReader dis= new BufferedReader(new InputStreamReader(System.in));
  5.         int arr[]= new int[10];
  6.         System.out.println("Enter elements of an array");
  7.         System.out.println("Enter -1 to quit");
  8.         int i=0;
  9.         String data;
  10.         System.out.flush();
  11.         for(i=0;arr[i]!= -1; i++){
  12.                 data= dis.readLine();
  13.                 try{
  14.                 arr[i]= Integer.parseInt(data);
  15.                 } catch(NumberFormatException e)
  16.                 {
  17.                     System.out.println("Invalid FOrmat");
  18.                     //arr[i]=0;
  19.                 }
  20.               System.out.println("The values of the array are :"+" "+arr[i]+" "+"i= "+i);
  21.             } 
  22.             for(int x:arr)
  23.                 System.out.println(x);
  24.         }
  25.  
  26.     }
  27.  
May 25 '10 #1

✓ answered by jkmyoung

for(i=0;arr[i]!= -1; i++)
The problem is that in a for loop, the increment runs before the conditional check.
So let's say the first number is -1. You put -1 in arr[0].
Then i++ -> i = 1
The for loop checks, is arr[1] != -1? No.

But you meant to check arr[0], not arr[1].

You might want to have a different check INSIDE the for loop, eg:
if number entered was -1, break out of the for loop.

4 11580
Dheeraj Joshi
1,123 Expert 1GB
Your for loop need some changes
Expand|Select|Wrap|Line Numbers
  1. for(i=0;arr[i]!= -1; i++)
  2.  
Your code runs till arr[i] != -1
Your program will throw array index out of bound exception. Since you defined array of size 10 and your for loop do not terminate. User is able to add 11th elements.

Your for loop should look like
Expand|Select|Wrap|Line Numbers
  1. for(int iCount=0;iCount<10;iCount++)
  2. {
  3.         //Logic here
  4. }
  5.  

Please catch a generic exception and see what exception it will throw.

Regards
Dheeraj Joshi
May 25 '10 #2
jkmyoung
2,057 Expert 2GB
for(i=0;arr[i]!= -1; i++)
The problem is that in a for loop, the increment runs before the conditional check.
So let's say the first number is -1. You put -1 in arr[0].
Then i++ -> i = 1
The for loop checks, is arr[1] != -1? No.

But you meant to check arr[0], not arr[1].

You might want to have a different check INSIDE the for loop, eg:
if number entered was -1, break out of the for loop.
May 25 '10 #3
@jkmyoung
Thank you very much for that explanation, I understand the For-Loop much better now. I was not aware that the the increment runs before the conditional check.
I corrected the program by adding
if (arr[i]== -1)
break;

and it works like magic now.

Regards,
Shashank.
May 27 '10 #4
@dheerajjoshim
Thank you for the explanation of the exception. That gave me a clear understanding of how it works.

Regards,
Shashank.
May 27 '10 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

11
by: Colin Steadman | last post by:
Hope this makes sense! I'm building an ASP page which allows uses to add items to an invoice via a form, ie: Item No Part No Order No Quanity Units Price VAT ------- ...
3
by: jacob nikom | last post by:
Hi, I would like to be able to store numerical array in MySQL. I am really looking for the solution to store it in the one field only. For example, I have a matrix, which I want to store in...
33
by: patrick_woflian | last post by:
hey guys, im just writing a basic calculation at the moment, before building on it for an A-Level piece of work. i can add/divide etc... two numbers together yet i am having a major problem with...
0
by: Ryan Liu | last post by:
How to read NIC card serial numbers or MAC address , Hard Drive serial numbers in Java or Delphi or C/C++ or C#? Thanks, Ryan
12
by: pallavi27 | last post by:
hii, i am working in c and my problem is that i have created a file which contains numbers,i want to store these numbers in an array.,please guide me how to go about it this is the part of code that...
2
by: wing ver ka gundam | last post by:
THanks~ this is the example and my quote are below Write a program in JAVA that allows the user to input 5 ints. The program will then output these five values in reverse order. The program will...
6
by: penny | last post by:
In this assignment we shall look at a possible representation of rational numbers in java using objects. The java language represents rational numbers using the same representation used for other...
0
by: rajamohammed | last post by:
Can anyone please help me how to store byte array in SQL database? Please give some sample code. Thanks in advance.
2
by: tuananh87vn | last post by:
Hi ! can anyone help me with the following topic: Find All Duplicates in a List of Numbers - Array implementation - -InitializeTree() -AddNode() -Add into...
5
rahulephp
by: rahulephp | last post by:
Hi there, can you please help me? i have data in array and i want to insert it in a single table. structure of table and array to be store is shown below: Please let me know how to store...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.