This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

New User Needs Some Help

 
Ali Almarhoon
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 15436
41
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
John McClellan
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic