class Account {
int accountNumber;
int balance;
Account(int accountNumber, int balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
Account() {
int accountNumber = 0;
int balance = 0;
}
}
public class HW2 {
public static void main(String[] args) {
Account[] oneH = new Account[100];
accountNumberGenerator(oneH);
balanceGenerator(oneH);
for(int i = 0; i < oneH.length; i++){
System.out.println(oneH[i].accountNumber + " " + oneH[i].balance);
}
}
public static void accountNumberGenerator(Account[] arr){
Account one = new Account();
for(int i = 0; i < arr.length; i++){
arr[i] = one;
arr[i].accountNumber = i+1;
}
}
public static void balanceGenerator(Account[] arr){
int min = 100;
int max = 100000;
for(int i = 0; i < arr.length; i++){
Random rand = new Random();
int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);
arr[i].balance = random_int;
}
}
}
I'm making an object array but it's not working.
Whenever I print each values of the Account array it just shows the 100 and random number that generated last for all values.
I'm not sure what is the problem.
public static void accountNumberGenerator(Account[] arr){
Account one = new Account();
for(int i = 0; i < arr.length; i++){
arr[i] = one;
arr[i].accountNumber = i+1;
}
}
In this method you are only creating one single instance of Account and assigning it to every element of the array.
You need to create a brand new object each iteration of your loop.
public static void accountNumberGenerator(Account[] arr){
for(int i = 0; i < arr.length; i++){
Account one = new Account();
arr[i] = one;
arr[i].accountNumber = i+1;
}
}
Here's a simple way to create 100 accounts.
public class Main {
public static void main(String[] args) {
java.util.Random r = new java.util.Random();
Account[] oneH = new Account[100];
for(int i=0; i<oneH.length; i++)
oneH[i] = new Account(i, r.nextInt(99900)+100);
for(int i = 0; i < oneH.length; i++)
System.out.printf("%3d%7d\n", oneH[i].accountNumber, oneH[i].balance);
}
}
Related
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
.
Having trouble with this code below. It is implementation of population evolution. In my case the max fitness is struck at a local maxima everytime and is unable to reach max possible value. Kindly suggest necessary edits and reason for the same.
Individual.java
package genetic.algorithm.project;
import java.util.Random;
public class Individual {
public static int SIZE = 300;
private int[] genes = new int[SIZE];
private double fitnessValue = 0.0;
// Getters and Setters
public void setGene(int index,int gene){
this.genes[index] = gene;
}
public int getGene(int index){
return this.genes[index];
}
public void setFitnessValue(double fitness){
this.fitnessValue = fitness;
}
public double getFitnessValue(){
return this.fitnessValue;
}
//Function to generate a new individual with random set of genes
public void generateIndividual(){
Random rand = new Random();
for(int i=0;i<SIZE;i++){
this.setGene(i, rand.nextInt(2));
}
}
//Mutation Function
public void mutate(){
Random rand = new Random();
int index = rand.nextInt(SIZE);
this.setGene(index, 1-this.getGene(index)); // Flipping value of gene
}
//Function to set Fitness value of an individual
public int evaluate(){
int fitness = 0;
for(int i=0; i<SIZE; ++i) {
fitness += this.getGene(i);
}
this.setFitnessValue(fitness);
return fitness;
}
}
Population.java
import java.util.Random;
public class Population {
final static int ELITISM = 1;
final static int POP_SIZE = 200+ELITISM; //Population size + Elitism (1)
final static int MAX_ITER = 2000;
final static double MUTATION_RATE = 0.05;
final static double CROSSOVER_RATE = 0.7;
private static Random rand = new Random();
private double totalFitness;
private Individual[] pop;
//Constructor
public Population(){
pop = new Individual[POP_SIZE];
//Initialising population
for(int i=0;i<POP_SIZE;i++){
pop[i] = new Individual();
pop[i].generateIndividual();
}
this.evaluate();
}
//Storing new generation in population
public void setPopulation(Individual[] newPop) {
this.pop = newPop;
}
//Method to find total fitness of population
public double evaluate(){
this.totalFitness = 0.0;
for (int i = 0; i < POP_SIZE; i++) {
this.totalFitness += pop[i].evaluate();
}
return this.totalFitness;
}
//Getters
public Individual getIndividual(int index) {
return pop[index];
}
//Function to find fittest individual for elitism
public Individual getFittest() {
Individual fittest = pop[0];
for (int i = 0; i < POP_SIZE; i++) {
if (fittest.getFitnessValue() <= getIndividual(i).getFitnessValue()) {
fittest = getIndividual(i);
}
}
return fittest;
}
//CROSSOVER Function : Takes 2 individuals and returns 2 new individuals
public static Individual[] crossover(Individual indiv1,Individual indiv2) {
Individual[] newIndiv = new Individual[2];
newIndiv[0] = new Individual();
newIndiv[1] = new Individual();
int randPoint = rand.nextInt(Individual.SIZE);
int i;
for (i=0; i<randPoint; ++i) {
newIndiv[0].setGene(i, indiv1.getGene(i));
newIndiv[1].setGene(i, indiv2.getGene(i));
}
for (; i<Individual.SIZE; ++i) {
newIndiv[0].setGene(i, indiv2.getGene(i));
newIndiv[1].setGene(i, indiv1.getGene(i));
}
return newIndiv;
}
//Roulette Wheel Selection Function
public Individual rouletteWheelSelection() {
double randNum = rand.nextDouble() * this.totalFitness;
int idx;
for (idx=0; idx<POP_SIZE && randNum>0; idx++) {
randNum -= pop[idx].getFitnessValue();
}
return pop[idx-1];
}
//Main method
public static void main(String[] args) {
Population pop = new Population();
Individual[] newPop = new Individual[POP_SIZE];
Individual[] indiv = new Individual[2];
//Current Population Stats
System.out.println("Total Fitness = "+pop.totalFitness);
System.out.println("Best Fitness = "+pop.getFittest().getFitnessValue());
int count;
for(int iter=0;iter<MAX_ITER;iter++){
count =0;
//Elitism
newPop[count] = pop.getFittest();
count++;
//Creating new population
while(count < POP_SIZE){
//Selecting parents
indiv[0] = pop.rouletteWheelSelection();
indiv[1] = pop.rouletteWheelSelection();
// Crossover
if (rand.nextDouble() < CROSSOVER_RATE ) {
indiv = crossover(indiv[0], indiv[1]);
}
// Mutation
if ( rand.nextDouble() < MUTATION_RATE ) {
indiv[0].mutate();
}
if ( rand.nextDouble() < MUTATION_RATE ) {
indiv[1].mutate();
}
// add to new population
newPop[count] = indiv[0];
newPop[count+1] = indiv[1];
count += 2;
}
// Saving new population in pop
pop.setPopulation(newPop);
//Evaluating new population
pop.evaluate();
System.out.print("Total Fitness = " + pop.totalFitness);
System.out.println(" ; Best Fitness = " +pop.getFittest().getFitnessValue());
}
Individual bestIndiv = pop.getFittest();
}
}
The max possible value of fitness is 300 in my case but it always stucks around 200-230.
Replaced this function :
public void setPopulation(Individual[] newPop) {
this.pop = newPop;
}
with
public void setPopulation(Individual[] newPop) {
System.arraycopy(newPop, 0, this.pop, 0, POP_SIZE);
}
and it works fine now.
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);
}
}
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;
}
Can you give me a hint on what I'm doing wrong with my average in the average method? I'm trying to call the method in the read scores.I'm trying to get the average of the scores I have in my input.txt file.
import java.io.*;
import java.util.*;
public class FindGrade {
public static final int NUM_SCORE_TYPES = 5;
public static void main(String[] args) {
Scanner scan = null;
int[] quizArray = null;
int[] labArray = null;
int[] attendance = null;
int[] midterms = null;
int quizgrade =0;
int labgrade=0;
int attendance_1=0;
int midterms_1 =0;
String name;
try {
scan = new Scanner(new File("input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
// each iteration is for single exam type (ie: Quizzes is the 1st one)
for (int i = 0; i < NUM_SCORE_TYPES; i++) {
name = scan.next();
int numScores = scan.nextInt();
int maxGrade = scan.nextInt();
if (name.equals("Quizzes")) {
quizArray = new int[numScores];
readScores(quizArray, numScores, scan);
}
else if (name.equals("Labs")) {
labArray = new int[numScores];
readScores(labArray, numScores, scan);
}
else if (name.equals("Lab_attendance")) {
attendance = new int[numScores];
readScores(attendance, numScores, scan);
}
else if (name.equals("Midterms")) {
midterms = new int[numScores];
readScores(midterms, numScores, scan);
}
}
}
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
}
public static void average(double [] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}
In any case, you can't directly call it with the arrays that you are creating there. Because the arrays are of type int, but the average-method requires a double array. When you change this, you can call the method like this...
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
average(scoreArray, numScores); // <----- Call it here
}
public static void average(int[] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}