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.
Related
I read Bert Bates and Katie Sierra's book Java and have a problem.
The Task: to make the game "Battleship" with 3 classes via using ArrayList.
Error: the method setLocationCells(ArrayList < String >) in the type
SimpleDotCom is not applicable for the arguments (int[])
I understand that ArrayList only will hold objects and never primatives. So handing over the list of locations (which are int's) to the ArrayList won't work because they are primatives. But how can I fix it?
Code:
public class SimpleDotComTestDrive {
public static void main(String[] args) {
int numOfGuesses = 0;
GameHelper helper = new GameHelper();
SimpleDotCom theDotCom = new SimpleDotCom();
int randomNum = (int) (Math.random() * 5);
int[] locations = {randomNum, randomNum+1, randomNum+2};
theDotCom.setLocationCells(locations);
boolean isAlive = true;
while(isAlive) {
String guess = helper.getUserInput("Enter the number");
String result = theDotCom.checkYourself(guess);
numOfGuesses++;
if (result.equals("Kill")) {
isAlive = false;
System.out.println("You took " + numOfGuesses + " guesses");
}
}
}
}
public class SimpleDotCom {
private ArrayList<String> locationCells;
public void setLocationCells(ArrayList<String> loc) {
locationCells = loc;
}
public String checkYourself(String stringGuess) {
String result = "Miss";
int index = locationCells.indexOf(stringGuess);
if (index >= 0) {
locationCells.remove(index);
if(locationCells.isEmpty()) {
result = "Kill";
} else {
result = "Hit";
}
}
return result;
}
}
public class GameHelper {
public String getUserInput(String prompt) {
String inputLine = null;
System.out.print(prompt + " ");
try {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0)
return null;
} catch (IOException e) {
System.out.println("IOException:" + e);
}
return inputLine;
}
}
convert ArrayList to int[] in Java
Reason for Basic Solution
Here's a simple example of converting ArrayList<String> to int[] in Java. I think it's better to give you an example not specific to your question, so you can observe the concept and learn.
Step by Step
If we have an ArrayList<String> defined below
List<String> numbersInAList = Arrays.asList("1", "2", "-3");
Then the easiest solution for a beginner would be to loop through each list item and add to a new array. This is because the elements of the list are type String, but you need type int.
We start by creating a new array of the same size as the List
int[] numbers = new int[numbersInAList.size()];
We then iterate through the list
for (int ndx = 0; ndx < numbersInAList.size(); ndx++) {
Then inside the loop we start by casting the String to int
int num = Integer.parseInt(numbersInAList.get(ndx));
But there's a problem. We don't always know the String will contain a numeric value. Integer.parseInt throws an exception for this reason, so we need to handle this case. For our example we'll just print a message and skip the value.
try {
int num = Integer.parseInt(numbersInAList.get(ndx));
} catch (NumberFormatException formatException) {
System.out.println("Oops, that's not a number");
}
We want this new num to be placed in an array, so we'll place it inside the array we defined
numbers[ndx] = num;
or combine the last two steps
numbers[ndx] = Integer.parseInt(numbersInAList.get(ndx));
Final Result
If we combine all of the code from "Step by Step", we get the following
List<String> numbersInAList = Arrays.asList("1", "2", "-3");
int[] numbers = new int[numbersInAList.size()];
for (int ndx = 0; ndx < numbersInAList.size(); ndx++) {
try {
numbers[ndx] = Integer.parseInt(numbersInAList.get(ndx));
} catch (NumberFormatException formatException) {
System.out.println("Oops, that's not a number");
}
}
Important Considerations
Note there are more elegant solutions, such as using Java 8 streams. Also, it's typically discouraged to store ints as Strings, but it can happen, such as reading input.
I can't see where you call setLocationCells(ArrayList<String>) in your code, but if the only problem is storing integers into an ArrayList there is a solution:
ArrayList<Integer> myArray = new ArrayList<Integer>();
myArray.add(1);
myArray.add(2);
It is true that you can't use primitive types as generics, but you can use the Java wrapper types (in this case, java.lang.Integer).
I am trying to create a method which creates a result for a athlete in a competition. I have an ArrayList with the athletes in another class and now I want this method to be able to find the size of the ArrayList and also compare one int attribute of every Athlete with the input number. This is what I have so far, Im really stuck. So my quetions to you are: How do I get my for loop to see the size of the ArrayList athletes? and what is a proper way to check whether or not the input has a matching athlete in the ArrayList(I want it to print out if there is no match)? Thank you
public class ResultList {
Scanner scanner = new Scanner(System.in);
ArrayList<Result> resultList = new ArrayList<Result>();
public ResultList() {
ArrayList<Athlete> temp = new AthleteList().getArrayList();
}
void addResult() {
int competetionNumber;
System.out.print("What is the athletes competetionnumber?");
competetionNumber = scanner.nextInt();
scanner.nextInt();
for (int i = 0; i < athletes.size(); i++) {
}
}
}
Other class with the Athlete ArrayList:
public class AthleteList {
ArrayList<Athlete> athletes = new ArrayList<Athlete>();
public AthleteList () {
}
public ArrayList<Athlete> getArrayList() {
return athletes;
}
You should create a variable that points to the AthleteList class. Then you can see that in the addResult method you just get the ArrayList from the AthleteList and call size() on it and iterate over the Athletes and check the completionNumber(You didn't post the Athlete class so I'm assuming there is a completionNumber property). I create a matched variable to hold on to the matched Athlete. After the loop I check to see if one matched and print out the result.
Hope this helps.
public class ResultList
{
Scanner scanner = new Scanner(System.in);
ArrayList<Result> resultList = new ArrayList<Result>();
AthleteList athleteList;
public ResultList()
{
athleteList = new AthleteList();
}
void addResult()
{
int competetionNumber;
System.out.print("What is the athletes competetionnumber?");
competetionNumber = scanner.nextInt();
scanner.nextInt();
Athlete matched = null;
List<Athlete> athletes = athleteList.getArrayList();
for(int i = 0; i < athletes.size(); i++)
{
if(athlete.completionNumber == completionNumber)
{
//you found a match!!
matched = athlete;
}
}
if(matched == null)
{
System.out.println("No Match Found for " + completionNumber);
}
else
{
System.out.println("Found match: " + matched.toString());
}
}
}
NOTE:
Not sure you need the AthleteList class. It's just holding an ArrayList. If that's all that class will ever do then I suggest you just using an ArrayList. It will make your code cleaner.
I'm making a little card deck program that uses an ArrayList for the deck. One of the limitations set upon me is that the method in which I "deal" the cards must be an Arraylist type. The problem I'm running into is that I don't know how to return just a specific index value from the ArrayList. See below.
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0); //<-- This doesn't work, Netbeans says that it is a string type
//not an ArrayList type. The only thing it will actually
//allow me to return is:
return.al; // But this doesn't work, I don't need to return the whole list,
// just the first element, but Netbeans calls that a String type, not
// ArrayList
So how can I return the first item of the List and still have it be the correct type? The rest of the code doesn't matter, just the Method type and return statement.
EDIT: As requested
package deckofcards;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Deck{
ArrayList<String> al = new ArrayList<>();
public void shuffle(){
Collections.shuffle(al);
}
public String displayDeck(){
String returnDeck = "";
for(int i = 0; i < al.size(); i++){
String printDeck = al.get(i);
returnDeck += printDeck;
}
return returnDeck;
}
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0);
}
public void populate(){
al.add(0, "Ace of Spades");
al.add(1, "Two of Spades");
al.add(2, "Three of Spades");
//yadaa yadaa
If you cannot change the signature and it is mandatory to return an arraylist, then you can create an arraylist with just one element and return it. Something like this:
ArrayList returnList = new ArrayList();
returnList.add(al.get(0));
return returnList;
Does not look great to me :-(
In your specific case, al is an ArrayList<String>. That means al.get(...) returns a String. However, your method is declared as returning an ArrayList, which is not a String. You will either need to change your method return type to String, or you will need to construct a new ArrayList and add your single string to it and return that.
Your declared return type needs to match the object you are returning. So for example:
ArrayList<String> al = ...;
String getSingleItem (int index) {
return al.get(index);
}
ArrayList<String> getSingleItemAsArrayList (int index) {
ArrayList<String> single = new ArrayList<String>();
single.add(al.get(index));
return single;
}
ArrayList<String> getItems () {
return al;
}
By the way, it's generally better to specify the type parameter to ArrayList, e.g. ArrayList<Whatever>, as this can save you a lot of casting things around / unchecked conversions and will give you compile-time checking of types.
Is there a reason that you have to return an ArrayList? Essentially, you are trying to create a method that takes a deck, picks a card, and then returns a deck. You could try and use the subList method someone mentioned above. You could create a new ArrayList containing only the card you want, but that's not very efficient. Or, if your goal is to actually return the whole deck, but with the correct card on top (aka in the first position of the ArrayList), there's lots of info about rearranging values in an ArrayList online.
EDIT: Based on your full code, it looks like the goal is to flip the first card face up. You should do that (not gonna do your homework for you!) and then return the ArrayList that the method took in. IRL, imagine handing someone a deck, they flip the first card face up, then hand the deck back to you.
//ADDING AND deleting employees
//Displaying employee list
public class EployeeDB {
static ArrayList e = new ArrayList<>();
public static boolean addEmployee(Employee e1) {
e.add(e1);
System.out.println("Employee added");
return true;
}
public static boolean deleteEmployee(int ecode) {
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
e.remove(i);
break;
}
}
if (temp == 1)
System.out.println("Emp deleted");
else
System.out.println("Deletion unsuccessful, check ecode again");
return true;
}
public static String showPaySlip(int ecode) {
double salary = 0;
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
salary = e.get(i).getSalary();
break;
}
}
if (temp == 1)
return "Salary is" + salary;
else
return "No employye found with the specified ecode";
}
public static ArrayList<Employee> listAll() {
return e;
}
public static void main(String[] args) {
Employee e1 = new Employee();
e1.setID(20);
e1.setName("sai");
e1.setSalary(150.00);
addEmployee(e1);
Employee e2 = new Employee();
e2.setID(30);
e2.setName("kumar");
e2.setSalary(1500.00);
addEmployee(e2);
deleteEmployee(30);
System.out.println(showPaySlip(30));
for (int i = 0; i < e.size(); i++)
System.out.println(
listAll().get(i).getID() + " " + listAll().get(i).getName() + " " + listAll().get(i).getSalary());
}
}
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 {
/..
}
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.