Im trying to put arraylists into an arraylist. Adding data to the new arrays, then print them in order. Im only getting errors.
Is this the right way to create an arraylist in another arraylist using a for loop?
I would also like to now how I can get data from the array in a better way then these long expresions.
My errors
jogging.java:101: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.ArrayList
res.get(iter).add(new Resultat(name,time));
jogging.java:152: warning: [unchecked] unchecked conversion found : java.util.ArrayList required: java.util.List<T> Collections.sort(res.get(iter2));
jogging.java:152: warning: [unchecked] unchecked method invocation: <T>sort(java.util.List<T>) in java.util.Collections is applied to (java.util.ArrayList)
Collections.sort(res.get(iter2));
import java.util.;
import java.lang.;
class Resultat implements Comparable<Resultat> {
String namn;
double tid;
public Resultat( String n, double t ) {
namn = n;
tid = t;
}
public String toString()
{
return namn + " "+ tid;
}
public int compareTo( Resultat r ) {
if (this.tid < r.tid){
return -1;
}
else if (this.tid > r.tid){
return 1;
}
else if (this.tid == r.tid && this.namn.compareTo(r.namn) <= 0)
{
return -1;
}
else if ( this.tid == r.tid && this.namn.compareTo(r.namn) >= 0){
return 1;
}
else {return 0;}
}
}
public class jogging {
public static void main( String[] args ){
int runners = scan.nextInt();
int competitions = scan.nextInt();
//create arraylist with arraylists within
ArrayList <ArrayList> res = new ArrayList<ArrayList>();
for(int i = 0; i <= competitions; ++i){
res.add(new ArrayList<Resultat>());
}
for (int i = 0; i < runners; i++){
String name = scan.next();
//runs the person made
int antalruns = scan.nextInt();
for(int n = 0; n <antalruns; n++){
//number of the run
int compnumber = scan.nextInt();
//time for the run
double time = scan.nextDouble();
for(int iter = 0; iter < res.size(); ++iter){
res.get(iter).add(new Resultat(name,time));
}
}
}
for(int iter2 = 0; iter2 < res.size(); ++iter2) {
Collections.sort(res.get(iter2));
System.out.println(iter2);
for(int it = 0; it < res.get(iter2).size(); ++it) {
System.out.println(res.get(iter2).get(it));
}
}
}
}
The unchecked warnings are because you haven't declared the generic types of the 2nd ArrayList. Try using
ArrayList <ArrayList<Resultat>> res = new ArrayList<ArrayList<Resultat>>();
Yes, it's a bit tedious. :-(
Also, most think it good practice to use the interface (e.g. List, not ArrayList) on the left side, just in case you change your mind as to the implementation in the future. e.g.
List <List<Resultat>> res = new ArrayList<ArrayList<Resultat>>();
ADDED
Also, you could simplify your compareTo() method. For comparing the tids, look at Double.compare(). Something like:
public int compareTo( Resultat r ) {
int compare = Double.compare(tid, r.tod);
if (compare != 0)
return compare;
else
return namn.compareTo(r.namn);
}
Every time you create a ArrayLIst you need to declare its datatype. So when you create a ArrayLIst inside ArrayList you need to write:
ArrayList<ArrayList<Resultat>> res = new ArrayList<ArrayList<Resultat>>();
Also compiler has to put less effort if you write:
import java.util.ArrayList; // NOT: import java.util.*;
Having a class name start from upperCase is java naming convention. So it is always a good practice to write your class name as:
public class Jogging {
/..
}
Related
I'm currently trying to working through a problem with ArrayList.
This is supposed to take the input of the user and customers sales and display the top customer. Yet, I'm having and issue with an inner while.
Using VSCODE. The inner while is throwing an error within the inner if sales.get(j) > largest) stating the > is undefined.
Please, any help would be greatly appreciated.
import java.util.ArrayList;
import java.util.Scanner;
public class TopCusomters {
public static void main(String[] args)
{
ArrayList sales = new ArrayList();
ArrayList customers = new ArrayList();
int numOfItems = 0;
double price = 0;
Scanner in = new Scanner(System.in);
boolean entryComplete = false;
do {
System.println("Customers Names");
customers.add(in.next());
System.println("Sales of the Customer (0 to end):");
price = in.nextDouble();
sales.add(price);
numOfItems++;
}while(price != 0 && mumOfItems < 100);
System.out.println("Please provide values of N");
int topN = in.nextInt();
ArrayList topCustomers = nameOfBestCustomers(sales, customers, topN);
System.out.println(" Top Customers list" + "is" + topCustomers.toString());
}
public static ArrayList nameOfBestCustomers (ArrayList sales,ArrayList customers, int topN)
{
ArrayList bestCustomers = new ArrayList();
sortCustomers(sales,customers);
int i = 0;
while (i)
{
bestCustomers.add(customers.get(i));
i++;
}
return bestCustomers;
}
public static void sortCustomers(ArrayList sales, ArrayList customers)
{
int i = 0;
double temp = 0;
String tempName = "";
while (i)
{
double largest = sales.get(i);
int largestIndex = i;
int j = i;
while (j)
{
if(sales.get(j) > largest)
{
largest = sales.get(j);
largestIndex = j;
}
i++;
}
temp = sales.get(i);
sales.set(i,sales.get(largestIndex));
sales.set(largestIndex,temp);
tempName = customers.get(i);
customers.set(i,customers.get(largestIndex));
customers.set(largestIndex, tempName);
i++;
}
}
}
You are not specifying object types that lists are holding for below declarations ,
ArrayList sales = new ArrayList();
ArrayList customers = new ArrayList();
So when you retrieve objects from list and try to apply operators, Java doesn't know which type its working on. ( Java assumes java.lang.Object and operator > doesn't make sense on Object )
For long term solution , declarations should be changed as below or you can try that after explicit cast too,
List<Double> sales = new ArrayList<>();
List<String> customers = new ArrayList<>();
where Double is java.lang.Double
ArrayList without type will default to ArrayList<Object>, that means that sales.get(j)'s return value is Object. You probably want ArrayList<Double>.
You have multiple syntax errors, for example:
Conditional expression like while (<expr>) { ... } need to evaluate to boolean. while(i) is not a valid expression, see
The while and do-while Statements docs.
do { ... } is not a valid Java construct, most likely you tried to use a do-while loop do { ... } while (<expr>); loop.
You are using rawtype ArrayList. Most likely it should be List<Double>. You need generics to compare sales elements with double largest using auto-boxing, see Lesson: Generics (Updated) docs.
I was trying to perform sorting of integers in an array and it worked fine.
But when i try to modify the program by including a "pass by reference" concept via a method, it is throwing error "cannot find symbol".
I am new to JAVA and learning by my own, Please help me with what I am doing wrong here.
import java.util.*;
import java.io.*;
public class Sort {
public static void main(String[] args) {
Sort obj = new Sort();
Scanner in = new Scanner(System.in);
int i, p, k, arr[];
arr = new int[10];
System.out.println("Enter the numbers for sorting \n");
for (i = 0; i < 5; i++) {
arr[i] = in.nextInt();
}
for (i = 0; i < 5; i++) {
for (p = 0; p < 5; p++) {
if (arr[i] < arr[p]) {
/*
* moving the below block for swapping to a new method. k =
* arr[i]; arr[i]= arr[p]; arr[p]= k;
*/
obj.swap(obj);
}
}
}
System.out.println("\n");
for (i = 0; i < 5; i++)
System.out.println(arr[i]);
}
public void swap(Sort m) {
m.k = m.arr[i];
m.arr[i] = m.arr[p];
m.arr[p] = m.k;
}
}
The error I am getting is :
"Sort.java:44: error: cannot find symbol
m.k = m.arr[i];
^
"
Similarly 10 such errors for other variables as well.
You are trying to use index variables (i and p) that don't exist in the context you are trying to use them (inside swap() method body) as well as members of Sort (k and arr) which don't exist. The scope of all these, you have limited to the method body of main():-
public void swap(Sort m) {
m.k = m.arr[i]; //No 'i' in swap(). No 'k' or 'arr' in 'm'(an instance of 'Sort')
m.arr[i] = m.arr[p]; //No 'p' in swap()
m.arr[p] = m.k;
}
Short-term Solution
Change your swap() method to
//Now accepting in i and p
public void swap(Sort m, int i, int p) {
m.k = m.arr[i];
m.arr[i] = m.arr[p];
m.arr[p] = m.k;
}
then call it like this
obj.swap(obj, i, p); //pass in i and p
and move your Sort variables to be accessible members of Sort
public class Sort {
public static int k; //now accessible with m.k
public static int[] arr = new int[10]; //now accessible with m.arr
...
}
Lastly, is it intentional that your array is 10 long but you only fill it with 5 numbers?
Pass-by-Reference
There is no "pass-by-reference" in Java. Everything is passed by value. The confusing thing is that what is passed by value is technically a reference to the object, meaning you get strange effects like you can edit the object but not reassign it.
Solution: move the stuff back from the swap method to where it was.
Alternatively, provide the necessary values as parameters to swap.
I'm building a simple genetic algorithm based off this guide. I have made an 'Individual' class, which is as follows.
package simpleGA;
public class Individual {
public static int defaultGeneLength = 64;
private static byte genes[] = new byte[defaultGeneLength];
private int fitness = 0;
public void generateIndividual(){
for (int i = 0; i < defaultGeneLength; i++){
byte gene = (byte) Math.round(Math.random());
genes[i] = gene;
}
}
public byte getGene(int index) {
return genes[index];
}
public int size(){
return genes.length;
}
public int getFitness(){
if (fitness == 0){
fitness = FitnessCalc.getFitness(this);
}
return fitness;
}
}
I have also made a class called 'FitnessCalc', which is as follows.
package simpleGA;
import java.util.Scanner;
public class FitnessCalc {
static byte[] solution = new byte[64];
static String newSolution;
static Scanner input = new Scanner(System.in);
static void setSolution(){
do{
newSolution = null;
System.out.println("Please enter a string of '1's and '0's of length 64.");
newSolution = input.next();
}
while(newSolution.length() != 64);
solution = new byte[newSolution.length()];
for (int i = 0; i < newSolution.length(); i++) {
String character = newSolution.substring(i, i + 1);
solution[i] = Byte.parseByte(character);
}
}
static int getFitness(Individual individual){
int fitness = 0;
for (int i = 0; i < solution.length && i < individual.size(); i++) {
if (individual.getGene(i) == solution[i]) {
fitness++;
}
}
return fitness;
}
}
My problem is that in the getFitness method in the 'FitnessCalc' class, the compiler returns an error for both the size and getGene methods, saying
"The method size() is undefined for the type Individual" and
"The method getGene(int) is undefined for the type Individual".
I'm not sure what this means. I've looked at other questions like this but none of the scenarios seem to relate to mine. Can anyone help?
EDIT:
After cleaning and rebuilding the project (I am using Eclipse), the errors remained, and a new error in my remaining class, 'Population', has appeared.
package simpleGA;
public class Population {
Individual[] individuals;
public Population (int populationSize, boolean initialise){
individuals = new Individual[populationSize];
if (initialise){
for (int i = 0; i < size(); i++){
Individual newIndividual = new Individual();
newIndividual.generateIndividual();
saveIndividual(i, newIndividual);
}
}
}
public int size(){
return individuals.length;
}
public void saveIndividual(int index, Individual indiv){
individuals[index] = indiv;
}
}
The error is with the generateIndividual method being called in the Population method, and says the same as the other two:
"The method generateIndividual() is undefined for the type Individual".
The generateIndividual method is defined in the 'Individual' class.
To anyone wondering, I got rid of the issue by rewriting the code slightly. I moved the getFitness method over to the 'Individual' class, and that seemed to work. After this I made sure that the 'Individual' class only used methods from within its own class, so that classes weren't dependent on each other.
When i call my TruthTable class & populate it w/inputs, I can't access individual slots in the array when I'm trying to set the inputs of the AND gates?
threeAndGates.java -the class where the error happens
import java.util.Scanner;
public class threeAndGates {
public static void main(String[] args){
LogicGate and1 = new LogicGate(LogicGate.AND);
LogicGate and2 = new LogicGate(LogicGate.AND);
LogicGate and3 = new LogicGate(LogicGate.AND);
System.out.print("What is the number of Inputs? ");
Scanner scan = new Scanner(System.in);
int numOfInputs = scan.nextInt();
System.out.print("What is the number of Outputs? ");
int numOfOutputs = scan.nextInt();
TruthTable Table1 = new TruthTable(numOfInputs,numOfOutputs);
Table1.PopulateTruthTable();
//below is where it is giving me "the type of the expression must be an array type but it resolves to TruthTable"
for(int r = 0; r<(Math.pow(2, numOfInputs)) ; r++ ){
and1.setInput1(Table1[r][0]);
and1.setInput2(Table1[r][1]);
and2.setInput1(Truth1[r][2]);
and2.setInput2(Truth1[r][3]);
and3.setInput1(and1.getOutput());
and3.setInput2(and2.getOutput());
Table1[r][numOfInputs + numOfOutputs] = and3.getOutput();
}
Table1.printTruthTable();
}
}
TruthTable.java
public class TruthTable {
private int numOfInputs;
private boolean[][] table;
public TruthTable(int inputs, int outputs){
this.numOfInputs = inputs;
int rows = (int) Math.pow(2,inputs);
int columns = inputs + outputs;
table = new boolean[rows][columns];
}
public void printTruthTable(){
for(int r = 0 ; r < table.length ; r++){
for(int c = 0; c < table[r].length; c++)
System.out.printf("%-5b ", table[r][c]);
System.out.println();
}
}
public String toString(){
String outStr = new String();
for(int r = 0; r < table.length; r++){
for(int c = 0; c < table[r].length; c++)
outStr += String.format("%-5b ", table[r][c]);
outStr += '\n';
}
return outStr;
}
public boolean[][] PopulateTruthTable(){
String s;
String r ="";
int[] Line = new int[numOfInputs];
boolean bit;
for ( int i= 0; i < Math.pow(2,numOfInputs) ; i++){
int x = numOfInputs - Integer.toBinaryString(i).length();
for(int j = 0; j<x ; j++)
r += "0";
s = r + Integer.toBinaryString(i);
for(int k=0; k<s.length() ;k++){
Line[k] = s.charAt(k)-48;
}
for(int m=0 ; m<numOfInputs ; m++){
if(Line[m]==1) bit = true;
else bit = false;
table[i][m] = bit;
}
r="";
}
return table;
}
}
Your TruthTable class is not an Array. It contains an Array. You could add a get and set method to your TruthTable class:
public boolean getValueAt(int x, int y) {
return this.table[x][y];
}
public void setValueAt(int x, int y, boolean value) {
this.table[x][y] = value;
}
and use that to work with the TruthTable values.
This is unrelated to your problem, but when naming variables in your classes, the general practice is to use lower case. For example you have:
TruthTable Table1 = new TruthTable(numOfInputs,numOfOutputs);
would be better
TruthTable table1 = new TruthTable(numOfInputs,numOfOutputs);
and probably best as
TruthTable truthTable = new TruthTable(numOfInputs,numOfOutputs);
The better and more consistent you name things the easier it will be to read down the road.
Your TruthTable class isn't a mutil-dimensional array; it has a multi-dimensional array field. Therefor, you can not use the following syntax:
tableInstance[x][y]
If you TruthTable's table field was public, or better yet, it had a getter, you could do womthing like this instead...
tableInstance.getTable()[x][y]
Some languages (like C#) also support operator overloading which would allow you define the behaviour of using the [] index operator (or others like +, /, etc.). This would allow you to make the indexing work. Unfortunately, Java doesn't have this feature.
This is more of a comment than an answer but I needed more space.
If your code causes you problems later, may I make a suggestion? Break down populateTruthTable into 2 or 3 methods, putting each loop in it's own well named method because Each method should do exactly one thing
Also you probably shouldn't be accessing the array directly from the main class, instead put all the code from your main classes "for" loop into a method in the TruthTable class and call that method from main because you should Tell an object what to do rather than asking for it's data.
I'm not trying to say you're doing it wrong or anything, you are obviously doing very well, but it's always good to pick up more coding tricks/practices as you go along and you seem like you are at the level where these would come in handy.
I am currently working on a lab and would like to know how to handle the following problem which I have spent at least two hours on:
I am asked to create an ArrayList containing the values 1, 2, 3, 4 and 10. Whilst I usually never have any trouble creating an ArrayList with said values, I am having trouble this time. Should I create the ArrayList outside of the method or inside the method? Whichever way I have attempted it, I have been presented with numerous error messages. How do I add values to this ArrayList parameter? I have attempted to add values to it when calling it from the main method, but this still doesn't work. Here is the method in question.
public static double ScalesFitness(ArrayList<Double> weights){
//code emitted for illustration purposes
}
If anybody could help me it would be greatly appreciated. If any more code is required, then please let me know.
Thank you so much.
Mick.
EDIT: The code for the class in question is as follows:
import java.util.*;
public class ScalesSolution
{
private static String scasol;
//Creates a new scales solution based on a string parameter
//The string parameter is checked to see if it contains all zeros and ones
//Otherwise the random binary string generator is used (n = length of parameter)
public ScalesSolution(String s)
{
boolean ok = true;
int n = s.length();
for(int i=0;i<n;++i)
{
char si = s.charAt(i);
if (si != '0' && si != '1') ok = false;
}
if (ok)
{
scasol = s;
}
else
{
scasol = RandomBinaryString(n);
}
}
private static String RandomBinaryString(int n)
{
String s = new String();
for(int i = 0; i > s.length(); i++){
CS2004.UI(0,1);
if(i == 0){
System.out.println(s + "0");
}
else if(i == 0){
System.out.println(s + "1");
}
}
return(s);
}
public ScalesSolution(int n)
{
scasol = RandomBinaryString(n);
}
//This is the fitness function for the Scales problem
//This function returns -1 if the number of weights is less than
//the size of the current solution
public static double scalesFitness(ArrayList<Double> weights)
{
if (scasol.length() > weights.size()) return(-1);
double lhs = 0.0,rhs = 0.0;
double L = 0;
double R = 0;
for(int i = 0; i < scasol.length(); i++){
if(lhs == 0){
L = L + i;
}
else{
R = R + i;
}
}
int n = scasol.length();
return(Math.abs(lhs-rhs));
}
//Display the string without a new line
public void print()
{
System.out.print(scasol);
}
//Display the string with a new line
public void println()
{
print();
System.out.println();
}
}
The other class file that I am using (Lab7) is:
import java.util.ArrayList;
public class Lab7 {
public static void main(String args[])
{
for(int i = 0 ; i < 10; ++i)
{
double x = CS2004.UI(-1, 1);
System.out.println(x);
}
System.out.println();
ScalesSolution s = new ScalesSolution("10101");
s.println();
}
}
you can these
1) use varargs instead of list
public static double scalesFitness(Double...weights)
so you can call this method with :
scalesFitness(1.0, 2.0, 3.0, 4.0, 10.0);
2) create the list outside your method
ArrayList<Double> weights = new ArrayList<Double>();
weights.add(1.0);
weights.add(2.0);
weights.add(3.0);
weights.add(4.0);
weights.add(10.0);
scalesFitness(weights);
Towards your initial posting, this would work:
scalesFitness (new ArrayList<Double> (Arrays.asList (new Double [] {1.0, 2.0, 4.0, 10.0})));
You may explicitly list the values in Array form, but
you have to use 1.0 instead of 1, to indicate doubles
you have to prefix it with new Double [] to make an Array, and an Array not just of doubles
Arrays.asList() creates a form of List, but not an ArrayList, but
fortunately, ArrayList accepts a Collection as initial parameter in its constructor.
So with nearly no boilerplate, you're done. :)
If you can rewrite scalesFitness that would be of course a bit more easy. List<Double> as parameter is already an improvement.
Should I create the ArrayList outside of the method or inside the method?
The ArrayList is a parameter for the method so it need to be created outside the method, before you invoke the method.
You need to import ArrayList in the file that includes your methods. This is probably solved but that's the issue I was encountering.