Why am I getting this IndexOutOfBoundsException error? - java

hi so im currently trying to get past this error in my code, if anyone could explain where I went wrong, would be greatly appreciated.
public class Lab07vst100SD
{
public static void main (String[] args)
{
System.out.println();
int size = 10;
School bhs = new School(size);
System.out.println(bhs);
System.out.println(bhs.linearSearch("Meg"));
System.out.println(bhs.linearSearch("Sid"));
System.out.println();
bhs.selectionSort();
System.out.println(bhs);
System.out.println(bhs.binarySearch("Meg"));
System.out.println(bhs.binarySearch("Sid"));
System.out.println();
}
}
class School
{
private ArrayList<Student> students;
private int size;
public School (int s)
{
students = new ArrayList<Student>();
size = s;
}
public void addData()
{
String [] name = {"Tom","Ann","Bob","Jan","Joe","Sue","Jay","Meg","Art","Deb"};
int[] age = {21,34,18,45,27,19,30,38,40,35};
double[] gpa = {1.685,3.875,2.5,4.0,2.975,3.225,3.65,2.0,3.999,2.125};
for(int i = 0; i < name.length; i++)
{
students.add(new Student(name[i], age[i], gpa[i]));
}
size = students.size();
}
public void selectionSort ()
{
for(int h = 0; h < students.size(); h++)
{
int index = h;
Student least = students.get(h);
for (int t = 0; t < size; t++) {
if (students.get(t).equals(least)) {
least = students.get(t);
index = t;
}
Student temp = students.get(h);
students.set(h, least);
students.set(t, temp);
}
}
}
public int linearSearch (String str)
{
// new arraylist
ArrayList<String> names = new ArrayList<String>();
for (int q = 0; q < size; q++) {
names.add(students.get(q).getName());
}
//comparison
for (int y = 0; y < size; y++) {
if (names.get(y).equals(str))
return y;
}
return -1;
};
public int binarySearch (String str) {
// new arraylist and variables
ArrayList<String> names = new ArrayList<String>();
Boolean found = false;
int lo = 0;
int hi = size;
int mid = (lo + hi) / 2;
//for loop for to transverse the array.
for (int m = 0; m < size; m++) {
names.add(students.get(m).getName());
}
while (lo <= hi && !found) {
if (names.get(mid).compareTo(str) == 0)
{
found = true;
return mid;
}
if (names.get(mid).compareTo(str) < 0) {
lo = mid + 1;
mid = (lo + hi) / 2;
}
else {
hi = mid -1;
mid = (lo + hi) / 2;
}
}
if (found)
return mid;
else
return -1;
}
public String toString() {
String temp = "";
for (int s = 0; s < students.size(); s++) {
temp += students.get(s);
}
return temp;
}
}
also, I should mention this uses the student class.
here
public class Student
{
private String name;
private int age;
private double gpa;
public Student (String n, int a, double g)
{
name = n;
age = a;
gpa = g;
}
public String getName() {
return name; }
public int getAge() {
return age; }
public double getGPA() {
return gpa; }
public String toString()
{
String temp = name + " " + age + " " + gpa + "\n";
return temp;
}
}
the school class calls to the student class.
this is what comes back.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at School.linearSearch(Lab07vst100SD.java:78)
at Lab07vst100SD.main(Lab07vst100SD.java:16)
I'm completely confused on why this is happening, I think it may have to do with the ArrayList, other than that, I'm not sure.
please help, and thank you
p.s. I'm new so please bear with my horrible format.

You need call addData:
public static void main (String[] args)
{
System.out.println();
int size = 10;
School bhs = new School(size);
bhs.addData(); // here
System.out.println(bhs);
System.out.println(bhs.linearSearch("Meg"));
System.out.println(bhs.linearSearch("Sid"));
System.out.println();
bhs.selectionSort();
System.out.println(bhs);
System.out.println(bhs.binarySearch("Meg"));
System.out.println(bhs.binarySearch("Sid"));
System.out.println();
}

...
class School
{
private ArrayList<Student> students;
private int size;
public School (int s)
{
students = new ArrayList<Student>(); // Here, it can throw IndexOutOfBoundsException
size = s;
}
...
Please see https://www.tutorialspoint.com/java/util/arraylist_add_index.htm
The capacity of ArrayList must be initialized before ArrayList.add method
.

Related

Issues with setting values in arrays

I'm new to java and making a hotel system. I have three major classes Room, Floor, and Hotel. Each floor has same type of rooms except for their room number. So I only make say 10 rooms and then give them all to my 5 floors and then assign the room number to each room in the respective floor.
The room number has its first digit as that of the floor no and the remaining digit(s) are from 1-10.
However, all my rooms in the hotel get assigned with the 5th floor number.
Heres snippets of my code.
class Floor
{
private int floorNo;
private Room[] Rooms;
public Floor()
{
floorNo = 0;
Rooms = null;
}
public Floor(int f, int t)
{
floorNo = f;
Rooms = new Room[t];
}
public void createRooms(Room[] R)
{
for (int i = 0; i < 10; i++)
{
Rooms[i] = new Room();
Rooms[i] = R[i];
}
}
public void setRoom(int i, int f, int r)
{
Rooms[i].setFloorNo(f);
Rooms[i].setRoomno(r);
}
}
public class Main
{
public static void main(String[] args)
{
Room[] Rooms = new Room[10];
for (int n = 0; n < 10; n++)
{
Rooms[n] = new Room();
}
}
Floor[] Floors = new Floor[5];
for (int n = 0; n < 5; n++)
{
Floors[n] = new Floor(n + 1, 10);
Floors[n].createRooms(Rooms);
for (int i = 0; i < 10; i++)
{
Floors[n].setRoom(i, n + 1, i + 1);
}
for (int n = 0; n < 5; n++)
{
Floors[n].print();
}
}
}
class Floor
{
private int floorNo;
private Room[] Rooms;
public Floor()
{
floorNo=0;
Rooms=null;
}
public Floor(int f, int t)
{
floorNo=f;
Rooms = new Room[t];
}
public void createRooms(Room[] R)
{
for(int i = 0 ; i < 10; i ++)
{
Rooms[i] = new Room();
Rooms[i] = R[i];
}
}
public void setRoom(int i, int f, int r)
{
Rooms[i].setFloorNo(f);
Rooms[i].setRoomno(r,f);
}
}
class Room
{
public void setFloorNo(int i)
{
System.out.println("floor no is "+i);
}
public void setRoomno(int j,int k)
{
System.out.println("room no is "+k+""+j);
}
}
public class main
{
public static void main(String[] args)
{
Room [] Rooms= new Room[10];
for(int n = 0; n < 10; n++)
{
Rooms[n] = new Room ();
}
Floor [] Floors= new Floor[5];
for(int n=0; n<5; n++)
{
Floors[n] = new Floor (n+1,10);
Floors[n].createRooms(Rooms);
}
for(int n=0; n < 5; n++)
{
for(int i=0;i<10;i++)
Floors[n].setRoom(i, n+1, i+1);
enter code here
}
}
}
You can try smth like this:
public class Hotel {
private List<Floor> floors = new ArrayList<>();
public boolean addFloor(Floor floor) {
return floors.add(floor);
}
public static void main(String[] args) {
int totalFloors = 5;
int totalRoomsOnAFloor = 10;
final Hotel hotel = new Hotel();
int roomNumber = 0;
for (int floorNumber = 0; floorNumber < totalFloors; floorNumber++) {
Floor floor = new Floor(floorNumber);
for (int floorRoomNumber = 0; floorRoomNumber < totalRoomsOnAFloor; floorRoomNumber++) {
Room room = new Room(floor, roomNumber++);
floor.addRoom(room);
System.out.println("Added " + room.toString());
}
}
}
public static class Floor {
private List<Room> rooms = new ArrayList<>();
private int number;
public Floor(int number) {
this.number = number;
}
public boolean addRoom(Room room) {
return rooms.add(room);
}
public int getNumber() {
return number;
}
#Override
public String toString() {
return "Floor{" +
"number=" + number +
'}';
}
}
public class Room {
private final Floor floor;
private final int number;
public Room(Floor floor, int number) {
this.floor = floor;
this.number = number;
}
public int getNumber() {
return number;
}
public Floor getFloor() {
return floor;
}
#Override
public String toString() {
return "Room{" +
"number=" + number +
", on the floor=" + floor +
'}';
}
}
}
Output:
Added Room{number=0, on the floor=Floor{number=0}}
Added Room{number=1, on the floor=Floor{number=0}}
Added Room{number=2, on the floor=Floor{number=0}}
...
Added Room{number=47, on the floor=Floor{number=4}}
Added Room{number=48, on the floor=Floor{number=4}}
Added Room{number=49, on the floor=Floor{number=4}}

ACM-ICPC 7384 programming challenge

I'm trying to solve the Popular Vote problem, but I get runtime error and have no idea why, I really appreciate the help. Basically my solution is to get the total of votes, if all candidates have the same amount of votes; then there's no winner, otherwise I calculate the percentage of votes the winner gets in order to know if he's majority or minority winner.
import java.util.Scanner;
class popular {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos=s.nextInt();
int cont=0;
int ganador=0;
float num=0;
while(cont!=casos){
n=s.nextInt();
int votos[]= new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
suma=sumar(votos);
if(suma==-1){
System.out.println("no winner");
}
else{
ganador=ganador(votos, suma);
num=(float)votos[ganador]/(float)suma;
if( num> 0.5){
System.out.println("majority winner "+(ganador+1));
}
else{
System.out.println("minority winner "+(ganador+1));
}
}
cont++;
ganador=0;
}
}
public static int sumar(int arreglo[]){
int resp1=-1, resp=0;
int temp=arreglo[0];
boolean sol=true;
for (int i = 0; i < arreglo.length; i++) {
resp=resp+arreglo[i];
if(temp!=arreglo[i]){
sol=false;
}
}
if(sol==false){
return resp;
}
return resp1;
}
public static int ganador(int arreglo[], int suma){
int mayor=0;
int ganador=0;
for (int i = 0; i < arreglo.length; i++) {
if(arreglo[i]>mayor){
mayor=arreglo[i];
ganador=i;
}
}
return ganador;
}
}
I submitted your code to the OJ, but I didn't get a runtime error, but I got Compilation error. I have to figure out there are some problems in your code. First of all, if you want to submit a java code to OJ, you need to name the public class as Main instead of popular or something else. Second, your code logic is not correct. Suppose a test case:
4
1
1
2
2
Your program will print "minority winner 3" but it's should be "no winner".
Here is a modified source code from yours (you can get accepted with this code):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n, suma, mayoria;
int casos = s.nextInt();
int cont = 0;
int ganador = 0;
float num = 0;
while (cont != casos) {
n = s.nextInt();
int votos[] = new int[n];
for (int i = 0; i < n; i++) {
votos[i] = s.nextInt();
}
ganador = findMaximum(votos);
if (getMaximumCount(votos, votos[ganador]) > 1) {
System.out.println("no winner");
} else {
suma = sumOf(votos);
if (votos[ganador] * 2 > suma) {
System.out.println("majority winner " + (ganador + 1));
} else {
System.out.println("minority winner " + (ganador + 1));
}
}
cont++;
ganador = 0;
}
}
private static int sumOf(int[] arreglo) {
int sum = 0;
for (int x : arreglo) {
sum += x;
}
return sum;
}
private static int getMaximumCount(int[] arreglo, int maximum) {
// Check if there are more than one items have the maximum value
int count = 0;
for (int x : arreglo) {
if (x == maximum) {
count++;
}
}
return count;
}
private static int findMaximum(int[] arreglo) {
int x = 0, pos = 0;
for (int i = 0; i < arreglo.length; i++) {
if (x < arreglo[i]) {
x = arreglo[i];
pos = i;
}
}
return pos;
}
}
Hope it could help you!

Implementing merge sort in java 7

I have a problem with implementation of merge sort in java. I am looking for the error almost week unfortunately without result. ArrayList at the entrance is the same as the output.
import java.util.ArrayList;
import java.util.Scanner;
public class MergeSort
{
private ArrayList<Integer> basicArrayList = new ArrayList<Integer>();
ArrayList<Integer> arrayListA = new ArrayList<Integer>();
ArrayList<Integer> arrayListB = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
private int firstIndexOfArrayList = 0;
private int lastIndexOfArrayListA;
private int lastIndexOfArrayListB;
public void Scal(ArrayList<Integer> basicArrayList, int p, int q, int r) {
this.firstIndexOfArrayList = p;
this.lastIndexOfArrayListA = q;
this.lastIndexOfArrayListB = r;
int numberOfElementsArrayListA = lastIndexOfArrayListA
- firstIndexOfArrayList + 1;
int numberOfElementsArrayListB = lastIndexOfArrayListB
- lastIndexOfArrayListA;
for (int i = 0; i < numberOfElementsArrayListA; i++) {
arrayListA.set(i, basicArrayList.get(firstIndexOfArrayList + i));
}
for (int j = 0; j < numberOfElementsArrayListB; j++) {
arrayListB.set(j, basicArrayList.get(lastIndexOfArrayListA + j));
}
arrayListA.add(Integer.MAX_VALUE);
arrayListB.add(Integer.MAX_VALUE);
int i = 0;
int j = 0;
for (int k = firstIndexOfArrayList; k <= lastIndexOfArrayListB; k++) {
if (arrayListA.get(i) <= arrayListB.get(j)) {
basicArrayList.set(k, arrayListA.get(i));
i = i + 1;
} else {
basicArrayList.set(k, arrayListB.get(j));
j = j + 1;
}
}
}
public void MergeSort(ArrayList basicArrayList, int p, int r) {
this.firstIndexOfArrayList = p;
this.lastIndexOfArrayListB = r;
if (firstIndexOfArrayList < lastIndexOfArrayListB) {
int lastIndexOfArrayListA = (firstIndexOfArrayList + lastIndexOfArrayListB) / 2;
MergeSort(basicArrayList, firstIndexOfArrayList,
lastIndexOfArrayListA);
MergeSort(basicArrayList, lastIndexOfArrayListA + 1,
lastIndexOfArrayListB);
Scal(basicArrayList, firstIndexOfArrayList,
lastIndexOfArrayListA,
lastIndexOfArrayListB);
}
}
public void setSize() {
System.out.println("Enter the number of elements to sort: ");
this.lastIndexOfArrayListB = input.nextInt();
}
public int getSize() {
return lastIndexOfArrayListB;
}
public void setData() {
System.out.println("Enter the numbers: ");
for (int i = 0; i < lastIndexOfArrayListB; i++) {
int number;
number = input.nextInt();
basicArrayList.add(number);
}
}
public void getTable() {
System.out.println(basicArrayList.toString());
}
public static void main(String[] args) {
MergeSort output = new MergeSort();
output.setSize();
output.setData();
output.MergeSort(output.basicArrayList,
output.firstIndexOfArrayList, (output.getSize() - 1));
output.getTable();
}
}
In terms of fixing your code I had a crack at it and as far as I can tell this seems to work. To do this a lot of your code had to be changed but it does now sort all Integers properly
import java.util.ArrayList;
import java.util.Scanner;
public class MergeSort
{
private ArrayList<Integer> basicArrayList = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
private int numbersToSort;
public void doMergeSort(int firstIndexOfArrayList,int lastIndexOfArrayListB, ArrayList<Integer> arrayList)
{
if(firstIndexOfArrayList<lastIndexOfArrayListB && (lastIndexOfArrayListB-firstIndexOfArrayList)>=1)
{
int mid = (lastIndexOfArrayListB + firstIndexOfArrayList)/2;
doMergeSort(firstIndexOfArrayList, mid, arrayList);
doMergeSort(mid+1, lastIndexOfArrayListB, arrayList);
Scal(firstIndexOfArrayList,mid,lastIndexOfArrayListB, arrayList);
}
}
public void Scal(int firstIndexOfArrayList,int lastIndexOfArrayListA,int lastIndexOfArrayListB, ArrayList<Integer> arrayList)
{
ArrayList<Integer> mergedSortedArray = new ArrayList<Integer>();
int leftIndex = firstIndexOfArrayList;
int rightIndex = lastIndexOfArrayListA+1;
while(leftIndex<=lastIndexOfArrayListA && rightIndex<=lastIndexOfArrayListB)
{
if(arrayList.get(leftIndex)<=arrayList.get(rightIndex))
{
mergedSortedArray.add(arrayList.get(leftIndex));
leftIndex++;
}
else
{
mergedSortedArray.add(arrayList.get(rightIndex));
rightIndex++;
}
}
while(leftIndex<=lastIndexOfArrayListA)
{
mergedSortedArray.add(arrayList.get(leftIndex));
leftIndex++;
}
while(rightIndex<=lastIndexOfArrayListB)
{
mergedSortedArray.add(arrayList.get(rightIndex));
rightIndex++;
}
int i = 0;
int j = firstIndexOfArrayList;
while(i<mergedSortedArray.size())
{
arrayList.set(j, mergedSortedArray.get(i++));
j++;
}
}
public void setSize()
{
System.out.println("Enter the number of elements to sort: ");
this.numbersToSort = input.nextInt();
}
public int getSize()
{
return numbersToSort;
}
public void setData()
{
System.out.println("Enter the numbers: ");
for (int i = 0; i < numbersToSort; i++)
{
int number;
number = input.nextInt();
basicArrayList.add(number);
}
}
public void getTable()
{
System.out.println(basicArrayList.toString());
}
public void runSort(ArrayList<Integer> arrayList)
{
doMergeSort(0, this.numbersToSort-1, arrayList);
}
public static void main(String[] args)
{
MergeSort output = new MergeSort();
output.setSize();
output.setData();
output.runSort(output.basicArrayList);
output.getTable();
}
}
Try this code. The following code takes an ArrayList input and outputs an ArrayList as well so it still works along the same basis of your code. The actual sort is handled in a different class MergeSort and is passes into ForMergeSort. Hope this helps
MergeSort.java
public class MergeSort
{
private int[] array;
private int[] tempMergArr;
private int length;
public void sort(int[] inputArr)
{
}
public int[] getSortedArray(int[] inputArr)
{
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
for(int i=0;i<length;i++)
{
int correctNumber = i+1;
System.out.println("Value "+correctNumber+" of the sorted array which was sorted via the Merge Sort is: "+inputArr[i]);
}
return inputArr;
}
private void doMergeSort(int lowerIndex, int higherIndex)
{
if (lowerIndex < higherIndex)
{
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
doMergeSort(lowerIndex, middle);
doMergeSort(middle + 1, higherIndex);
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex)
{
for (int i = lowerIndex; i <= higherIndex; i++)
{
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex)
{
if (tempMergArr[i] <= tempMergArr[j])
{
array[k] = tempMergArr[i];
i++;
}
else
{
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle)
{
array[k] = tempMergArr[i];
k++;
i++;
}
}
}
ForMergeSort.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ForMergeSort
{
ArrayList<Integer> arrayList = new ArrayList<Integer>();
ArrayList<Integer> sortedArrayList = new ArrayList<Integer>();
MergeSort mS = new MergeSort();
public void buildArrayList()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of elements to sort: ");
int toSort = input.nextInt();
System.out.println("Enter the numbers: ");
for(int i =0; i<toSort; i++)
{
int number = input.nextInt();
arrayList.add(number);
}
}
public void runMergeSort(ArrayList<Integer> arrayList)
{
int[] arrayOfValues = new int[arrayList.size()];
int i = 0;
for(int a:arrayList)
{
arrayOfValues[i] = a;
i++;
}
MergeSort mS = new MergeSort();
for(int intOfArray:mS.getSortedArray(arrayOfValues))
{
sortedArrayList.add(intOfArray);
}
System.out.println(sortedArrayList.toString());
}
public static void main(String[] args)
{
ForMergeSort fMS = new ForMergeSort();
fMS.buildArrayList();
fMS.runMergeSort(fMS.arrayList);
}
}

how to call a bubble sort in java

i need to do a bubble sort with 2 different set of datas. currently i have entered the bubble sort method twice so it can run with both set of data. is there a way to use a call method to the bubble sort.
int intJ1R1 = Integer.parseInt(txtJ1R1.getText());
int intJ2R1 = Integer.parseInt(txtJ2R1.getText());
int intJ3R1 = Integer.parseInt(txtJ3R1.getText());
int intJ4R1 = Integer.parseInt(txtJ4R1.getText());
int intJ5R1 = Integer.parseInt(txtJ5R1.getText());
int intJ6R1 = Integer.parseInt(txtJ6R1.getText());
double[] r1Array = {intJ1R1, intJ2R1, intJ3R1, intJ4R1, intJ5R1, intJ6R1};
double temp;
for (int i=0; i<r1Array.length; i++)
{
for (int j = 1; j <(r1Array.length-i); j++)
{
if (r1Array[j-1]>=r1Array[j])
{
temp=r1Array[j-1];
r1Array[j-1] = r1Array[j];
r1Array[j] = temp;
}
}
}
double totalR1 = (r1Array[1] + r1Array[2] + r1Array[3] + r1Array[4])/4;
String stringTotalR1 = Double.toString(totalR1);
lblTotalRun1.setText(stringTotalR1);
int intJ1R2 = Integer.parseInt(txtJ1R2.getText());
int intJ2R2 = Integer.parseInt(txtJ2R2.getText());
int intJ3R2 = Integer.parseInt(txtJ3R2.getText());
int intJ4R2 = Integer.parseInt(txtJ4R2.getText());
int intJ5R2 = Integer.parseInt(txtJ5R2.getText());
int intJ6R2 = Integer.parseInt(txtJ6R2.getText());
double[] r2Array = {intJ1R2, intJ2R2, intJ3R2, intJ4R2, intJ5R2, intJ6R2};
for (int i=0; i<r2Array.length; i++)
{
for (int j = 1; j <(r2Array.length-i); j++)
{
if (r2Array[j-1]>=r2Array[j])
{
temp=r2Array[j-1];
r2Array[j-1] = r2Array[j];
r2Array[j] = temp;
}
}
}
double totalR2 = (r2Array[1] + r2Array[2] + r2Array[3] + r2Array[4])/4;
String stringTotalR2 = Double.toString(totalR2);
lblTotalRun2.setText(stringTotalR2);
Create a method with the following signature:
public double[] bubbleSort(double[] array){
//move your sorting code here, and change array's name to array
return sortedArray;
}
Create a class and a method and then invoke the method from the main method
public class BubbleSort
{
public void bubbleSort(int value1, int value2, int value3, int value4, int value5, int value6) {
double[] r1Array = {value1, value2, value3, value4, value5, value6};
double temp;
for (int i=0; i<r1Array.length; i++)
{
for (int j = 1; j <(r1Array.length-i); j++)
{
if (r1Array[j-1]>=r1Array[j])
{
temp=r1Array[j-1];
r1Array[j-1] = r1Array[j];
r1Array[j] = temp;
}
}
}
double totalR1 = (r1Array[1] + r1Array[2] + r1Array[3] + r1Array[4])/4;
String stringTotalR1 = Double.toString(totalR1);
lblTotalRun1.setText(stringTotalR1);
}
public static void main(String[] args)
{
BubbleSort bubbleSort = new BubbleSort();
int intJ1R1 = Integer.parseInt(txtJ1R1.getText());
int intJ2R1 = Integer.parseInt(txtJ2R1.getText());
int intJ3R1 = Integer.parseInt(txtJ3R1.getText());
int intJ4R1 = Integer.parseInt(txtJ4R1.getText());
int intJ5R1 = Integer.parseInt(txtJ5R1.getText());
int intJ6R1 = Integer.parseInt(txtJ6R1.getText());
bubbleSort.bubbleSort(intJ1R1,intJ1R1,intJ1R1,intJ1R1,intJ1R1,intJ1R1);
int intJ1R2 = Integer.parseInt(txtJ1R2.getText());
int intJ2R2 = Integer.parseInt(txtJ2R2.getText());
int intJ3R2 = Integer.parseInt(txtJ3R2.getText());
int intJ4R2 = Integer.parseInt(txtJ4R2.getText());
int intJ5R2 = Integer.parseInt(txtJ5R2.getText());
int intJ6R2 = Integer.parseInt(txtJ6R2.getText());
bubbleSort.bubbleSort(intJ1R2,intJ1R2,intJ1R3,intJ1R4,intJ1R5,intJ1R6);
}
}
You can define the integer parameters inside the bubbleSort method itself once however since I don't know from What datatype you are converting to Integer hence have written it twice in main method itself
public static void main(String[] args)
{
BubbleSort bs = new BubbleSort(); //name of your class instead of BubbleSort
double[] r1Array = {intJ1R1, intJ2R1, intJ3R1, intJ4R1, intJ5R1, intJ6R1};
double[] r2Array = {intJ1R2, intJ2R2, intJ3R2, intJ4R2, intJ5R2, intJ6R2};
double[] sortedR1 = bs.bubbleSort(r1Array);
double[] sortedR2 = bs.bubbleSort(r2Array);
}
public double[] bubbleSort(double[] array){
double temp;
for (int i=0; i<array.length; i++)
{
for (int j = 1; j <(array.length-i); j++)
{
if (array[j-1]>=array[j])
{
temp=array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
return array;
}

Sorting arrays from a file and printing results

I have to read a file of data and store it into an array of integers, sort through the array and then report the highest total and the lowest total but for some reason when i run my code nothing appears, and it says that it is error free. this is the code that i have so far...
import java.io.*;
import java.util.Scanner;
public class CarbonAnalysis {
public static void main (String [] Args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
File f = new File("carbon_data.txt");
Scanner welcome = new Scanner(f);
File outputFile = new File("carbon_report.txt");
PrintStream output = new PrintStream(outputFile);
String firstLine = welcome.nextLine();
int secondLine = welcome.nextInt();
CarbonDioxideData[] Country = new CarbonDioxideData[secondLine];
for(int i = 0; i < secondLine; i++) {
Country[i] = new CarbonDioxideData();
Country[i].setCountry(welcome.next());
Country[i].setTotalCO2(welcome.nextDouble());
Country[i].setRoadCO2(welcome.nextDouble());
Country[i].setCO2PerPerson(welcome.nextDouble());
Country[i].setCarsPerPerson(welcome.nextInt());
}
int count = 0;
int count2 = 0;
CarbonDioxideData[] totalEmissions = new CarbonDioxideData[count];
CarbonDioxideData[] perPersonRoadEmissions = new CarbonDioxideData[count2];
reportDescription(output);
sortTotalEmissions(totalEmissions);
sortPerPersonRoadEmissions(perPersonRoadEmissions);
}
//prints the output of data analyzed
public static void reportDescription(PrintStream output) {
output.println("Country with the lowest total emissions: ");
output.println("Country with the highest total emissions: " );
output.println("Canada is ranked for lowest total emissions.");
output.println();
output.println("Country with the lower per-person road emissions: ");
output.println("Country with the highest per-person road emissions: ");
output.println("Canada is ranked for the lowest per-road emissions.");
}
//sorts the total Emissions from highest to lowest
public static void sortTotalEmissions(CarbonDioxideData[] totalEmissions){
for(int i = 0; i < totalEmissions.length; i++) {
double max = totalEmissions[i].getTotalCO2();
int maxPos = i;
for(int j = i; j < totalEmissions.length; j++) {
if(max < totalEmissions[j].getTotalCO2() ) {
max = totalEmissions[j].getTotalCO2();
maxPos = j;
}
}
CarbonDioxideData temp = totalEmissions[maxPos];
totalEmissions[maxPos] = totalEmissions[i];
totalEmissions[i] = temp;
}
}
//sorts the per person road Emissions from highest to lowest
public static void sortPerPersonRoadEmissions(CarbonDioxideData[] perPersonRoadEmissions){
for(int i = 0; i < perPersonRoadEmissions.length; i++) {
int max = perPersonRoadEmissions[i].getCarsPerPerson();
int maxPos = i;
for(int j = i; j < perPersonRoadEmissions.length; j++) {
if(max < perPersonRoadEmissions[j].getCarsPerPerson() ) {
max = perPersonRoadEmissions[j].getCarsPerPerson();
maxPos = j;
}
}
CarbonDioxideData temp = perPersonRoadEmissions[maxPos];
perPersonRoadEmissions[maxPos] = perPersonRoadEmissions[i];
perPersonRoadEmissions[i] = temp;
}
}
}
The code that was given to me to help:
public class CarbonDioxideData {
private String country;
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
public CarbonDioxideData() {
country = "blank_country";
totalCO2 = -1.0;
roadCO2 = -1.0;
CO2PerPerson = -1.0;
carsPerPerson = -1;
}
public String toString() {
String result = country;
result += " " + totalCO2;
result += " " + roadCO2;
result += " " + CO2PerPerson;
result += " " + carsPerPerson;
return result;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public double getTotalCO2() {
return totalCO2;
}
public void setTotalCO2(double totalCO2) {
this.totalCO2 = totalCO2;
}
public double getRoadCO2() {
return roadCO2;
}
public void setRoadCO2(double roadCO2) {
this.roadCO2 = roadCO2;
}
public double getCO2PerPerson() {
return CO2PerPerson;
}
public void setCO2PerPerson(double cO2PerPerson) {
CO2PerPerson = cO2PerPerson;
}
public int getCarsPerPerson() {
return carsPerPerson;
}
public void setCarsPerPerson(int carsPerPerson) {
this.carsPerPerson = carsPerPerson;
}
}
Your program always ouputs a constant String in the file since there is no variable in reportDescription.
Secondly to properly sort you array, CarbonDioxideData should implement Comparable. Then you can call
Arrays.sort like this :
Arrays.sort(perPersonRoadEmissions)
and then retrieve the highest/value :
perPersonRoadEmissions[0] / perPersonRoadEmissions[perPersonRoadEmissions.length-1]
To display the information you have to call output after sorting and change the signature to accept variable for highest and lowest value.
Arrays.sort(totalEmissions);
Arrays.sort(perPersonRoadEmissions)
reportDescription(output,totalEmissions[0],totalEmissions[totalEmissions.length-1],perPersonRoadEmissions[0],perPersonRoadEmissions[perPersonRoadEmissions.length-1]);
As an alternative you can also simply pass the arrays as parameters and retrieve min max in the body of reportDescription :
reportDescription(output,totalEmissions,perPersonRoadEmissions);
How to change the content of reportDescription and implementing compareTo is left to the OP.

Categories

Resources