Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am working with an ArrayList of objects that contain multiple variables. For example:
// pseudo code
class Ticket {
int gameID
double price
int seatnumber
}
and I have an ArrayList of multiple Ticket objects and need to access them. I've looked at the javadoc and so far I have come up with
list.get(index).attribute
However I get a compile-error saying:
cannot find symbol
am I doing something wrong with the syntax?
here is my code:
public static void printGameMoney(ArrayList games, ArrayList tickets)
{
double total = 0;
double tickMoney = 0;
for (int i=0; i<tickets.size(); i++)
{
double tickMoney = tickets.get(i).priceOfTick;
total = total + tickMoney;
}
}
You code is "old-school", you should use typed-types, interfaces and new style for-loop:
public static void printGameMoney(final List<Game> games, final List<Ticket> tickets)
{
double total = 0;
for (final Ticket ticket : tickets)
{
final double tickMoney = ticket.getPriceOfTick();
total = total + tickMoney;
}
}
Also note this method is strange as it doesn't return anything.
If attribute is really one of your class member then please use as follow.
((Ticket) list.get(index)).attribute;
Start by putting semicolons after each field declaration:
class Ticket {
int gameID;
double price;
int seatnumber;
}
Also, show the exact code you're using instead of list.get(index).attribute.
List<Object> list = new ArrayList<Object>();
((Ticket)list.get(x)).attribute;
Use this instead:
public static void printGameMoney(ArrayList games, ArrayList<Ticket> tickets)
{
double total = 0;
double tickMoney = 0;
for (int i=0; i<tickets.size(); i++)
{
double tickMoney = tickets.get(i).priceOfTick;
total = total + tickMoney;
}
}
Basically, the change leads to ArrayList<Ticket> instead of simple ArrayList. This way you tell the compiler that objects inside your ArrayList are of Ticket type, therefore they have attributes you specified (e.g. priceOfTick).
Same goes for games, so if you have Game class, you should use ArrayList<Game> games.
You have to access like this ,list.get(i).price; not list.price.get(i);
for (int i=0; i<tickets.size(); i++)
{
double tickMoney = list.get(i).price;
total = total + tickMoney;
}
Here problem is that with your deceleration of ArrayList
If you declare like ArrayList<Ticket> you need not to cast there while getting. Other wise you need a cast there. More over use for each loop.
Related
I want to add a new element that has several arguments in an array. I know how to add with just one argument, but with more i don't know.
My code is:
private Calculate[] calculation;
public Element(int numElements) {
calculation = new Calculate[numElements];
}
public void addElement(Date elementDate, double price, ElementType type) {
int numElements = elements.length;
int i = 0;
if (i < numElements) {
Calculate[i] = calculation.elementDate;
Calculate[i] = calculation.price;
Calculate[i] = calculation.type;
i++;
}
}
Calculate[i] = calculation.elementDate;
Calculate[i] = calculation.price;
Calculate[i] = calculation.type;
You shouldn't assign to the same array index 3 times. You're overriding what you've just set.
Try this (Calculate should have a constructor):
Calculate[i] = new Calculate(elementDate, price, type);
You're also maintaining an index i, but you're not looping over anything. i is just incremented from from zero to one and is not really used (apart from an almost useless conditional check).
I suggest you read over a beginners Java tutorial. You seem to be missing a lot of the fundamentals, and Stack Overflow is not a place where we should have to show you how to write a for-loop. It's well-documented and demonstrated in a tonne of tutorials already.
I assume Calculate is a class defined else where with a constructor
There is a couple of issues in this piece of code:
You want to update the array, but specify array. Calculate[] is the array type. The name if the array is calculation. The other thing is that you are trying to access calculation.elementDate etc. but since that is an array, it does not have the field elementDate. I assume your Calculate class has that field. Also, you are not applying a loop. So currently your code will only update the array on index 0.
My code:
public void addElement(Date elementDate, double price, ElementType type) {
for(int i = 0; i < elements.length; i++) { // for loop over all elements in your array
Calculate calculate = new Calculate(elementDate, price, type) // I assume this constructor is available to initialize the Calculate object
calculation[i] = calculate;
}
Hope this helps.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to create one array of objects of my class Percurso for another class Custos, but I don't know how to do this. Here is what is asking in the question:
Receives as parameter an array of path-type objects
My code :
Class Custos :
public class Custos {
public String calcularViagem(Percurso [] p) {
return "";
}
}
Class Percurso :
private double kmPercorrida;
private double valorCombustivel;
private double valorPedagio;
public double getKmPercorrida() {
return kmPercorrida;
}
public void setKmPercorrida(double kmPercorrida) {
this.kmPercorrida = kmPercorrida;
}
public double getValorCombustivel() {
return valorCombustivel;
}
public void setValorCombustivel(double valorCombustivel) {
this.valorCombustivel = valorCombustivel;
}
public double getValorPedagio() {
return valorPedagio;
}
public void setValorPedagio(double valorPedagio) {
this.valorPedagio = valorPedagio;
}
public Percurso() {
this(0,0,0);
}
public Percurso(double kmPercorrida, double valorCombustivel,
double valorPedagio) {
this.kmPercorrida = kmPercorrida;
this.valorCombustivel = valorCombustivel;
this.valorPedagio = valorPedagio;
}
How can I do this ? If someone can help, I will thanks.
PS: Before someone say that this post is similar to other questions about array, it's not,I looked for questions similar that could help and I didn't found any that really could help me.
Creating an array of Percurso objects is the same as creating an array of any object. To create the array, you will need to include a line like this:
Percurso[] percursoArray = new Percurso[LENGTH]; //with your own array name and length
However, that just creates an array; it doesn't put anything in it. To put Percurso objects in the array (or, more accurately references to the objects), you need code like this.
percusoArray[0] = new Percurso(5, 2, 1);
percusoArray[1] = new Percurso(1, 1, 1); //etc
Or, if the array is long, you could create the objects in a for loop:
for (int i = 0; i < LENGTH; i++){
percusoArray[i] = new Percurso(1,2,3); //with your own values
}
Of course, a question remains-- where should you put this code? Is the array of Percurso an attribute of Custos? If so, you might create the array as a class variable of Custos and populate it in the constructor for Custos. If it's not an attribute of Custos, but rather just a parameter for one of Custos methods, you'll need this code in whichever part of your code calls calcularViagem(), whether that is another method in Custos, a method in another class, or from inside your main method.
I'm quite new to arrays and methods, and I've been seeing this error recurring through several programs: error '[' expected.
In each occasion, it seems to correct itself as I adjust something else, but in this particular case, I am completely stumped.
By the way, I am using several methods and arrays to create a quiz (before you ask, yes, this is an assignment and I agree, a list is a better way to handle this data - but that is not an option).
It is possible that I am not passing the arrays correctly between methods, as I'm a little muddy on that process. From my understanding, in order to send/receive (i.e. import/export) an array or other variable between methods, I must declare that variable/array in the method header parameters.
import java.util.Scanner;
public class H7pseudo
{
public static void main(String[] args)
{
//call getAnswerkey method
getAnswerkey(answerkey[i]);
//call getAnswers method
getAnswers(answers[i]);
//call passed method? necessary or no?
boolean passed = passed(answerkey[i], answers[i], qMissed[i], points);
//Print results of grading
if (passed)
{
System.out.println("Congratulations! You passed.");
}
else
{
System.out.println("Try again, sucka. You FAILED.");
}
//call totalPoints
totalIncorrect(points);
//call questionsMissed
questionsMissed(qMissed[i]);
}
//get answer key (create answerkey array & export)
public static void getAnswerkey(answerkey[i])
{
//create answerkey array here
char[] answerkey;
//determine number of questions (indices)
answerkey = new char[20];
//input values (correct answers) for each index
//for our purposes today, the answer is always 'c'.
for (int i = 0; i <=20; i++)
{
answerkey[i] = 'c';
}
}
//get student answers (create answers array & export)
public static void getAnswers(answers[i])
{
//initialize scanner for user input
Scanner scan = new Scanner(System.in);
//create answer array here
char[] answers;
//determine number of questions (indices)
answers = new char[20];
//prompt for user input as values of each index
for (int i = 0; i <= 20; i++) {
answers[i] = scan.nextChar();
}
}
//grade student answers (import & compare index values of arrays:answers&answerkey
//create & export qMissed array
public static boolean passed(answerkey[i], answers[i], qMissed[i], points)
{
int points = 0;
//create new array: qMissed
boolean[] qMissed;
//determine number of questions to be graded
qMissed = new boolean[20];
//initialize values for array
for (int i = 0; i <= 20; i++) {
qMissed[i] = false;
}
//cycle through indices of answerkey[i] & answers[i];
for (int i = 0; i =< 20; i++)
{
if (answers[i] == answerkey[i])
{
correct = true;
points = points+1;
qMissed[i] = true;
}
else {
qMissed[i] = false;
}
}
//evaluate whether or not the student passed (15+ correct answers)
if (points >= 15)
{
passed = true;
}
else
{
passed = false;
}
return passed;
}
public static void totalIncorrect(points)
{
int missed = 20 - points;
System.out.println("You missed " + missed + " questions.");
}
public static void questionsMissed(qMissed[i])
{
// for each index of the array qMissed...
for (int i = 0; i < qMissed.length; i++)
{
//...print correct and false answers.
system.out.println(i + ": " + qMissed[i] + "\n");
}
}
}
You can't define array size in the method signature, in Java.
public static void getAnswerkey(answerkey[i])
You can't put anything inside the [] in a method declaration. Also, you have to mention the type:
public static void getAnswerKey(char[] answerkey)
This is not the only reason your code won't work as intended, but I'll leave the rest as part of the exercise.
Look at your method definitions:
public static void questionsMissed(qMissed[i])
This is wrong. You should define the type of the variable and it should not contain [i] like an element of an array. It should be something like this:
public static void questionsMissed(int qMissed)
Or if you want to pass the array, write it like this:
public static void questionsMissed(int[] qMissed)
Apart of this, there are other several errors in your code:
getAnswerkey(answerkey[i]); //answerkey is not defined
getAnswers(answers[i]); //answers is not defined
It would be better if you start reading a Java tutorial first.
I want to vote up Luiggi's answer, but I don't have enough reputation to do that :)
Congrats, cordivia, on getting started with Java!
Here is how an array is declared:
type[] arrayName = new type[numberOfElements]
For example, you did this right in your method definition for getAnswerkey():
char[] answerkey;
answerkey = new char[20];
The part in the method definition inside the parentheses defines the kind of data the method is willing to accept from the outside. So if you don't need to put something into the method to get something out of it, you don't need to put anything in the parentheses. Define the method like this:
getAnswerkey() {
...But that's not the whole story. If you want to get something out of the method, it needs to have a return type as well. A return type is what you're gonna get out of the method when the method's done doing it's magic. For example, if you want to get an int array out of a method you would do something like this:
public static int getTheInteger() {
Since you want an array of chars from the method, you'll want to do something like this:
public static char[] getAnswerkey() {
So that's how you get a method to give you something back. If don't want anything back, you put void:
public static void noMarshmallows() {
Now, when you use the method, you're gonna need to do something with what it gives you, or it did all that work for nothing. So you need to store the return value in a variable when you call the array (calling methods is what you've been doing in main). You know how to store something in a variable. You use the '=' operator:
int myVeryFavoriteNumber;
myVeryFavoriteNumber = 5;
So, you do the same thing when you're getting something out of an array. You assign the return value to a variable. If you want to do this with an array, do this:
int[] myFavs;
myFavs = getMyFavoriteNumbers();
Same with chars:
char[] answerKey;
answerKey = getAnswerKey();
Voila! Your answer key is now right out in the open for the rest of main to see :)
Now, if you want to put something into a method and have it do something with what you put in, you define a parameter. You know how this works. It's just like declaring a variable, and that's exactly what it is. Parameters go in the parentheses and only the method using the parameter sees that variable name (it's local). Something like this:
public static void plusOneToAll (int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] + 1;
}
}
Notice int[] numbers in the parentheses. The type being passed in is int[] or integer array. numbers is just the parameter name. It functions just like a variable, but it is declared locally (inside the parentheses) and use locally (inside the method). So, if you wanted to compare the answers from two arrays and return the number of matches (like a total score for instance), you would do something like this:
public static int getTotalScore (char[] correctAnswers, char[] userAnswers) {
int totalScore = 0;
for (int i = 0; i < correctAnswers.length; i++) {
if (userAnswers[i] == correctAnswers[i]) {
totalScore = totalScore + 1;
}
}
return totalScore;
}
Notice the return type: int (written before the method name). Inside the array I'm using the variable totalScore to keep track of the number of times the answers match. The method takes two char arrays from the outside and uses them on the inside. Finally, I return an int: totalScore. That kicks the value of totalScore back out to whatever called it (main).
If I might add one last thing: Do yourself a favor and go pick up a copy of Head First Java. It's hard to find a good tutorial online and Java textbooks are just plain boring. The Head First series are kind of like coloring books for adults.
Best of luck!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I shall program some methods in Java for the game battleship? Not sure how it's called in English.
We shall create the method:
private static Point[] createSchiff(int laenge)
Which creates a ship with the length laenge, a random position on the field and random direction, and returns a reference of the ship.
The ship shall be from the type Point and we shall use the object Vector as a container for all ships we create.
The full programmcode I have so far is:
import java.awt.*;
import java.awt.Point;
import java.lang.*;
import java.util.*;
public class Programm34 {
public int anzahlschiffe=5;
public Point[] schiffe = new Point[anzahlschiffe];
public static void main(String[]args){
Vector v=new Vector();
int i=10;
double random=0;
System.out.println("Zufallszahlen: ");
for(i=anzahlschiffe;i>0;i--){
random=random(0,10);
System.out.print((int)random+" ");
System.out.println("");
} //Test für random Methode!!
int[][] Spielfeld= new int[10][10];
init(Spielfeld);
for(int x=9;x>=0;x--){
for(int y=9;y>=0;y--){
System.out.print(Spielfeld[x][y]);
if(y!=0){
System.out.print(" ");
}
if(y==0 && x!=0){
System.out.print("\n");
}
}
}
}
private static long random(int u, int o){
double random;
random=Math.random()*(u-o)+o;
return (int)random;
}
private static Point[] createSchiff(int laenge){
point(1,2);
}
private static boolean positionOk(Vector<Point[]> schiffe,Point[] schiff){
}
private static boolean grenze(Point[] schiff){
}
private static boolean konflikt(Vector<Point[]> schiffe,Point[] schiff){
}
private static boolean nachbar(Vector<Point[]> schiffe,Point[] schiff){
}
private static boolean increment(Vector<Point[]> schiffe,int laenge){
}
private static void init(int[][] spielfeld){
for(int i=9;i>=0;i--){
for(int j=9;j>=0;j--){
spielfeld[i][j]=0;
}
}
}
private static void add(int[][] spielfeld, Vector<Point[]> schiffe){
}
}
All those methods and the main shall be programmed, but what matters ist the createschiff ("createship") one.
Can you help me explain the vector? the point? And how the whole stuff works? I sit here now for like 2 hours with no progress... thx alot
First a minor (but helpful) thing: You should add generics parameters to the vector. (I doubt that it is necessary to use Vector. A List should be sufficient. But when it is in the assignment, you have to do it...)
Vector<Point[]> v=new Vector<Point[]>();
About the createSchiff method: You' have to create several Point objects. Namely, one for each field that is covered by the ship. This could roughly look like this:
private static Point[] createSchiff(int laenge)
{
int positionX = ... // Some random position
int positionY = ... // Some random position
// Create the array that will contain the fields
// covered by the ship:
Point result[] = new Point[laenge];
// Fill the array
for (int i=0; i<laenge; i++)
{
result[i] = new Point(positionX, positionY);
// Change the position for the next field,
// depending on the direction of the ship:
positionX += ...
positionY += ...
}
return result;
}
Then you can call this method like this:
Point ship[] = createSchiff(3);
v.add(ship);
(I could insert more real code instead of the placeholders ... , but you should try this on your own)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
'm currently making a purchase program. I'm almost halfway done on it, the only thing i need is. when i Press 1 for purchase it will give me an option to input the Item Code that i stored in my inventory. And then it respectively displays the datas or values corresponds on my inputted code based on my stored products on my inventory.
PS: im new in java and i know my codes are still basic cus im still learning java on my own. And my variables are not yet changed into Arraylist cus i just found out that Arraylist is much better than a plain Array in storing collection of data.
Any suggestions is highly appreciated and welcome. Would stick on using Arraylist or Array. not Hashset or etc.. Thank you Guys!
Hope you guys could help me. Thanks!
class Item {
public final int sku;
public final String desc;
public final type other_fields;
public Item(int s, String d, type fields...) {
// set fields
}
}
or if you really want to be clever
abstract class Item {
public final int sku
// ....
}
class PinkCurtains extends Item {
public PinkCurtains() {
sku = 129534;
desc = "Adorable Pink Indoor Curtains";
}
}
class FuzzyTowel extends Item {
public FuzzyTowel() {
sku = 874164;
desc = "Machine Washable Fuzzy Towel";
}
}
then populate your list and search away
ArrayList<Item> catalog = new ArrayList<Item>(0);
for (int i = 0; i < numItems; i++) {
catalog.add(new Item(arg, arg, arg...));
}
// or
catalog.add(new PinkCurtains());
catalog.add(new FuzzyTowel());
for (Item item : catalog) {
if (chosenItem == item.sku) {
// do all your stuff
}
}
They are called Iterables for a reason. You don't have to make classes if you don't want to. ArrayList also has searching methods, contains() and indexOf() for example:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
If you want to fill in the fields as you go you can make a class that lets you do that:
class Item {
public int id;
public float price;
}
ArrayList<Item> cart = new ArrayList<Item>(0);
do {
Item item = new Item();
item.id = userInput;
item.price = userInput;
cart.add(item);
} while (userInputting);
float total = 0;
for (Item i : cart) {
total += i.price;
}
// using a regular for loop instead of for-each
for (int i = 0; i < cart.size(); i++) {
Item item = cart.get(i);
// or search for something particular
if (item.id == searchID) {
System.out.println("found item " + item.id + " with price $" + item.price);
}
// equivalent to
if (ids[i] == searchID) {
System.out.println("found item " + ids[i] + " with price $" + prices[i]);
}
}
Each time the user wants to add an item, you just make a new one, fill in the fields and add it to the list.