Arrays: Comparing one array to another to find averages - java

Hey I'm trying to calculate the of a quiz by comparing two arrays. The two arrays set up are the correct answers and student answers of a quiz. I'm trying to get it to look like this:
Student Marks Average
Arnie Score: 4 Percentage: 0.8
This is because Arnie has got 4 questions correct out of 5 questions. The answers of the student and the correct answers are found in the text document which I already loaded onto an array on my code. The text document contains a 2D array with Arnie's answers in the form of chars and a 1D array containing the correct answers (also chars). There are more students but I would like some guidance on how to get the average for Arnie so I can do it for the rest of the names on my own.
Here is my code so far with the two arrays set up.
public class workingCode
{
private static String newline = System.getProperty("line.separator");
public static void stuAnsOut(String arg []) throws IOException
{
File studentAns = new File("Ans_Stu.txt");
Scanner stuAns = new Scanner(studentAns);
String stuAnsString[] = new String[6];
char stuAnsArray[][] = new char[3][5];
String[] stuNameArray = new String[3];
for (int i = 0; i<stuAnsString.length;i++)
{
stuAnsString[i]=stuAns.nextLine();
}
for (int i=0,j=0; i<stuAnsArray.length && j<stuAnsString.length;i++, j=j+2)
{
stuNameArray[i] = stuAnsString[j];
}
for (int i=0,j=1; i<stuAnsArray.length && j<stuAnsString.length;i++, j=j+2)
{
stuAnsArray[i] = stuAnsString[j].toUpperCase().toCharArray();
}
System.out.println("Student Answers: ");
System.out.printf("%5s","Name");
for (int i =0; i<1;i++)
{
for (int j =1; j<(stuAnsArray[i].length+1);j++)
{
System.out.printf("%5s",j);
}
}
System.out.printf("%n");
for (int i =0; i<stuAnsArray.length;i++)
{
System.out.printf("%5s",stuNameArray[i]);
for (int j=0;j<stuAnsArray[i].length;j++)
{
System.out.printf("%5s",stuAnsArray[i][j]);
}
System.out.printf("%n");
}
}
public static void corAnsOut(String arg []) throws IOException
{
File correctAns = new File("Ans_Cor.txt");
Scanner corAns = new Scanner(correctAns);
String corAnsString = corAns.next();
char corAnsArray[] = new char[5];
for (int i=0; i<corAnsArray.length;i++)
{
corAnsArray[i] = corAnsString.toUpperCase().charAt(i);
}
System.out.println("Correct Answers: ");
System.out.println(newline);
for (int i =1; i<(corAnsArray.length+1);i++)
{
System.out.printf("%5s",i);
}
System.out.printf("%n");
for (int i =0; i<corAnsArray.length;i++)
{
System.out.printf("%5s",corAnsArray[i]);
}
System.out.printf("%n");
}
}
I am not allowed to use ArrayLists, only Arrays. And please use the array names I already have in my code. Thanks!
Edit: This is what I got so far. But it is giving me an error:
public static void compareInteger(int corAnsArray [], int stuAnsArray[])
{double score =0;
for (int i = 0; i < stuAnsArray.length; i++)
{if(stuAnsArray[i] == corAnsArray[i])
score += 1.0;
}
System.out.println(score/corAnsArray.length);
}

What i would do is create a class called Student
public class Student {
private string studentName;
private float marks;
private float average;
// Getters & all parameter constructor
}
Then change your working class to
public class workingCode
{
private static String newline = System.getProperty("line.separator");
public static void stuAnsOut(String arg []) throws IOException
{
File studentAns = new File("Ans_Stu.txt");
Scanner stuAns = new Scanner(studentAns);
List<Student> students = new ArrayList<Student>();
while(stuAns.hasNext()) {
string parts = stuAns.nextLine().split(" ");
students.add(new Student(parts[0],parts[1],parts[2]))
}
// At this point you have all the students in the List
}
}
Now to calculate avg :
float total = 0;
for(Student s : students) {
total += s.getMarks();
}
System.out.println("avg = " + total/students.size());
or
float total = 0;
for(Student s : students) {
total += s.getAverage();
}
System.out.println("avg = " + total);

Code for comparing arrays (both for INT and String arrays):
public class Compare{
public static void main(String[] args){
double averageInt;
double averageString;
int[] correctInt = {9,8,12,6,3,12,90}; //Correct answers
int[] answerInt = {9,8,4,6,3,12,90}; //Student's answers
String[] correctString = {"A","A","B","C"}; //Correct answers
String[] answerString = {"A","C","B","C"}; //Student's answers
Compare compare = new Compare();
averageInt = compare.compareInteger(correctInt, answerInt);
averageString = compare.compareString(correctString, answerString);
System.out.println(averageInt);
System.out.println(averageString);
}
public double compareInteger(int[] correct, int[] answer){ //Compares the int arrays
double score = 0;
for(int i = 0; i < correct.length; i++){
if(correct[i] == answer[i])
score += 1.0;
}
return score/correct.length; //Returns average
}
public double compareString(String[] correct, String[] answer){ //Compares the String arrays
double score = 0;
for(int i = 0; i < correct.length; i++){
if(correct[i].equals(answer[i]))
score += 1.0;
}
return score/correct.length; //Returns average
}
}
I do not understand the marking system though. If you'd explain it more in-depth, I'd be more than happy to provide you with the code.

Related

Sorting arrays from lowest to highest numbers with ratios using methods in Java

I am writing a program that takes in the number of ingredients. The prog
This is my code:
import java.util.Scanner;
public class Restaurant {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
}
Change this sortCalories function to the one below. Also you need to pass price array as second parameter like this sortCalories(calories,price, ingredientName);:
public static void sortCalories(double[] calories,double[] price, String[] ingredientName) {
double temp;
String temp1;
for (int p=0; p<calories.length; p++) {
for (int j=p+1; j<calories.length; j++) {
if(calories[p]/price[p]>calories[j]/price[j]) {
temp = calories[p];
calories[p] = calories[j];
calories[j] = temp;
temp = price[p];
price[p] = price[j];
price[j] = temp;
temp1 = ingredientName[p];
ingredientName[p] = ingredientName[j];
ingredientName[j] = temp1;
}
}
}
}

Add String Input to Array Java

I'm trying to build an Array with 5 strings in there; indexed 0 - 4. After this I need to shuffle the different pieces in the array rounds. The problem that I'm having is that is creating 5 different arrays I think? Could someone explain to me what I'm doing wrong and how to fix it?
To give an better understanding; this is the input of the fileScanner:
5,4 4,5 8,7=6,3 3,2 9,6 4,3=7,6=9,8=5,5 7,8 6,5 6,4
class Pirate {
public static final int MAX_ELEMENTS = 5;
String [] coordinateArray;
int position;
PrintStream out;
Pirate() {
out = new PrintStream(System.out);
}
void addInOrginalArray (String coordinateRowInput) {
coordinateArray = new String [MAX_ELEMENTS];
int position = 0;
coordinateArray[position] = coordinateRowInput;
for (int i = 0; i < coordinateArray.length; i++) {
position += 1;
System.out.println(i + "\t" + coordinateArray [i]);
}
}
void start() {
Scanner fileScanner = UIAuxiliaryMethods.askUserForInput().getScanner();
fileScanner.useDelimiter("=");
while (fileScanner.hasNext()) {
String coordinateRowInput = fileScanner.next();
Scanner coordinateInputScanner = new Scanner(coordinateRowInput);
addInOrginalArray(coordinateRowInput);
}
}
public static void main(String[] argv) {
new Pirate().start();
}
}

Sum of columns and rows of 2D array

I've searched up and down for the fix to my issue, but none seem to work. One particular reference-- this and this, and especially this. However, no matter how I implement them, I receive an OutOfBoundsError, which I can't understand.
The program is extra credit for a class. In truth, it is very simple--
Program Description: Use a two dimensional array to solve the following problem. A company has four sales persons (1 to 4) who sell five different products (1 to 5). Once a day, each salesperson passes in a slip for each different type of product sold. Each slip contains:
The sales persons numberThe product numberThe total dollar value of that product sold that day
Thus, each salesperson passes in between 0 and 5 sales slips per day. Assume that the information from all of the slips for last month is available. Each data line contains 3 numbers (the sales person number, product number, sales).
Write a program that will read all this information for last month’s sales, and summarize the total sales by salesperson by product.
The data provided:
1 2 121.77
1 4 253.66
1 5 184.22
1 1 97.55
2 1 152.44
2 2 104.53
2 4 189.97
2 5 247.88
3 5 235.87
3 4 301.33
3 3 122.15
3 2 301.00
3 1 97.55
4 1 125.66
4 2 315.88
4 4 200.10
4 3 231.45
The error only comes when it tries to calculate the columns. My rows work; no matter how I change the for-loop or any of the indeces in the row or column of the array, it doesn't work. I at first had my rows calculated separately, then my column sums, and it didn't work either. There is something that I'm missing that I'm clearly overlooking.
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.Scanner;
public class prog480u {
static Scanner inFile = null;
public static void main(String[] args) {
try {
// create scanner to read file
inFile = new Scanner(new File ("prog480u.dat"));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.exit(0);
}
// make the array
int x = 0;
int y = 0;
double[][] profits = new double[4][5];
while (inFile.hasNext()) {
x = inFile.nextInt(); // use sales numbers as coordinates
y = inFile.nextInt();
profits[x - 1][y - 1] = inFile.nextDouble();
}
// check if it's okay
System.out.println("");
double[][] columnProfits = sums(profits);
for (int a = 0; a < columnProfits.length; a++) {
System.out.print((a+1) + "\t");
for (int b = 0; b < columnProfits[a].length; b++) {
System.out.print(columnProfits[a][b] + "\t");
}
System.out.println("");
}
double[] bottomRow = columnSums(columnProfits);
for (int a = 0; a < bottomRow.length; a++) {
System.out.print("Total:" + bottomRow + "\t");
}
}
public static double[][] sums (double[][] q) {
double[][] array = new double[5][6];
array = q;
double sum = 0;
for (int a = 0; a < array.length; a++) {
for (int b = 0; b < array[0].length; b ++) {
sum += array[a][b]; // add everything in the row
}
array[a][4] = sum; // set that row to the last column
sum = 0; // reset sum to 0
}
return array;
}
public static double[] columnSums (double[][]q) {
double[][] array = new double[5][6];
array = q;
double sum2 = 0;
double[] columns = new double [5];
for (int a = 0; a < array.length; a++) {
for (int b = 0; b < array[0].length; b ++) {
sum2 += array[b][a];
columns[b] = sum2;
}
sum2 = 0; // reset sum to 0
}
return columns;
}
}
Thank you very much for your time. I have a feeling my program is close to working, but this small mistake is pushing me over the edge.
Here's the working code (I cleaned it up a bit):
You were very close, you just needed to swap your max indicies in the for loops. That's why you were getting a java.lang.ArrayIndexOutOfBoundsException
public static double[] columnSums(double[][] q)
{
double[][] array = q;
double[] columns = new double[5];
for (int a = 0; a < array[0].length; a++)
{
for (int b = 0; b < array.length; b++)
{
columns[a] += array[b][a];
}
}
return columns;
}
Just for fun, I wrote the object oriented version for that.
Easier to handle once the system requires additional functionalities:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
class Sale {
static public ArrayList<Sale> readSales(final String pSalesFileName) throws FileNotFoundException, IOException {
final ArrayList<Sale> ret = new ArrayList<>();
try (final BufferedReader br = new BufferedReader(new FileReader(pSalesFileName))) {
int lineIndex = 0;
while (true) {
++lineIndex;
final String line = br.readLine();
if (line == null) {
System.out.println("Line #" + lineIndex + " is empty, skipping...");
break;
}
try {
final String[] values = line.split("\\s");
final int salesPersonId = Integer.parseInt(values[0]);
final int productId = Integer.parseInt(values[1]);
final float sales = Float.parseFloat(values[2]);
final Sale sale = new Sale(salesPersonId, productId, sales);
ret.add(sale);
} catch (final ArrayIndexOutOfBoundsException e) {
System.err.println("Parse error in line #" + lineIndex + ": '" + line + "'");
}
}
}
return ret;
}
private final int mSalesPersonId;
private final int mProductId;
private final float mSales;
public Sale(final int pSalesPersonId, final int pProductId, final float pSales) {
mSalesPersonId = pSalesPersonId;
mProductId = pProductId;
mSales = pSales;
}
public Integer getSalesPersonId_R() {
return Integer.valueOf(mSalesPersonId);
}
public Integer getProductId_R() {
return Integer.valueOf(mProductId);
}
public float getSales() {
return mSales;
}
}
class SalesPerson {
private final HashMap<Integer, ArrayList<Sale>> mSalesMap = new HashMap<>();
private final int mId;
public SalesPerson(final int pId) {
mId = pId;
}
#Override public boolean equals(final Object pObj) {
if (!(pObj instanceof SalesPerson)) return false;
return ((SalesPerson) pObj).mId == mId;
}
#Override public int hashCode() {
return mId;
}
public void addSale(final Sale pSale) {
final Integer productId = pSale.getProductId_R();
ArrayList<Sale> salesList = mSalesMap.get(productId);
if (salesList == null) {
salesList = new ArrayList<>();
mSalesMap.put(productId, salesList);
}
salesList.add(pSale);
}
public Integer getId_R() {
return Integer.valueOf(mId);
}
public HashMap<Integer, ArrayList<Sale>> getSalesMap() {
return mSalesMap;
}
public float getSalesTotalByProductId(final Integer pProductId) {
final ArrayList<Sale> sales = mSalesMap.get(pProductId);
float accumulator = 0;
for (final Sale sale : sales) {
accumulator += sale.getSales();
}
return accumulator;
}
}
public class SalesFun {
public static void main(final String[] args) throws FileNotFoundException, IOException {
final ArrayList<Sale> sales = Sale.readSales("test/sales.txt");
final HashMap<Integer, SalesPerson> personMap = new HashMap<>();
for (final Sale sale : sales) {
// find right salesperson or create new, then add sale to it
final Integer salesPersonId = sale.getSalesPersonId_R();
SalesPerson person = personMap.get(salesPersonId);
if (person == null) {
person = new SalesPerson(salesPersonId.intValue());
personMap.put(salesPersonId, person);
}
person.addSale(sale);
}
printSales(personMap);
}
static private void printSales(final HashMap<Integer, SalesPerson> pPersonMap) {
for (final SalesPerson person : pPersonMap.values()) {
System.out.println("SalesMan ID: " + person.getId_R());
for (final Entry<Integer, ArrayList<Sale>> entry : person.getSalesMap().entrySet()) {
final Integer productId = entry.getKey();
final float sales = person.getSalesTotalByProductId(productId);
System.out.println("\tProduct ID: " + entry.getKey() + "\tSales: " + sales);
}
}
}
}

Array (list?) required, but int found error

I have the following code:
import java.util.ArrayList;
public class TestCandidate2
{
public static void main(String[] args) {
ArrayList<Candidate> election = new ArrayList<Candidate>();
Candidate john = new Candidate("John Smith", 5000);
election.add(john);
Candidate mary = new Candidate("Mary Miller", 4000);
election.add(mary);
Candidate michael = new Candidate("Micheal Duffy", 6000);
election.add(michael);
Candidate tim = new Candidate("Tim Robinson", 2500);
election.add(tim);
Candidate joe = new Candidate("Joe Ashtony", 1800);
election.add(joe);
System.out.println("Results Per Candidate:");
System.out.println("________________________");
System.out.print("\n");
int totalVotes = 0;
int total = 0;
for(Candidate dec : election) {
System.out.println(dec.toString());
total += dec.getVotes();
totalVotes += dec.getVotes();
}
System.out.print("\n");
System.out.println("Total number of votes in election: " + totalVotes);
}
public static void printVotes(ArrayList<Candidate> table) {
for(int i = 0; i < table.size(); i++) {
System.out.println(table.size()[i]);
}
}
/**public static int getTotal(ArrayList<Candidate> table) {
int total = 0;
for(int i = 0; i < table.size(); i++) {
total = table[i].getVotes() + total;
}
return total;
}*/
/**public static void printResults(ArrayList<Candidate> table) {
double total = getTotal(table);
System.out.print("Candidate Votes Received % of Total Votes");
System.out.print("\n");
for(int i = 0; i < table.length; i++) {
System.out.printf("%s %17d %25.0f", table[i].getName(), table[i].getVotes(), ((table[i].getVotes() / total) * 100));
System.out.println("");
}
}*/
}
Now first off the error I think I should be getting is 'arraylist required, but int found', but instead the error that I am getting is 'array required, but int found'.
I do not know how I should fix the int i, for whenever I put [] to declare it as an array I still get errors. I have tried researching, but no one seems to have my exact problem.
You appear to be accessing your Lists incorrectly. Instead of:
table[i].getVotes()
try:
table.get(i).getVotes();
Or avoid using indexes altogether. For example, you could rewrite getTotal() as:
public static int getTotal(List<Candidate> candidates) {
int total = 0;
foreach (Candidate c : candidates) {
total += c.getVotes();
}
return total;
}
The line producing the error:
System.out.println(table.size()[i]);
is a little confusing, but I think you want:
System.out.println(table.get(i).getVotes());
You could use List.get(int) to get an element by position (not [] that's for arrays). Also, I suggest you program to the list interface. Like
public static void printVotes(List<Candidate> table) {
for(int i = 0; i < table.size(); i++) {
System.out.println(table.get(i));
}
}
You could also use a for-each loop and += like,
public static int getTotal(List<Candidate> table) {
int total = 0;
for(Candidate c : table) {
total += c.getVotes();
}
return total;
}
you should use table.get(i) instead of table[i]. this is an ArrayList not an array

What am I doing wrong with using arrays?

I'm trying to fill an array using a method and later print that array out.
However when I try to do so all it gives me are zeroes. I think my fill method is not working properly but I'm not sure why. I'm trying to understand arrays but so far no good. I would prefer an explanation rather than an answer. If I can get this myself it would be best.
import java.util.Scanner;
public class diverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
double[] score = new double[6];
inputAllScores(score);
printArray(score);
}
public static double[] inputAllScores(double[] x) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
In your inputAllScores, you're writing to a new local array, and returning it, but you're not using the returned array. It would be better if you wrote to the array that you passed into that method (which inside the method is called x).
try
import java.util.Scanner;
public class DiverScore {
static double score = 0;
static double validDegreeOfDiff = 0;
public static void main(String[] args) {
// double[] score = new double[6];
double[] score = inputAllScores(/*score*/);
printArray(score);
}
public static double[] inputAllScores(/*double[] x*/) {
Scanner s = new Scanner(System.in);
double[] array_score = new double[6];
for (int i = 0; i < 6; i++) {
System.out.println("What is the score given by the judge?");
array_score[i] = s.nextDouble();
}
return array_score;
}
public static void printArray(double[] j) {
for (int i = 0; i < 6; i++) {
System.out.println("The array is:" + j[i]);
}
}
}
double[] score = new double[6];
This line simply initializes an array of type double with 6 indexes allocated for it, with each resulting in 0 when printed out.
You could simply change the code in main to this, thus actually using the return value of the inputAllScores function.
public static void main(String[] args) {
double[] score = new double[6];
printArray(inputAllScores(score));
}
HTH

Categories