Reputation: 104
This program is suppose to read a file that has the item, code, and price. I have it outputted to the screen to its represented index in the array. For example Item[0], Code[0] ,Price[0] all through each possible index. The program is suppose to sort through the Code values from smallest to biggest using the bubble sort method. I have gotten this correct so far. My problem is how do you get the all three to there respect variables. For example if wine ,1298, 8.99 are all in their respective index at [3] and then when the Code value is put into the bubble sort it is swapped to index [0]. How do you get the index of the price and Item to switch to index [0] also. That is my problem. We have just learned basic java so far in class so I don't know anything advanced yet.
import java.io.File;
import java.util.Scanner;
import java.util.*;
public class test2 {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\Isiah\\Desktop\\xfiles.txt");
Scanner input = new Scanner(file);
System.out.println("Item \t Code \t Price");
String[] Item = new String[7];
int[] Code = new int[7];
double[] Price = new double[7];
int c = 0;
while (input.hasNext()) {
Item[c] = input.next();
Code[c] = input.nextInt();
Price[c] = input.nextDouble();
System.out.println(Item[c] + "\t" + Code[c] + "\t" + Price[c]);
c++;
}
input.close();
// Call Bubble Method
bubbleSort(Code, Item, Price);
System.out.println(" ");
System.out.println("Code \t Item \t Price");
for (int i = 0; i < Item.length; i++) {
System.out.println(Code[i]);
}
}
// Bubble Sort Method
static void bubbleSort(int Code[], String[] Item, double Price[]) {
int n = Code.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (Code[j] > Code[j + 1]) {
// swap temp and score[i]
int temp = Code[j];
Code[j] = Code[j + 1];
Code[j + 1] = temp;
}
}
}
Item Code Price
beer 1357 12.99
apple 2357 0.5
bread 2123 1.25
wine 1298 8.99
pants 3009 6.99
sugar 2111 2.69
socks 3123 11.89
Code Item Price
1298
1357
2111
2123
2357
3009
3123
Upvotes: 0
Views: 36
Reputation: 140329
With your current code, you would have to swap the items in all arrays. So, when you swap Code[i]
and Code[j]
, also swap Item[i]
and Item[j]
and Price[i]
and Price[j]
.
A more object-oriented way would be to define a class with Code
, Item
and Price
fields, say, Thing
:
class Thing {
int code;
String item;
double price;
}
and then sort an array of those: Thing[]
.
Upvotes: 2