Sorting an array of Strings
Okay, my first concern is that I'm pretty new to Java. It's my first language that I've ever looked at, and I'm just getting into it.
I'm trying to read from a .txt file a name and an integer value associated with that name, like for instance, Jimmy Bob Jones 123. I have several lines of different names with different integers associated with each, sorted alphabetically in the .txt file to begin with. That's not the issue really--though I haven't figured out how to do that, I figure it's pretty simple compared to what I have to do with those. I set each line as a new element in an array of Strings, and then I want to sort them based on the value of the integer that follows each. I know that each integer is 5 digits, so I'm thinking about some way to sort based on Integer.parseInt(name.substring(name.length - 5, name.length)) for each element, but it's not coming to me.
I mean, let's say I have the following in a .txt file:
Abigail 32534
Bo 28935
Chris 45000
Damian 13777
And I feed those into my .class and set each line to an array element, so it would be like arrayName[0] = "Abigail 32534" etc. for each. Convoluted question, sorry. How would I sort those strings based solely on the integer values, yet also retain the name that goes along with it?
Any help is appreciated, though I don't guarantee I'll understand : )
One easy (such a relative term) way is to create an Object, such as NameAndNumber, which has two member variables (name and number). When you read in your file, create objects of this type.
As for the sorting, this is a two step process:
1) Create a Comparator class to compare your objects
2) Populate a TreeSet which uses this comparator.
The TreeSet will be sorted automatically (based on your Comparator) and you can then iterate through it to retrieve instances of your object.
This all sounds much more complicated than it is. I have written some code to get you started.
// Your class
public class NameAndNumber {
private int m_nNumber;
private String m_sName;
// sets the name
public void setName(String sName) {
m_sName = sName;
// gets the name
public String getName() {
return m_sName;
// sets the number
public void setNumber(int nNumber) {
m_nNumber = nNumber;
// gets the number
public int getNumber() {
return m_nNumber;
// Your comparator
public class MyComparator implements Comparator {
// required by interface
public int compare(Object obj1, Object obj2) {
// throws ClassCastException if there is a problem - you will need to add
// handling if this is an issue
NameAndNumber objNan1 = (NameAndNumber) obj1;
NameAndNumber objNan2 = (NameAndNumber) obj2;
// will return the proper comparison based on the number
return (objNan1.getNumber() - objNan2.getNumber());
// Inside your "main" class
TreeSet setNumbers = new TreeSet(new MyComparator());
NameAndNumber objNameAndNumber = getNextListing(); // you need to provide this method, which gets the items one at a time
setNumbers.add(objNameAndNumber);Hope this helps.
Similar Messages
-
I need to sort an array of strings based on the number in each string.
Basically, I have a directory of files that all have the same name but each with a different number on the end.
example: image 1.jpg, image 2.jpg, etc.
When I use the List Directory function that returns an array of strings containing the file names in the directory, they don't come out in a 1, 2, 3, order like they appear in the directory. It sorts them character by character so that they come out like: 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22 etc.
Is there a simple way of sorting this array of strings with the file names (as above) so that they are in numerical order?It's a while since this thread was started, but I am sure others will have use for this so here goes:
The in-built array sort function sorts the strings the same way DOS and Windows do. Microsoft has fixed this in the Explorer that comes with XP, however the rest of the OS(s) still sorts the old way.
The attached "AlphaLogical String Array Sort" VIs will sort strings arrays the same way as the new XP Explorer. There are three different implementations of the sorting, one based on the Insertion sort algorithm, a Quick Sort based on recursive calls (the most elegant way, but unfortunately LabVIEW has too much overhead when doing recursive calls so this is actually a very slow alternative) and finally the fastest; a stack based Quick Sort. There is also a test VI that will show you how the different implementations perform.
I had not used recursive calls in LV much until I made the attached quick sort and was a bit disappointed by the fact that it is so slow, but it's a good learning example...The ability to do recursive calls this way was introduced in LV7 I believe...There is an example here on the zone that shows how you can calulate a factorial by using recursive calls, however - unlike for the quick sort (normally) - recursive calls are actually not the optimal solution for that calculation.
Message Edited by Mads on 09-13-2005 02:30 AM
MTO
Attachments:
AlphaLogical Sorting.zip 142 KB -
Help Sorting array of strings with numbers in them
Hello I need to sort an array of Strings of numbers. The order is not what I want it to be. instead of 1, 5, 20 it will go 1, 20, 5.
I did a google search for this and found some code that could fix this. The only problem is I tried using it as a method in my program and am getting a compile-time error that I'm not sure how to fix.
C:\Documents and Settings\Owner\Desktop\stringcompare.java:18: '(' or '[' expected
new Comparator<String>()
^I'm not sure what to do here. Any help would appreciated.import java.io.*;
class MyProgram{
//This is my old bubble sort method which screws up with numbers
public static String[] sort( String[] points)
boolean keepGoing = true;
while(keepGoing == true){
keepGoing = false;
for(int i = 0; i < points.length - 1; i ++)
if(points.compareToIgnoreCase(points[i + 1]) < 0)
String temp = points[i];
points[i] = points[i + 1];
points[i + 1] = temp;
keepGoing = true;
return points;
//This method reads a pre-existing text file
public static String[] readPoints() throws IOException
FileReader file = new FileReader("points.txt");
BufferedReader in = new BufferedReader(file);
String temp;
String[] list = new String[100];
int i = 0;
while (i < list.length)
temp = in.readLine();
if (temp != null)
list[i] = temp;
else
list[i] = " ";
i++;
in.close();
return list;
//rewrites file after being sorted
public static void savePoints(String[] points) throws IOException
FileWriter file = new FileWriter("points.txt");
BufferedWriter out = new BufferedWriter(file);
int i = 0;
while (i < points.length) // while the end of file is not reached
out.write(points[i]) ;
out.newLine();
i++;
out.flush();
out.close();
public static void main(String[]args) throws Exception{
String[]points = new String [100];
points = readPoints();
points = sort(points);
savePoints(points);
for(int i = 0; i < points.length - 1; i++)
System.out.println(points[i]);
The problem is that it doesn't sort as I would like it and I'm not sure how to get the comparator to work properly.
Edited by: myol on May 31, 2008 4:21 PM
Edited by: myol on May 31, 2008 4:23 PM -
I'm trying to sort an array of strings alphabetically. I used some code example in my java book as a guide line, and it compiles, but I keep getting exception errors.
Am I completely off or is there something simple I can throw in here?
public String[] sort()
int min;
String temp;
for (int index=0;index<list.length-1;index++)
min = index;
for (int scan = index+1;scan<list.length;scan++)
if (list[scan].compareTo(list[min])<0)
min=scan;
temp=list[min];
list[min]=list[index];
list[index]=temp;
return list;
}Exception in thread "main" java.lang.NullPointerException at StringCollection.sort<StringCollection.java:63> at Assignment7.main<Assigntment7.java:60>
in regards to Assignment7
case 'd': //sort the list
String [] temp = collection.sort();// line 60
for (int i =0; i<collection.size(); i++)
System.out.print(temp[i] + " ");
System.out.println();
break;in regards to the method within StringCollection
public String[] sort()
int min;
String temp;
for (int index=0;index<list.length-1;index++)
min = index;
for (int scan = index+1;scan<list.length;scan++)
if (list[scan].compareTo(list[min])<0) //line 63
min=scan;
temp=list[min];
list[min]=list[index];
list[index]=temp;
return list;
} -
I need to store a data array and include text that describes what the data is. (using for various configuration files.) Anyway, I would like to be able to save the string as part of the txt file, and somehow read it back, remove the (various length string), and display it in an indicator. All the while, not causing too much problem with the initial data array.
Thanks in advance!!There are several ways to do what you require. A simple method would be to use an ASCII text file. When writing one of those, you just need to basically build a gaint string starting with the description text you want. We like to call that a header. Once you've got the header, make some sort of delimiter like a bunch of "-" or two sets of ( EOL = End of Line = CRLF = \r\n ). After your delimiter, concatenate your array in string form or flatten your array from its native form into a string and tack it on the file (append).
See the (very quick) example attached.
Dan Press
www.primetest.com
Attachments:
fileheader.vi 41 KB -
Re: how to sort an array of type string
thanks bina and turing pest. well i can't use collections.sort or arrays.sort i need to create a method to sort. stupid instructor dont want to take advantage of this good java language. anyways i am able to do the sort but now OMG the whole data is crappy. formatting is gone everything is fukedd up. excuse my language.
public void getSort(String[] A)
String temp= A[0];
for(int i=0; i<A.length; i++)
for (int j=0; j<A.length-1-i; j++)
if(A[j].compareTo(A[j+1])>0)
temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
}and here is my output if i dont use the sort before it was not giving me an exception of arraysoutofbound and now it is
Item Number Cost_unit Sale_unit TotalSale profit Totalprofit
Binder 500 4 7 3300 1500 1500
Bookbag 350 5 10 3300 1750 3250
Calendar 300 3 8 2400 1500 4750
Shirt 800 4 6 4600 1600 6350
Notebook 400 1 2 800 400 6750
Schedule 876 1 2 1752 876 7626and if i turn my sort function on this is what i getg
Item Number Cost_unit Sale_unit TotalSale profit Totalprofit
4 500 7 Binder 3300 1500 1500
10 350 5 Bookbag 3300 1750 3250
3 300 8 Calendar 2400 1500 4750
4 6 800 Shirt 4600 1600 6350
1 2 400 Notebook 800 400 6750
1 2 876 Schedule 1752 876 7626
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at BookStore.main(BookStore.java:62)at this line it is giving me an exception
totalsale = test.totalSales(Integer.parseInt(str[1].trim()), Integer.parseInt(str[3].trim()));why is it all messed up?you create bean for your data like this
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
public String getName() {
return name;
public void setName(String name) {
this.name = name;
public int getAge() {
return age;
public void setAge(int age) {
this.age = age;
public String toString() {
return "Name : " + name + "\n" + "Age : " + age;
}after that, just sort it
public class Sample {
public static void main(String[] args) {
Person[] array = new Person[3];
array[0] = new Person("Dewi", 20);
array[1] = new Person("Agus", 21);
array[2] = new Person("Cindy", 18);
sortByName(array);
printOut(array);
private static void printOut(Person[] array) {
for(Person person : array){
System.out.println(person);
System.out.println();
private static void sortByName(Person[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = array.length - 1; j > i; j--) {
if (array[j].getName().compareTo(array[j - 1].getName()) < 0) {
Person temp = new Person(array[j].getName(), array[j].getAge());
array[j].setName(array[j - 1].getName());
array[j].setAge(array[j - 1].getAge());
array[j - 1].setName(temp.getName());
array[j - 1].setAge(temp.getAge());
} -
Using .sort() to sort an array of numbers NOT as strings
Hi,
is there a function or simple way to sort an array of numbers in order of their values and not as strings? E.g, have 100 come AFTER 9; (9, 100) not (100, 9).
Thanks.use the ARRAY.numeric parameter.
(and you can always use a custom sort function parameter for more customized sorts.) -
Sort an array of Application Class with respect to property
class MyClass
property string myProgram;
property string myType;
property string Description;
end-class;
Local array of MyClass &myProgArray;
&myProgArray.Sort("D");
I want to sort the Array in descending Order with respect to "myType".
How to provide "myType" parameter to sort method ?
Edited by: Mohsin on Oct 11, 2012 3:28 PMIf you add myType to the array then you can sort on that, assuming you have different values for myType.
According to PeopleBooks (8.51), API documentation;
Sort(order)
Note. This method works with arrays that have only one or two dimensions. You receive a runtime error if you try to use this method with an array that has more than two dimensions. -
How can i asign value to variables stored in an array of string?
hi
how can i asign value to variables stored in an array of string. i need to do it so that i can evaluate a math expression by usin those values. for example, i have a string array like [x, y, z, k]. now i need to asign 2.0 to x, 3.0 to y and so on. then if i type x+y, the program should evaluate the expression by usin x=2.0 and y=3.0. i am usin JEP for parsing and evaluating.
any help or suggestion would be much apreciated.
here is how i got the array
System.out.println("Type first expression");
BufferedReader br1 = new BufferedReader( new
InputStreamReader(System.in));
String expression1 = br1.readLine();
Jep jep = new Jep();
Node node1 = jep.parse(expression1);
TreeAnalyzer Ta1 = new TreeAnalyzer(node1);
Map<Variable, Integer> map1 = Ta1.getVariables();
/**The following will convert the variable names to a sorted array*/
/**with the result in varNames.*/
String[] res1 = new String[map1.size()];
int i=0;
for(Variable v:map1.keySet())
res1[i++]=v.getName();
System.out.println(Arrays.toString(res1));I could not use HashMap as those variables are to be retrieved from any expression typed by user and thus unknown to me beforehand.
System.out.println("Type first expression");
BufferedReader br1 = new BufferedReader( new
InputStreamReader(System.in));
String expression1 = br1.readLine();
Jep jep = new Jep();
Node node1 = jep.parse(expression1);
TreeAnalyzer Ta1 = new TreeAnalyzer(node1);
Map<Variable, Integer> map1 = Ta1.getVariables();then i have converted them to a sorted array
String[] res1 = new String[map1.size()];
int i=0;
for(Variable v:map1.keySet())
res1[i++]=v.getName();
System.out.println(Arrays.toString(res1));now i need to assign random double values to those variables.
and then use those double values for variables when evaluating the expression.
pls help. -
La fonction "Sort 1D Array" accepte en entrée un Tableau de n'importe quel type.
N'importe quel type ... hmmm, presque.
Returns a sorted version of array with the elements arranged in ascending order.
If array is an array of clusters, the function sorts the elements by comparing the first elements.
If the first elements match, the function compares the second and subsequent elements.
Résolu !
Accéder à la solution.oui, j'avais remarqué ... si on place le string en 1er dans le Cluster ... la fonction accepte.
Dans ce cas, le tri s'effectue sur le string et la fonction ne tient pas compte de la présence de la ref.
Dans l'absolu, vouloir "trier" des references entre elles n'a pas de sens.
Il faudrait trier l'équivalent U32 .... cela, à mon sens, est vide de sens.
par contre la fonction "recherche" accepte une Ref. ... mais rechercher une référence a du sens.
Les fonction "Tri" et "Recherche" ont toutes les deux cette même phrase dans leur "doc_help" respective.
"accepte un Tableau de n'importe quel type".
Pour la fonction "recherche", c'est parfaitement juste ... pour la fonction "Tri", cette phrase est fausse.
Je voulais pointer la doc qui parfois est lègèrement erronée.
Petit défaut de ma part, je suis perfectionniste ... mais je me soigne.
En fait, je suis perfectionniste uniquement pour ce qui a une réelle importance pour moi.
Pour le reste, je peux laisser tout pourrir en tas et enjamber le chose ... sans le moindre scrupule -
how can i sort an array by name and also by size
size is an int
name a string
whats the best way
thankyou.Thats my main class code...
as you can see i havent been able to work out the last few options on the menu
which include size and name
if anyone can get me started in the right direction id apreciate it very much thankyou!
import java.util.*;
import java.io.*;
* @author aRiFy
public class SpaceProgram {
static int TotalObjects = 0;
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws FileNotFoundException, IOException
menuApp();
//MENU
public static void menuApp() throws FileNotFoundException, IOException
SpaceObject[] Universe = new SpaceObject[1000000];
System.out.println("Welcome to the Universe Program\n\n");
char opt = 'x';
while (opt !='M')
System.out.println(""
+ "A - load from file\n"
+ "B - Display to screen\n"
+ "C - add a new space body\n"
+ "D - Write to file\n"
+ "E - Display by size\n"
+ "F - Display by name\n"
+ "G - Display moons of planet/dwarf planet\n"
+ "H - Display all space bodies in temperature range\n"
+ "I - Display a given space body\n"
+ "J - Display largest space body\n"
+ "K - Display smallest space body\n"
+ "L - Display most distant object\n"
+ "M - Exit Program\n");
System.out.print("Enter your Menu option: ");
String s = sc.next();
opt = s.charAt(0);
switch (opt)
case 'A':
case 'a':
input(Universe);
break;
case 'B':
case'b':
displayToScreen(Universe);
break;
case 'C':
case 'c':
addObject(Universe);
break;
case 'D':
case'd':
addObjectToFile(Universe);
break;
case 'E':
case'e':
sortSize(Universe);
break;
case 'F':
case'f':
sortName(Universe);
break;
case 'G':
case'g':
break;
case 'H':
case'h':
tempRange(Universe);
break;
case 'I':
case'i':
SearchObjects(Universe);
break;
case 'J':
case'j':
findLargest(Universe);
break;
case 'K':
case'k':
findSmallest(Universe);
break;
case 'L':
case'l':
//mostDistant(Universe);
break;
case 'M':
case'm':
System.exit(0);
break;
default:
//msg = "";//wrongValue();
break;
//ENDMENU
//Add Space Object To File
public static SpaceObject[] addObjectToFile(SpaceObject[] Universe ) throws FileNotFoundException, IOException
System.out.println("What is the name of the text file you would like to write to? ");
String textfile = sc.next();
File f =new File(textfile);
if(!f.exists())
f.createNewFile();
System.out.println("File Created");
System.out.print("Add a Star, Planet, Dwarfplanet or Moon? "); //Asks to add
String adding = sc.next();
if (adding.equalsIgnoreCase("star")) //Add Star
String OType="Star";
System.out.println("Enter the name of the Star: ");
String OName = sc.next();
System.out.println("Enter the Radius: ");
String ORadius = sc.next();
double ORadiusD=Double.parseDouble(ORadius);
System.out.println("Class O -blue");
System.out.println("Class B -blue white");
System.out.println("Class A -white");
System.out.println("Class F -yellowish white");
System.out.println("Class G -yellow");
System.out.println("Class K -orange");
System.out.println("Class M -red");
System.out.println("Class W -superluminous blue");
System.out.println("Class L -dark red");
System.out.println("Class T -cool brown dwarf");
System.out.println("Class Y -ultra cool brown dwarf");
System.out.println("Class C -carbom star");
System.out.println("Class S -between a class M and carbon star");
System.out.println("Class D -white dwarf");
System.out.println("Enter A Spectral Type: ");
String ST = sc.next();
System.out.println("I -supergiants");
System.out.println("II -bright giants");
System.out.println("III -normal giants");
System.out.println("IV -subgiants");
System.out.println("V -dwarfs");
System.out.println("VI -subdwarfs");
System.out.println("VII -white dwarfs");
System.out.println("Enter Yerkes Spectral Classification: ");
String YSC = sc.next();
System.out.println("Enter the Distance: ");
String Distance = sc.next();
double DistanceD=Double.parseDouble(Distance);
Universe[TotalObjects]= new Star(OType, OName, ORadiusD, ST, YSC, DistanceD);
Universe[TotalObjects].display();
TotalObjects = TotalObjects +1;
System.out.println("Star Added");
PrintWriter outputStream = null;
try
outputStream = new PrintWriter(new FileOutputStream(textfile, true));
catch(FileNotFoundException e)
System.out.println("Error opening spacebodies.txt");
System.exit(0);
System.out.println("Writing to file");
outputStream.println(OType);
outputStream.println(OName);
outputStream.println(ORadiusD);
outputStream.println(ST);
outputStream.println(YSC);
outputStream.println(DistanceD);
outputStream.println("\n");
outputStream.close();
System.out.println("Written to file succesfully");
else if (adding.equalsIgnoreCase("planet")) //Add Planet
String OType="Planet";
System.out.println("Enter the name of the Planet: ");
String OName = sc.next();
System.out.println("Enter the Radius: ");
String ORadius = sc.next();
double ORadiusD=Double.parseDouble(ORadius);
System.out.println("Enter the Mass: ");
String PMass = sc.next();
System.out.println("Enter the Orbital Period: ");
String POB = sc.next();
double POBD=Double.parseDouble(POB);
System.out.println("Enter the Temperature: ");
String PTemp = sc.next();
double PTempD=Double.parseDouble(PTemp);
Universe[TotalObjects]= new Planet(OType, OName, ORadiusD, PMass, POBD, PTempD);
Universe[TotalObjects].display();
TotalObjects = TotalObjects +1;
System.out.println("Planet Added");
PrintWriter outputStream = null;
try
outputStream = new PrintWriter(new FileOutputStream(textfile, true));
catch(FileNotFoundException e)
System.out.println("Error opening spacebodies.txt");
System.exit(0);
System.out.println("Writing to file");
outputStream.println(OType);
outputStream.println(OName);
outputStream.println(ORadiusD);
outputStream.println(PMass);
outputStream.println(POB);
outputStream.println(PTempD);
outputStream.println("\n");
outputStream.close();
System.out.println("Written to file succesfully");
else if (adding.equalsIgnoreCase("dwarfplanet")) //add dwarfplanet
String OType="DwarfPlanet";
System.out.println("Enter the name of the Dwarf Planet: ");
String OName = sc.next();
System.out.println("Enter the Radius: ");
String ORadius = sc.next();
double ORadiusD=Double.parseDouble(ORadius);
System.out.println("Enter the Mass: ");
String PMass = sc.next();
System.out.println("Enter the Temperature: ");
String PTemp = sc.next();
double PTempD=Double.parseDouble(PTemp);
Universe[TotalObjects]= new DwarfPlanet(OType, OName, ORadiusD, PMass, PTempD);
Universe[TotalObjects].display();
TotalObjects = TotalObjects +1;
System.out.println("DwarfPlanet Added");
PrintWriter outputStream = null;
try
outputStream = new PrintWriter(new FileOutputStream(textfile, true));
catch(FileNotFoundException e)
System.out.println("Error opening spacebodies.txt");
System.exit(0);
System.out.println("Writing to file");
outputStream.println(OType);
outputStream.println(OName);
outputStream.println(ORadiusD);
outputStream.println(PMass);
outputStream.println(PTempD);
outputStream.println("\n");
outputStream.close();
System.out.println("Written to file succesfully");
else if (adding.equalsIgnoreCase("moon"))
String OType="Moon";
System.out.println("Enter the name of the Moon: ");
String OName = sc.next();
System.out.println("Enter the Radius: ");
String ORadius = sc.next();
double ORadiusD=Double.parseDouble(ORadius);
System.out.println("Enter the Mass: ");
String MMass = sc.next();
System.out.println("Enter the Planet: ");
String Planet = sc.next();
System.out.println("Enter the Temperature: ");
String MTemp = sc.next();
double MTempD=Double.parseDouble(MTemp);
Universe[TotalObjects]= new Moon(OType, OName, ORadiusD, MMass, Planet, MTempD);
Universe[TotalObjects].display();
TotalObjects = TotalObjects +1;
System.out.println("Moon Added");
PrintWriter outputStream = null;
try
outputStream = new PrintWriter(new FileOutputStream(textfile, true));
catch(FileNotFoundException e)
System.out.println("Error opening spacebodies.txt");
System.exit(0);
System.out.println("Writing to file");
outputStream.println(OType);
outputStream.println(OName);
outputStream.println(ORadiusD);
outputStream.println(MMass);
outputStream.println(Planet);
outputStream.println(MTempD);
outputStream.println("\n");
outputStream.close();
System.out.println("Written to file succesfully");
else
System.out.println("You have entered an invalid input please try again");//invalid input
addObjectToFile(Universe);
return Universe;
public static SpaceObject[] addObject(SpaceObject[] Universe ) throws FileNotFoundException
System.out.print("Add a Star, Planet, Dwarfplanet or Moon? "); //Asks to add
String adding = sc.next();
if (adding.equalsIgnoreCase("star")) //Add Star
String OType="Star";
System.out.println("Enter the name of the Star: ");
String OName = sc.next();
System.out.println("Enter the Radius: ");
String ORadius = sc.next();
double ORadiusD=Double.parseDouble(ORadius);
System.out.println("Class O -blue");
System.out.println("Class B -blue white");
System.out.println("Class A -white");
System.out.println("Class F -yellowish white");
System.out.println("Class G -yellow");
System.out.println("Class K -orange");
System.out.println("Class M -red");
System.out.println("Class W -superluminous blue");
System.out.println("Class L -dark red");
System.out.println("Class T -cool brown dwarf");
System.out.println("Class Y -ultra cool brown dwarf");
System.out.println("Class C -carbom star");
System.out.println("Class S -between a class M and carbon star");
System.out.println("Class D -white dwarf");
System.out.println("Enter A Spectral Type: ");
String ST = sc.next();
//char STc = ST.charAt(0);
System.out.println("I -supergiants");
System.out.println("II -bright giants");
System.out.println("III -normal giants");
System.out.println("IV -subgiants");
System.out.println("V -dwarfs");
System.out.println("VI -subdwarfs");
System.out.println("VII -white dwarfs");
System.out.println("Enter Yerkes Spectral Classification: ");
String YSC = sc.next();
System.out.println("Enter the Distance: ");
String Distance = sc.next();
double DistanceD=Double.parseDouble(Distance);
Universe[TotalObjects]= new Star(OType, OName, ORadiusD, ST, YSC, DistanceD);
Universe[TotalObjects].display();
TotalObjects = TotalObjects +1;
System.out.println("Star Added");
else if (adding.equalsIgnoreCase("planet")) //Add Planet
String OType="Planet";
System.out.println("Enter the name of the Planet: ");
String OName = sc.next();
System.out.println("Enter the Radius: ");
String ORadius = sc.next();
double ORadiusD=Double.parseDouble(ORadius);
System.out.println("Enter the Mass: ");
String PMass = sc.next();
System.out.println("Enter the Orbital Period: ");
String POB = sc.next();
double POBD=Double.parseDouble(POB);
System.out.println("Enter the Temperature: ");
String PTemp = sc.next();
double PTempD=Double.parseDouble(PTemp);
Universe[TotalObjects]= new Planet(OType, OName, ORadiusD, PMass, POBD, PTempD);
Universe[TotalObjects].display();
TotalObjects = TotalObjects +1;
System.out.println("Planet Added");
else if (adding.equalsIgnoreCase("dwarfplanet")) //add dwarfplanet
String OType="DwarfPlanet";
System.out.println("Enter the name of the Dwarf Planet: ");
String OName = sc.next();
System.out.println("Enter the Radius: ");
String ORadius = sc.next();
double ORadiusD=Double.parseDouble(ORadius);
System.out.println("Enter the Mass: ");
String PMass = sc.next();
System.out.println("Enter the Temperature: ");
String PTemp = sc.next();
double PTempD=Double.parseDouble(PTemp);
Universe[TotalObjects]= new DwarfPlanet(OType, OName, ORadiusD, PMass, PTempD);
Universe[TotalObjects].display();
TotalObjects = TotalObjects +1;
System.out.println("DwarfPlanet Added");
else if (adding.equalsIgnoreCase("moon"))
String OType="Moon";
System.out.println("Enter the name of the Moon: ");
String OName = sc.next();
System.out.println("Enter the Radius: ");
String ORadius = sc.next();
double ORadiusD=Double.parseDouble(ORadius);
System.out.println("Enter the Mass: ");
String MMass = sc.next();
System.out.println("Enter the Planet: ");
String Planet = sc.next();
System.out.println("Enter the Temperature: ");
String MTemp = sc.next();
double MTempD=Double.parseDouble(MTemp);
Universe[TotalObjects]= new Moon(OType, OName, ORadiusD, MMass, Planet, MTempD);
Universe[TotalObjects].display();
TotalObjects = TotalObjects +1;
System.out.println("Moon Added");
else
System.out.println("You have entered an invalid input please try again");//invalid input
addObject(Universe);
return Universe;
//read text file
public static void input(SpaceObject[] Universe) throws FileNotFoundException
System.out.println("What is the name of the text file you would like to write to? ");
String textfile = sc.next();
File f =new File(textfile);
Scanner infile;
infile = new Scanner(new File("spacebodies.txt"));
while (infile.hasNext())
String SpaceType = infile.next();
String OType = infile.nextLine();
String OName = infile.nextLine();
double ORadius = infile.nextDouble();
if (SpaceType.equals("Star"))
String ST = infile.next();
String YSC = infile.next();
infile.nextLine();
double Distance = infile.nextDouble();
Universe[TotalObjects]= new Star("Star", OName, ORadius, ST, YSC, Distance);
Universe[TotalObjects].display();
TotalObjects = TotalObjects +1;
System.out.println("");
else if (SpaceType.equals("Planet"))
String PMass = infile.next();
infile.nextLine();
double POB = infile.nextDouble();
double PTemp = infile.nextDouble();
Universe[TotalObjects]= new Planet("Planet", OName, ORadius, PMass, POB, PTemp);
Universe[TotalObjects].display();
TotalObjects = TotalObjects +1;
System.out.println("");
else if (SpaceType.equals("DwarfPlanet"))
String PMass = infile.next();
infile.nextLine();
double PTemp = infile.nextDouble();
Universe[TotalObjects]= new DwarfPlanet("DwarfPlanet", OName, ORadius, PMass, PTemp);
Universe[TotalObjects].display();
TotalObjects = TotalObjects +1;
System.out.println("");
else if (SpaceType.equals("Moon"))
String MMass = infile.next();
String Planet = infile.nextLine();
infile.nextLine();
double MTemp = infile.nextDouble();
Universe[TotalObjects]= new Moon("Moon", OName, ORadius, MMass, Planet, MTemp);
Universe[TotalObjects].display();
TotalObjects = TotalObjects +1;
System.out.println("");
else{
System.out.println("Error");
//Display To Screen
public static void displayToScreen(SpaceObject[] Universe)
System.out.println("Displaying Added Space Objects\n");
if (TotalObjects>0)
for (int i=0;i<TotalObjects;i++)
Universe.display();
System.out.println("");
//Search Objects
public static void SearchObjects(SpaceObject[] Universe)
System.out.println("Please Enter a Space Body to Search: ");
String SBody = sc.nextLine();
SBody = sc.nextLine();
for (int i=0;i<TotalObjects;i++)
if (Universe[i].OName.equalsIgnoreCase(SBody))
Universe[i].display();
//Find Largetst
public static void findLargest(SpaceObject[] Universe)
double MaxRadius = Universe[0].ORadius;
int Max=0;
for (int i=0;i<TotalObjects;i++)
if (MaxRadius < Universe[i].ORadius)
MaxRadius = Universe[i].ORadius;
Max = i;
Universe[Max].display();
//Find Smallest
public static void findSmallest(SpaceObject[] Universe)
double MaxRadius = 900000;
int Max=0;
for (int i=0;i<TotalObjects;i++)
if (MaxRadius < Universe[i].ORadius)
MaxRadius = Universe[i].ORadius;
Max = i;
Universe[Max].display();
//Temp Range
public static void tempRange(SpaceObject[] Universe)
public static void mostDistant(SpaceObject[] Universe)
public static void sortSize(SpaceObject[] Universe)
public static void sortName(SpaceObject[] Universe)
-
How to sort an array of objects?
I need to sort an array of objects. Each object has serial number, and other properties. I need to sort it by serial number.
Do a java.util.Arrays.sort(). The method has quite a few overloads, so I'll give a complete example this time:import java.util.*
public class SortDemo {
public static void main(String args) {
SimpleObject[] objs = new SimpleObject[10];
for (int i=0; i<10; i++)
objs=new SimpleObject();
dump(objs);
Comparator c = new SimpleComparator();
Arrays.sort(objs, c);
dump(objs);
static void dump(Object[] o) {
for (int i=0; i<o.length; i++)
System.out.print(o[i] + " ");
/** Object to demonstrate comparing with **/
class SimpleObject {
private int n = (int) (10*Math.random());
public String toString() {
return String.valueOf(getNumber());
public int getNumber() {return n;}
/** The custom comparator **/
class SimpleComparator implements Comparator {
public int compare(Object o1, Object o2) {
return ((SimpleObject) o1).getNumber() - ((SimpleObject) o2).getNumber();
public boolean equals(Object o) {return false;}
}I could have made the SimpleObject class "Comparable", but a design like this allows more flexibility so I decided to use another class for the Comparator. -
Store and sort large amounts of Strings
Hi, everyone.
I would be very grateful if someone could help me with the two questions I have.
I am working on the program, which has to turn a billion of integers in words, sort them and find a certain character.
My first question is how can I process my convertion of integer other than in loop? ( loop takes about an hour). The algorithm works well for smaller iterations.
Where can I store such large amounts of strings to be able to sort them then and work with them?
Thank you in advance.I will try to explain it better.
I have written a function, which converts integers in
words. I call it in a for loop for all the integers
from 1 to 999999999. It works well for smaller
integers, but takes too long to complete all the
cycles for 999999999. This seems nonsensical. But yes it will take a long time.
Do you in fact mean that you are converting integers INTO words? Maybe?
I try to store each converted integer in an array of
Strings, but obviously it is a lot of Strings. Yes it would seem that is in fact what you do mean...
would like to find out what kind of array I can use
to store all those Strings. I have to sort them then,
concatenate all of them and get a certain character.You can store them into a file instead.
Why do you want to sort AND concatenate them? This also makes no sense and will be difficult.
Is it better?
Thank you.Not really.
At any rate in order to solve this problem I think you are going to
a) have to live with buffering to disk
b) use multiple threads
c) get a more realistic requirement then concatenating 900 million Strings together because that won't be happening -
Using Comparator to sort an array
I didn't undersatnd why a comparator is used for sorting an arry in ascending order
For descending also i didn't understand the logic it follows
I have a program which works for both asc and desc using comparator
import java.io.*;
import java.util.*;
class Ascend implements Comparator<Integer>
public int compare(Integer i1, Integer i2)
return i1.compareTo(i2);
class Descend implements Comparator<Integer>
public int compare(Integer i1, Integer i2)
return i2.compareTo(i1);
public class ArrayDemo {
public static void main(String[] args) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many Elements");
int size = Integer.parseInt(br.readLine());
Integer[] arr = new Integer[size];
for(int i=0 ;i<size;i++)
System.out.println("Enter "+(i+1)+"th element");
arr=Integer.parseInt(br.readLine());
Arrays.sort(arr, new Ascend());
System.out.println("The sorted array in Ascending order is:");
display(arr);
Arrays.sort(arr, new Descend());
System.out.println("The sorted array in Descending order is:");
display(arr);
static void display(Integer[] a)
for(Integer i:a)
System.out.print(i+"\t");
System.out.println("");
can anyone explain
1 why do we are passing an object of Ascend class(code was there in above program) to Arrays.sort() method
2. what will be retruned by that object
3 why do we are passing an object of Descend class(code was there in above program) to Arrays.sort() method
4. what will be retruned by that object
5 We can sort the array in ascending simply by using Arrays.sort(arr) method directly, then what was usage of Ascend class
If I am wrong in understating the code of the above pls correct me and tell me the actual usage of Comparator<T> interfance and its method compare()
Pls....camickr wrote:
Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.am sorry!! pls find the code and try to execute it. It works fine in sorting
import java.io.*;
import java.util.*;
class Ascend implements Comparator<Integer>
public int compare(Integer i1, Integer i2)
return i1.compareTo(i2);
class Descend implements Comparator<Integer>
public int compare(Integer i1, Integer i2)
return i2.compareTo(i1);
public class ArrayDemo {
public static void main(String[] args) throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many Elements");
int size = Integer.parseInt(br.readLine());
Integer[] arr = new Integer[size];
for(int i=0 ;i<size;i++)
System.out.println("Enter "+(i+1)+"th element");
arr=Integer.parseInt(br.readLine());
Arrays.sort(arr, new Ascend());
System.out.println("The sorted array in Ascending order is:");
display(arr);
Arrays.sort(arr, new Descend());
System.out.println("The sorted array in Descending order is:");
display(arr);
static void display(Integer[] a)
for(Integer i:a)
System.out.print(i+"\t");
System.out.println("");
Can u explain the below
what happens actually when Arrays.sort(arr,new Descend() ) is executed -
How to compare array of String with column of a table
Hi,
i have a array of string(say array is of length 1000). I want to
compare those string in array with one table column
- whether that table column has a string
if yes
do nothing.
if no
then insert that string into table.
- whether table has obsolete row i.e, the one present in table and
not in array
then delete that row.
How do i go about this, because i see, it is not feasible to loop
through array and search table to find new string OR loop through each
row from table to find some obsolete row
How can i accomplish this task more feasibly(without running query for
each string, for comparission)? Is there any way to find this kind of
problem. I would have been easy if i had to compare two tables(with
UNION and INTERSECT), but it is not the case.
thanks,
kath.I'm not sure, whether I understand your problem correctly. Only two comments:
- if both arrays are sorted, all can be done running exactly once simultaneously through both arrays.
- if the column is marked as UNIQUE, all column strings will be different. I.e. you cannot insert the same string a second time.
Regards Thomas
Maybe you are looking for
-
ITunes upgraded and now crashes computer
I upgraded to the new 7.0 iTunes and for about 10 minutes it worked fine. I then changed my library view to the screen the shows the "jukebox-like" images of the album cover. Just a couple of minutes in that view froze my entire computer and now iTun
-
Conversion does not look the same?
I converted a pdf file to a word document last night and the page does not look the same. It is a weekly time log and the lines are messed up and the font is not placed correctly. Is there any way to fix this?
-
IPad int'l time & date problems
I was at the Apple Store today asking questions about the iPad and it's ability to handle international times and dates. On my MPB and MBAir I have time on the computer, iCal, etc set for the 24 hour clock. As well as the calendar set as, day | date
-
Too many items in submenu! help!
I need to put nearly 20 items in the submenu, it is too long. When I change the width, so that 3 submenu items can be in one row, it works, but I have to change all the submenu width. Then I try to have 2 menu bar with 2 sets of spryasset, it don't w
-
What is the «iPhoto Library link» file for ?
Hi ... In the Pictures (Images in French) folder, what is the «iPhoto Library link» alias file for ? It points to the «iPhoto Library»in the same folder.