File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes New User Needs Some Help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "New User Needs Some Help" Watch "New User Needs Some Help" New topic

New User Needs Some Help

Ali Almarhoon

Joined: Sep 19, 2012
Posts: 1
Hello everyone,

I'm new to Java and new in this forum as well.
I'm studying Java right now and I hope that I learn from you.

I have a homework which is a program to make a program to arrange even numbers then odd numbers in integer array from a file that contains these numbers!

and this is my code I figured after 2 days I'm here to ask if there is an easier way to solve the same problem?!

here is the code:

I think it is kind of long code for this purpose isn't it ? any other ideas?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15093

Welcome to the Ranch.

You could combine some things in your code. For example, at the moment you're reading the whole file twice, first in lines 24 to 28, and then again in lines 40 to 47. I understand that you first need to know how many numbers there are because arrays have a fixed size, so you need to know how large to make the array. If you could use collection classes, for example java.util.ArrayList instead of arrays, then you wouldn't need to know beforehand how many numbers there are to read - an ArrayList grows automatically as you add elements to it.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
John McClellan
Ranch Hand

Joined: Aug 15, 2011
Posts: 35
Basically, yeah, what de Jong is saying is pretty valid. And even if you can't use an ArrayList for the end result, you should be able to use one temporarily and just convert it to an array at the end of the program. In the real world, you would generally just use an ArrayList and keep it, but depending on what your teacher wants you to do, you might have to waste time like that. Either way, by using an ArrayList, you can just read through the file one time and go ahead and add the numbers to the ArrayList during each step of your for loop. There's actually a method ArrayLists have called toArray().

Another thing you might do is call Array.sort() to get everything in ascending order, as opposed to using an explicit, double-nested for loop.
I agree. Here's the link:
subject: New User Needs Some Help
It's not a secret anymore!