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
Related
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);
}
}
}
}
I have a programming assignment for an introductory level Java class (the subset sum problem) - for some reason, my recursive method isn't executing properly (it just goes straight to the end of the method and prints out the sorted list). Any help would be appreciated - I'm a newbie and recursive functions are really confusing to me.
package programmingassignment3;
import java.io.*;
import java.util.*;
public class ProgrammingAssignment3 {
static int TARGET = 10;
static ArrayList<Integer> list = new ArrayList<>();
static int SIZE = list.size();
public static void main(String[] args) {
populateSortSet();
sumInt(list);
recursiveSS(list);
}//main
public static void populateSortSet() {
try {
File f = new File("set0.txt");
Scanner input = new Scanner(f);
while (input.hasNext()) {
int ele = input.nextInt();
if (ele < TARGET && !list.contains(ele)) {
list.add(ele);
}//if
}//while
Collections.sort(list);
}//try
catch (IOException e) {
e.printStackTrace();
}//catch
}//populateSet
public static void recursiveSS(ArrayList<Integer> Alist) {
if (Alist.size() == SIZE) {
if (sumInt(Alist) == TARGET) {
System.out.println("The integers that equal " + TARGET + "are: " + Alist);
} //if==TARGET
}//if==SIZE
else {
for (int i = 0; i < SIZE; i++) {
ArrayList<Integer> list1 = new ArrayList<>(Alist);
ArrayList<Integer> list0 = new ArrayList<>(Alist);
list1.add(1);
list0.add(0);
if (sumInt(list0) < TARGET) {
recursiveSS(list0);
}//if
if (sumInt(list1) < TARGET) {
recursiveSS(list1);
}//if
}//for
}//else
System.out.println("echo" + Alist);
}//recursiveSS
public static int sumInt(ArrayList<Integer> Alist) {
int sum = 0;
for (int i = 0; i < SIZE - 1; i++) {
sum += Alist.get(i);
}//for
if (Alist.size() == TARGET) {
sum += Alist.get(Alist.size() - 1);
}//if
return sum;
}//sumInt
}//class
This thing that you do at class level:
static ArrayList<Integer> list = new ArrayList<>();
static int SIZE = list.size();
means that SIZE will be initiated to 0, and stay 0 (even if you add elements to the list.)
This means that the code inside the for-loop will be executed 0 times.
Try something like:
public class ProgrammingAssignment3 {
private static int initialSize;
//...
public static void populateSortSet() {
//populate the list
initialSize = list.size();
}
So you don't set the value of the size variable until the list is actually populated.
That being said, there a quite a few other strange things in your code, so I think you need to specify exactly what you are trying to solve here.
Here's how I'd do it. I hope it clarifies the stopping condition and the recursion. As you can see, static methods are not an issue:
import java.util.ArrayList;
import java.util.List;
/**
* Demo of recursion
* User: mduffy
* Date: 10/3/2014
* Time: 10:56 AM
* #link http://stackoverflow.com/questions/26179574/recursive-method-not-properly-executing?noredirect=1#comment41047653_26179574
*/
public class RecursionDemo {
public static void main(String[] args) {
List<Integer> values = new ArrayList<Integer>();
for (String arg : args) {
values.add(Integer.valueOf(arg));
}
System.out.println(String.format("input values : %s", values));
System.out.println(String.format("iterative sum: %d", getSumUsingIteration(values)));
System.out.println(String.format("recursive sum: %d", getSumUsingRecursion(values)));
}
public static int getSumUsingIteration(List<Integer> values) {
int sum = 0;
if (values != null) {
for (int value : values) {
sum += value;
}
}
return sum;
}
public static int getSumUsingRecursion(List<Integer> values) {
if ((values == null) || (values.size() == 0)) {
return 0;
} else {
if (values.size() == 1) { // This is the stopping condition
return values.get(0);
} else {
return values.get(0) + getSumUsingRecursion(values.subList(1, values.size())); // Here is recursion
}
}
}
}
Here is the case I used to test it:
input values : [1, 2, 3, 4, 5, 6]
iterative sum: 21
recursive sum: 21
Process finished with exit code 0
Thanks everyone. I really appreciate the help. I did figure out the problem and the solution is as follows (closing brace comments removed for the reading pleasure of #duffymo ):
public class ProgrammingAssignment3 {
static int TARGET = 6233;
static ArrayList<Integer> set = new ArrayList<>();
static int SIZE;
static int count = 0;
public static void populateSortSet() {
try {
File f = new File("set3.txt");
Scanner input = new Scanner(f);
while (input.hasNext()) {
int ele = input.nextInt();
if (ele < TARGET && !set.contains(ele)) {
set.add(ele);
}
}
Collections.sort(set);
SIZE = set.size();
System.out.println("The original sorted set: " + set + "\t subset sum = " + TARGET);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void recursiveSS(ArrayList<Integer> list) {
if (list.size() == SIZE) {
if (sumInt(list) == TARGET) {
System.out.print("The Bit subset is: " + list + "\t");
System.out.println("The subset is: " + getSubset(list));
count++;
}
}
else {
ArrayList<Integer> list1 = new ArrayList<>(list);//instantiate list1
ArrayList<Integer> list0 = new ArrayList<>(list);//instantiate list0
list1.add(1);
list0.add(0);
if (sumInt(list0) <= TARGET) {
recursiveSS(list0);
}
if (sumInt(list1) <= TARGET) {
recursiveSS(list1);
}
}
}
public static int sumInt(ArrayList<Integer> list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 1) {
sum += set.get(i);
}
}
return sum;
}
public static ArrayList<Integer> getSubset(ArrayList<Integer> list) {
ArrayList<Integer> l = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 1) {
l.add(set.get(i));
}
}
return l;
}
}
I am new to programming and don't get why the program gives me a run time error for NullPointerException when I have tried initializing n, numInt, and arrayMenu. None of which seem to work. The program's job is to gather a set of random integers to store in an array and allow the user to pick which sort to choose from. Thanks for reading.
import java.util.Scanner;
import java.util.Random;
public class VariousSortsHS
{
private static int[] arrayMenu;
private static Random generator;
/**
* Constructor for objects of class VariousSortsHS.
*/
public VariousSortsHS(int n) //The error starts here
{
arrayMenu = new int[n]; //I don't get why it says null in the array when
//i am initializing the length of the array to n
/*Assigns a random number between 0 too 100.*/
for(int i = 0; i < n; i++)
{
int temp = generator.nextInt(100);
arrayMenu[n] = temp;
}
}
/**
* Selection Sort method.
*/
public static void selection(int n)
{
for(int i = 0; i < arrayMenu.length - 1; i++)
{
int minPos = i;
for(int j = i + 1; j < arrayMenu.length; j++)
{
if(arrayMenu[j] < arrayMenu[minPos]) minPos = j;
}
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[minPos];
arrayMenu[minPos] = temp;
System.out.print(temp + " ");
}
}
/**
* Insertion Sort method.
*/
public static void insertion(int n)
{
for(int i = 1; i < arrayMenu.length; i++)
{
int next = arrayMenu[i];
int j = i;
while(j > 0 && arrayMenu[j - 1] > next)
{
arrayMenu[j] = arrayMenu[j - 1];
j--;
}
arrayMenu[j] = next;
System.out.print(next + " ");
}
}
/**
* Quick Sort method.
*/
public static void quick(int n)
{
int pivot = arrayMenu[0];
int i = 0 - 1;
int j = n + 1;
while(i < j)
{
i++; while(arrayMenu[i] < pivot) i++;
j++; while(arrayMenu[j] > pivot) j++;
if(i < j)
{
int temp = arrayMenu[i];
arrayMenu[i] = arrayMenu[j];
arrayMenu[j] = temp;
System.out.print(temp + " ");
}
}
}
/**
* Main method that allows user to input data.
*/
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Do you wish to sort random integers? (Yes or No) ");
String answer = in.next();
String answer2 = answer.toLowerCase();
do
{
/*Prompts for array length.*/
System.out.println("How many random integers do you wish to sort?");
int numInt = in.nextInt();
/*Promps for sort selection choice.*/
System.out.println("Select a sort to use: \n\t1)Selection\n\t2)Insertion\n\t3)Quick");
String sort = in.next();
String sort2 = sort.toLowerCase();
if(sort2.equals("selection"))
{
selection(numInt);
}
else if(sort2.equals("insertion"))
{
insertion(numInt);
}
else if(sort2.equals("quick"))
{
quick(numInt);
}
else
{
System.out.println("You have entered the wrong input.");
}
} while(!answer2.equals("no"));
}
}
Everything in your code is static. This means the constructor you wrote is never called, and the array has never been changed from its default value, null. Consider changing your constructor code to a static initialization block instead.
generator is never set to anything, so it's null too and you can't call nextInt on it
initializing the array is setting arrayMenu[n] instead of arrayMenu[i]
When you call insertion(numInt);, method public static void insertion(int n) is called and then you are trying to do the for-loop like this for(int i = 1; i < arrayMenu.length; i++)
However, arrayMenu was not initialized, it is null. When you try to call a length, on null, you get NullPointerException.
You need to add a static constructor and initialize the size using a static int
//set parameter = n
public static int parameter;
static
{
arrayMenu = new int[parameter];
}
I have this class and in the printVotes method I had to do the if statement every time to print each votes. Is there any way to combine both the if statements. Could I print all the names of the candidates and the number of votes they got at the same time?
public class TestCandidate {
public static void main(String[] args)
{
Canidate[] canidate = new Canidate[5];
// create canidate
canidate[0] = new Canidate("John Smith", 5000);
canidate[1] = new Canidate("Mary Miller", 4000);
canidate[2] = new Canidate("Michael Duffy", 6000);
canidate[3] = new Canidate("Tim Robinson", 2500);
canidate[4] = new Canidate("Joe Ashtony", 1800);
printVotes(canidate) ;
}
public static void printVotes(Canidate [] List)
{
double max;
int index;
if (List.length != 0)
{
index = 0;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
}
if (List.length != 0)
{
index = 1;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
return;
}
}
}
If you pass in a List<Candidate> candidates; and assuming that each candidate has a List<Integer> Votes:
List<Integer> votes= new ArrayList<Integer>() ;
for(Candidate c:candidates)
{
votes.add(c.GetVote()) ;
}
for(Integer v:votes)
{
System.out.println(v);
}
You could override the Candidate class's toString() method like so:
public String toString() {
return "Candidate Name: " + this.name + "\nVotes: " + this.votes;
}
Then your printVotes method would look something like this:
public static void printVotes(Candidate[] list) {
for(Candidate c : list) {
System.out.println(c);
}
}
As someone else mentioned, avoid using capital letters in variable names especially in cases where words such as List are used. List is a collection type and can be easily confused.
I am attempting to write a simple Genetic Algorithm in Java after reading a book on Machine Learning and have stumbled on the basics. I'm out of practice with Java so I'm probably missing something extremely simple.
Individual
public class Individual {
int n;
int[] genes = new int[500];
int fitnessValue;
public int getFitnessValue() {
return fitnessValue;
}
public void setFitnessValue(int fitnessValue) {
this.fitnessValue = fitnessValue;
}
public int[] getGenes() {
return genes;
}
public void setGenes(int index, int gene) {
this.genes[index] = gene;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
// Constructor
public Individual() {
}
}
Population
import java.util.Random;
public class Population {
public Population() {
}
public static void main(String[] args) {
Random rand = new Random();
int p = rand.nextInt(10);
int n = rand.nextInt(10);
Individual pop[] = new Individual[p];
System.out.println("P is: " + p + "\nN is: " + n);
for(int j = 0; j <= p; j++) {
for(int i = 0; i <= n; i++) {
pop[j].genes[i] = rand.nextInt(2);
}
}
}
public void addPopulation() {
}
}
The aim of this code is to populate the Population and the Genes with a random number. Could someone please take a look at my code to see where I'm going wrong?
before
pop[j].genes[i] = rand.nextInt(2);
add
pop[j] = new Individual();
the elements of the array are null.
I believe you need to initialize pop[j] before doing pop[j].genes[i] = rand.nextInt();
Individual pop[] = new Individual[p];
This just initializes the array, not the individual elements. Try to put pop[j] = new Individual() between your two loops.
What they said...
Also, do you mean to call your setGenes method, or do you just want to directly access the gene array.
From what I understand of your code I think you need to do this:
for(int j = 0; j <= p; j++) {
pop[j] = new Individual();
for(int i = 0; i <= n; i++) {
pop[j].setGenes(i, rand.nextInt(2));
}
}