average method arrays hint - java

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);
}

Related

To find the single digit sum of palindrome numbers in array

I tried to check the palindrome number and find the single digit sum of the palindrome numbers, but my code is not returning the proper value (I am finding it difficult to return the value of sum from the loops). Can anyone help me getting the mistake. Any help will be appriciated.
import java.util.Scanner;
public class SumOfPalindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
System.out.println(SumOfPalindromeNumber(inp));
}
private static int SumOfPalindromeNumber(int[] inp )
{
int sumpal =0;
for(int i = 0; i<inp.length;i++)
{
int rem =0;
int sum = 0;
while(inp[i]!=0)
{
rem = inp[i]%10;
sum=(sum*10)+rem;
inp[i]/=10;
}
if(inp[i]==sum)
{
sumpal+=inp[i];
if(sumpal>9)
{
sumpal=singledigitsum(sumpal);
}
}
}
return sumpal;
}
private static int singledigitsum(int sumpal)
{
int rem1 = 0;
int sum1 = 0;
while(sumpal!=0)
{
rem1=sumpal%10;
sum1+=rem1;
sumpal/=10;
}
if(sum1>9)
{
sum1=singledigitsum(sum1);
}
return sum1;
}
}
Enter numbers
Check which numbers are palindromes.
If that number is a palindrome then find sum of its digits.
Code:
import java.util.Scanner;
public class SumOfPalindrome {
public static void main(String[] args) {
SumOfPalindrome sumOfPalindrome=new SumOfPalindrome();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
for(int i=0;i<n;i++)
{
if(sumOfPalindrome.isPallindrone(inp[i]))
{
System.out.println("No -> "+inp[i]+" Sum->"+sumOfPalindrome.sumOfDigits(inp[i]));
}
}
}//
public boolean isPallindrone(int no)
{
int r,sum=0,temp;
temp=no;
while(no>0){
r=no%10; //getting remainder
sum=(sum*10)+r;
no=no/10;
}
if(temp==sum)
{
return true;
}
else
{
return false;
}
}
public int sumOfDigits(int no)
{
int sum = 0;
while (no != 0)
{
sum = sum + no % 10;
no = no/10;
}
return sum;
}
}
I did not understand the purpose of sumpal in your code. You wanted a method which return sumOfPalindromes in an array. I commented the part which was wrong.
import java.util.Scanner;
public class SumOfPalindrome_1
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
//System.out.println(SumOfPalindromeNumber(inp));
SumOfPalindromeNumber(inp);
}
private static void SumOfPalindromeNumber(int[] inp )
{
int sumpal =0;
for(int i = 0; i<inp.length;i++)
{
int rem =0;
int sum = 0;
while(inp[i]!=0)
{
rem = inp[i]%10;
sum=(sum*10)+rem;
inp[i]/=10;
}
if(inp[i]==sum)
{
// sumpal+=inp[i];
/*if(sumpal>9)
{
sumpal=singledigitsum(sumpal);
}
*/
System.out.println(singleDigitSum(inp[i]));
}
}
}
private static int singleDigitSum(int sumpal)
{
int rem1 = 0;
int sum1 = 0;
while(sumpal!=0)
{
rem1=sumpal%10;
sum1+=rem1;
sumpal/=10;
}
if(sum1>9)
{
sum1=singleDigitSum(sum1);
}
return sum1;
}
}
Apologies if this is not the case but this seems like you are looking for answers to a coding test.

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);
}
}

Java: Finding average of doubles in array

I'm working on an assignment for my intro to java class. Part of the assignment is reading in doubles from a text file into an array and then using a different method to calculate the average. So far I've read the doubles into the array but I'm not sure how to reference that array in another method to calculate the average. I've been searching online, but with no results probably because my poor terminology leads me to irrelevant answers. I get an error from netbeans that the symbol classGrades can't be found(because its only in the main method.) I tried defininig it as a global variable, but that didn't work and we haven't learned about those yet so there must be another way to do it.
To summarize: I don't know how to reference variables between methods.
Here is my code
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class GradeChecker {
public static void main(String[] args) {
// TODO code application logic here
double[] classGrades = new double[76];
double classAverage = calculateAverageGrade();
fillArray(classGrades);
for (int i = 0; i < classGrades.length; i++) {
System.out.println(classGrades[i]);
}
//System.out.print(Arrays.toString(classGrades));
System.out.print(classGrades.length);
}
public static void fillArray(double[] ary) {
try {
File arrayInput = new File("ClassGrades.txt");
Scanner in = new Scanner(arrayInput);
in.useDelimiter("\r\n");
int i = 0;
while (in.hasNextLine()) {
ary[i++] = in.nextDouble();
}
in.close();
} catch (Exception exception) {
System.out.println("Error: " + exception.getMessage());
}
}
private static double calculateAverageGrade(double[] classGrades) {
double gradeSum = 0;
double gradeAverage = 0;
for (int i = 0.0; i < classGrades.length; i++) {
gradeSum = gradeSum + classGrades[i];
}
gradeAverage = gradeSum/classGrades.length;
return gradeAverage;
}
}
You can pass array classGrades to the function:
double[] classGrades = new double[76];
double classAverage = calculateAverageGrade(classGrades);
Here:
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class GradeChecker {
public static void main(String[] args) {
// TODO code application logic here
double[] classGrades = new double[76];
double classAverage = calculateAverageGrade(classGrades);
fillArray(classGrades);
for (int i = 0; i < classGrades.length; i++) {
System.out.println(classGrades[i]);
}
//System.out.print(Arrays.toString(classGrades));
System.out.print(classGrades.length);
}
public static void fillArray(double[] ary) {
try {
File arrayInput = new File("ClassGrades.txt");
Scanner in = new Scanner(arrayInput);
in.useDelimiter("\r\n");
int i = 0;
while (in.hasNextLine()) {
ary[i++] = in.nextDouble();
}
in.close();
} catch (Exception exception) {
System.out.println("Error: " + exception.getMessage());
}
}
private static double calculateAverageGrade(double[] classGrades) {
double gradeSum = 0;
double gradeAverage = 0;
for (int i = 0; i < classGrades.length; i++) {
gradeSum = gradeSum + classGrades[i];
}
gradeAverage = gradeSum / classGrades.length;
return gradeAverage;
}
}
I have been edited your code.
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
public class GradeChecker {
public static void main(String[] args) {
// TODO code application logic here
double[] classGrades = new double[76];
fillArray(classGrades);
double classAverage = calculateAverageGrade(classGrades);
for (int i = 0; i < classGrades.length; i++) {
System.out.println(classGrades[i]);
}
//System.out.print(Arrays.toString(classGrades));
System.out.print(classGrades.length);
}
public static void fillArray(double[] ary) {
try {
File arrayInput = new File("ClassGrades.txt");
Scanner in = new Scanner(arrayInput);
in.useDelimiter("\r\n");
int i = 0;
while (in.hasNextLine()) {
ary[i++] = in.nextDouble();
}
in.close();
} catch (Exception exception) {
System.out.println("Error: " + exception.getMessage());
}
}
private static double calculateAverageGrade(double[] classGrades) {
double gradeSum = 0;
double gradeAverage = 0;
for (int i = 0; i < classGrades.length; i++) {
gradeSum = gradeSum + classGrades[i];
}
gradeAverage = gradeSum/classGrades.length;
return gradeAverage;
}
}
Please try this and let me know
EDIT 1
Lot of compilation issue.
fillArray called after finding calculateAverageGrade

Baseball Menu Insertion sort part

I'm trying to use insertion sort to sort for the batting average of the players. I get an error message "The method get(int) in the type java.util.ArrayList is not applicable for the arguments (double)" on the lines of S.get(outer) and S.get(inner - 1)
What am I doing wrong?
How can I fix this?
import java.util.*;
import java.io.*;
class menu {
public static void main (String [] arg) throws IOException
{
PlayerRip.PlayerInfo obj5 = new PlayerRip.PlayerInfo();
ArrayList<Player> obj6 = new ArrayList<Player>();
MainMenu(obj5, obj6);
}
public static void MainMenu(PlayerRip P, ArrayList<Player> S) throws IOException
{
Scanner keyboard = new Scanner(System.in);
int response = 0;
int response2 = 0;
ArrayList<Player> obj1 = new ArrayList<Player>();
obj1.add(new Player("Agostini", "Aldo", "Pitcher", 170, 20, 72, 12, 6, 1, 1, 0));
do
{
System.out.println("1. Open A file:");
System.out.println("7. Exit the program");
response = keyboard.nextInt();
switch (response)
{
case 1:
{
openFile(obj1);
do
{
System.out.println("2. Display all players");
System.out.println("3. Enter player's Height");
System.out.println("4. Sort all players alphabetically by Surname");
System.out.println("5. Sort all players by batting average");
System.out.println("6. Delete a player by selecting the player's surname from a list");
System.out.println("7. Add a player to the stats");
System.out.println("8. Save stats to a file");
System.out.println("9. Exit the program");
response2 = keyboard.nextInt();
switch (response2)
{
case 2:
{
displayInfo(obj1);
break;
}
case 3:
{
changeHeight(obj1);
break;
}
case 4:
{
BubbleSort(obj1);
break;
}
case 5:
{
break;
}
case 6:
{
deletePlayerInfo(obj1);
break;
}
case 7:
{
addPlayerInfo(obj1);
break;
}
case 8:
{
saveFile(obj1);
break;
}
case 9:
{
System.exit(0);
break;
}
}
} while (response2 != 9);
break;
}
case 7:
{
System.exit(0);
break;
}
}
} while (response != 1 || response != 7); // End of switch statement
}
public static void displayInfo(ArrayList<Player> S) {
System.out.printf("%10s %10s %10s \t %4s %4s \t %4s \t %4s %4s \t %4s %4s %4s \n", "Surname", "GivenName", "Postition", "Height(cm)", "Hits", "AtBats", "Singles", "Doubles", "Triples", "HomeRuns", "Batting Average");
for (int index = 0; index < S.size(); index++)
S.get(index).displayInfo();
}
public static void openFile(ArrayList<Player> S) throws IOException // This method allows the oepning of files into the program
{
Scanner userInput = new Scanner(System.in);
String fileName;
S.removeAll(S); // Empties the list readies it for a new oned
System.out.println("Enter a file name to open: ");
fileName = userInput.next().trim();
File file = new File(fileName);
if (file.exists()) // Checks whether or not the file exists in the directory
{
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext())
{
S.add(new Player(fileInput.next(), fileInput.next(), fileInput.next(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextDouble())); // If it exists it adds the token values into the respective lists
}
fileInput.close(); // Closes further file input
}
else // Error message incase the file-name is not valid
System.out.println("FILE NOT FOUND");
}
public static void saveFile(ArrayList<Player> S) throws IOException // This method allows for the saving of values to an external file
{
Scanner inputInfo = new Scanner(System.in);
String fileName;
System.out.println("Enter a file name to save the info with:");
fileName = inputInfo.next().trim();
File file = new File(fileName);
PrintStream writeFile = new PrintStream(file);
for (int i = 0; i < S.size(); i++) // Gathers all values and prints them to the file in their respective format
{
writeFile.print(S.get(i).getName() + " ");
writeFile.print(S.get(i).getName2() + " ");
writeFile.print(S.get(i).getPosition() + " ");
for (int j = 0; j < 7; j++)
writeFile.print(S.get(i).getMark(j) + " ");
for (int j = 0; j < 1; j++)
writeFile.print(S.get(i).getBatAvg(j));
writeFile.println(" ");
}
writeFile.close(); // Stops any further writing to the file
}
public static void deletePlayerInfo(ArrayList<Player> S) // THis method allows the user to delete any player within the list
{
int deleteIt = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please select the number of the player to be deleted: ");
for (int i = 0; i < S.size(); i++) // Displays only the first/surNames of the players
{
System.out.print(i + ". " + S.get(i).getName());
System.out.println(" ");
}
deleteIt = keyboard.nextInt();
S.remove(deleteIt);
}
public static void addPlayerInfo(ArrayList<Player> S) // This method allows the user to add a new player to the list
{
String firstName = "";
String surName = "";
String posName = "";
int heightVal = 0;
int hitsVal = 0;
int atBatsVal = 0;
int singVal = 0;
int doubVal = 0;
int tripVal = 0;
int homeVal = 0;
Scanner keyboard = new Scanner(System.in); // Various user input
System.out.println("Enter the surname and name of the new player: ");
System.out.println("Surname: ");
surName = keyboard.nextLine();
System.out.println("Name: ");
firstName = keyboard.nextLine();
System.out.println("Enter the position of the new player: ");
System.out.println("Position: ");
posName = keyboard.nextLine();
System.out.println("Enter the height of the new player: ");
heightVal = keyboard.nextInt();
System.out.println("Enter the batting statistics: ");
System.out.println("Hits: ");
hitsVal = keyboard.nextInt();
System.out.println("AtBats: ");
atBatsVal = keyboard.nextInt();
System.out.println("Singles: ");
singVal = keyboard.nextInt();
System.out.println("Doubles: ");
doubVal = keyboard.nextInt();
System.out.println("Triples: ");
tripVal = keyboard.nextInt();
System.out.println("HomeRuns: ");
homeVal = keyboard.nextInt();
S.add(new Player(surName, firstName, posName, heightVal, hitsVal, atBatsVal, singVal, doubVal, tripVal, homeVal, 0));
}
public static void changeHeight(ArrayList<Player> S)
{
int playerSel = 0;
int newHeight = 0;
Scanner keyboard = new Scanner(System.in); // Various user input
System.out.println("Select a player to enter the height for: ");
do
{
for (int i = 0; i < S.size(); i++) // Displays only the first/surNames of the players
{
System.out.print(i + ". " + S.get(i).getName());
System.out.println(" ");
}
playerSel = keyboard.nextInt();
System.out.println("Enter the height for this character: ");
newHeight = keyboard.nextInt();
if (newHeight < 125 && newHeight > 240)
{
System.out.println("WRONG! TRY AGAIN!");
}
else
{
}
} while (newHeight >= 125 && newHeight <= 240);
}
public static void BubbleSort(ArrayList<Player> S){
Player strTemp;
int i = 0;
boolean isSorted = false;
while(i < S.size()&&isSorted==false)
{
isSorted = true;
for(int j = 0; j < (S.size()-1)-i;j++)
{
if(S.get(j).getName().compareToIgnoreCase(S.get(j+1).getName())>0){
strTemp = S.get(j);
S.set(j,S.get(j+1));
S.set(j+1,strTemp);
isSorted = false;
}
}
i++;}
}
public static void InsertionSort(ArrayList<Player> S){ // hits over atbats
int outer;
double inner;
for(outer = 1; outer < S.size();outer++){
double keyItem = S.get(outer).getBatAvg();
inner = outer - 1 ;
while(inner >0&&S.get(inner-1).getBatAvg() > keyItem){
S.set((inner),S.get(inner-1));
inner--;
break;
}
double helpSort = S.get(inner).getBatAvg();
helpSort = keyItem;
}
}
}
class PlayerRip {
public String name;
public String name2;
public String position;
public int [ ] mark = new int[7];
public double [ ] batAvg = new double[1];
static class PlayerInfo extends PlayerRip
{
PlayerInfo() {
this.name = "-1";
this.name2 = "-1";
this.position = "-1";
for (int i=0; i < mark.length; i++)
mark[i] = -1;
}
PlayerInfo(String nam, String nam2, String pos, int a, int b, int c, int d, int e, int f, int g, double h) {
this.name = nam;
this.name2 = nam2;
this.position = pos;
this.mark[0] = a; this.mark[1] = b; this.mark[2] = c; this.mark[3] = d; this.mark[4] = e; this.mark[5] = f; this.mark[6] = g;
batAvg[0] = (((double)mark[1] / (double)mark[2]) * 100);
}
public void setName(String nam) { name = nam; }
public void setName2(String nam2) { name2 = nam2; }
public void setPosition(String pos) { position = pos; }
public void setMark(int index, int mark) { this.mark[index] = mark; }
public void setBatAvg(int index, double batAvg) {this.batAvg[index] = batAvg;}
public String getName() { return this.name; }
public String getName2() { return this.name2; }
public String getPosition() { return this.position; }
public double getBatAvg() { return this.batAvg[0];}
public int getMark(int index) { return this.mark[index]; }
public void setHeight(int index, int mark) { this.mark[index] = mark; }
public int getHeight(int index) { return this.mark[0]; }
public void setHits (int index, int mark) { this.mark [index] = mark; }
public int getHits (int index) { return this.mark [1]; }
public void setAtBats (int index, int mark) { this.mark [index] = mark; }
public int getAtBats(int index) { return this.mark [2]; }
public void setSingles (int index, int mark) { this.mark [index] = mark; }
public int getSingles (int index) { return this.mark [3] ; }
public void setDoubles (int index, int mark) { this.mark [index] = mark; }
public int getDoubles (int index) { return this.mark [4] ; }
public void setTriples (int index, int mark) { this.mark [index] = mark; }
public int getTriples (int index) { return this.mark [5] ; }
public void setHomeRuns (int index, int mark) { this.mark [index] = mark; }
public int getHomeRuns (int index) { return this.mark [6] ; }
}
}
sorry for format im new to the site
}
public static void InsertionSort(ArrayList<Player> S){ // hits over atbats
int outer;
double inner;
for(outer = 1; outer < S.size();outer++){
double keyItem = S.get(outer).getBatAvg();
inner = outer - 1 ;
while(inner >0&&S.get(inner-1).getBatAvg() > keyItem){
S.set((inner),S.get(inner-1));
inner--;
break;
}
double helpSort = S.get(inner).getBatAvg();
helpSort = keyItem;
}
}
}
is the specific area of problems
S.get() and S.set() take a int variable so cast inner to a int.
You defined inner as a double, and in Java, when you do math with a double and an int (such as inner - 1), you'll get a double as a result. This page has a fairly good explanation.
Then when you say S.get(inner - 1), you're saying to use a double as an the index in the ArrayList. The documentation for ArrayList.get says that you can only use an int as an index, and that's why you're getting a compiler error. You're also only allowed to use an int as the index for set, so that's why the compiler would complain about S.set(inner, ...).
You could just cast inner to an int, but it would be much better to declare it as an int in the first place since there's no reason it needs to be a double.

Categories

Resources