Using array names correctly in for each loop - java

Given the following example code, please help me answer the following questions with hints
public class Coin
{
private String myColor;
private int mySideOne;
private double mySideTwo;
public Coin(String Color, int SideOne, double SideTwo)
{
myColor= Color;
mySideOne = SideOne;
mySideTwo = SideTwo;
}
//accessors getColor(), getSideOne(), and getSideTwo()
}
public class Total
{
private int myNumCoins;
private Coin[] moneyList;
//constructor
public Total(int myCoins)
{
myNumCoins = numCoins;
moneyList = new Coins[numCoins]
String color;
int mySideOne;
double mySideTwo;
for (int i = 0; i<numCoins; i++)
{
}
}
**
Question:
**
//Returns total amount for Coins
public double totalMoney()
{
double total = 0.0;
/* code to calculate
return total;
}
}
Which represents correct / code to calculate amount */ in the totalMoney method?
A. for (Coin t: moneyList)
total+= moneyList.getSideTwo();
B. for (Coin t: moneyList)
total+=t.getSideTwo();
I think A is right because the "t" in B. doesn't exist in the code. How am I wrong?

Let's evaluate the code using A.:
public double totalPaid()
{
double total = 0.0;
for (Ticket t:tickList)
total+= tickList.getPrice();
return total;
}
tickList is an array of Tickets. An array is an object which only has a static final field called length. So, tickList cannot have getPrice. This means, option A doesn't compile.
Let's evaluate the code using B.:
public double totalPaid()
{
double total = 0.0;
for (Ticket t:tickList)
total+=t.getPrice();
return total;
}
Here you state:
I think A is right because the "t" in B. doesn't exist in the code. How am I wrong?
In fact, t is a variable declared and used in the enhanced for loop statement. t is from type Ticket and it will take the value of each Ticket object reference stored in tickList. The enhanced for loop can be translated to this form for arrays:
for (int i = 0; i < tickList.length; i++) {
Ticket t = tickList[i];
//use t in this scope
//in this case, it's used to accumulate the value of total
total += t.getPrice();
}
Which makes B as the solution for this problem.

The answer is B because you declare t in your loop when you say Ticket t. The loop iterates the ticketList and t will stand for each Ticket in the list.

Related

why is my accumulator not incrementing and always returuns zero?

I have just started to learn java so my question might be funny to most of you,
i am trying to write a program that calculate an average for an array of courses
and for some reason my accumulator is not incrementing
public void setStudents() {
accumulator=0;
for(int x=0;x<course.length;x++)
{
accumulator =accumulator+ course[x].result;
}
}
public double getAverage () {
average=(double)(accumulator/course.length);
return average;
}
public int getTotal() {
return accumulator;
}
I'm assuming this is wrapped in a class with a member field variable called accumulator. In this case, when the class is constructed, the setStudents method should be called, so that the accumulator is properly set. If you don't call the setStudents method in the constructor, or anywhere before you call the getAverage method, the accumulator field will just be set to its default value, which is 0. This is probably the reason why you are getting 0 as the result. This can be fixed by calling setStudents in the constructor of this class, or anywhere before you call the getAverage method. Also, in the getAverage method, you should be casting to double before doing the arithmetic, or else the integer division still gets called and then gets cast to a double afterward. So the line
average=(double)(accumulator/course.length);
should be
average=(double)(accumulator)/course.length;
class Mine {
int accumulator;
double average;
Course[] course = {Course.builder().result(10).build(), Course.builder().result(20).build(), Course.builder().result(30).build()};
public static void main(String[] args) {
Mine obj=new Mine();
obj.setStudents();
double avg = obj.getAverage();
System.out.println(avg);
}
public void setStudents() {
Course[] course = {Course.builder().result(10).build(), Course.builder().result(20).build(), Course.builder().result(30).build()};
for (int x = 0; x < course.length; x++) {
accumulator = accumulator + course[x].result;
}
}
public double getAverage() {
average = (double) (accumulator / course.length);
return average;
}
public int getTotal() {
return accumulator;
}
}
#Builder
#Data
class Course {
int result;
}
If you see above code, i had just modified your existing code.
You made some minor mistake with getting and assigning local variables.
Just go through with this link, which will guide you about scope,global variable, local variables

Return the result of each iteration in the loop

I'm doing something that produces the right result. However, it is wrong from a design POV.
The point of the program is to list the result of all the powers of a number up to and including the user-defined limit.
I have a constructor which accepts the base and the exponent from the Scanner. Then a method, which utilises a for loop to calculate the power for each exponent.
Now, the problem is that I'm printing the result from each loop iteration directly from this method. This beats the point of private variables and it being void in the 1st place.
Therefore, I want to define a getter method which returns the result of each power to the output. I used to set them just fine for if/switch statements, but I don't know how to do the same for loops. If I assign the result to a variable within the loop and return that variable from the getter then it will return only the output from the final iteration.
Private implementation
package Chapter6Review;
public class Powers {
private int target;
private int power;
public Powers(int target, int power) {
this.target = target;
this.power = power;
}
public void calculatePower() {
for (int i = 0; i <= power; i++) {
System.out.println((int) Math.pow(target, i));
}
}
/*
public int getPower() {
return
}
*/
}
User interface
package Chapter6Review;
import java.util.Scanner;
public class PowersTester {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter your base: ");
int target = in.nextInt();
System.out.print("Enter your exponent: ");
int power = in.nextInt();
Powers tester = new Powers(target, power);
tester.calculatePower();
}
}
You can simply use a List ;
public List<Integer> calculatePower() {
int p;
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i <= power; i++) {
p = (int) Math.pow(target, i);
result.add(p);
}
return result;
}
Then in you main method, you can iterate the list to print the powers like that :
List<Integer> result = new ArrayList<Integer>();
Powers tester = new Powers(target, power);
result = tester.calculatePower();
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i));
}
You could store each of the results in a List:
List<Power> list = new ArrayList<>();
and when you call it add it as well
list.add(new Powers(target, power));
At the end you can iterate over the list like this:
for (Power power : list){
// your code
}
You might consider using streams as well
public List<Integer> calculatePower() {
return IntStream
.rangeClosed(0, power). // iterate from 0 till power inclusive
.mapToObj(i -> (int) Math.pow(target,i))
.collect(Collectors.toList()); // get result as list
}
Thanks for all the answers. Using a list seems to be a good choice.
Since I haven't covered lists yet, I resorted to this solution for now. But I don't like having code that can affect the solution in the main. Ideally, the loop should go in the private implementation.
Main
Powers tester = new Powers(target, power);
for (int i = 0; i <= power; i++) {
tester.calculatePower(i);
System.out.println(tester.getPower());
}
Private implementation
public void calculatePower(int iPower) {
result = (int) Math.pow(target, iPower);
}
public int getPower() {
return result;
}

How to get my methods to return the value I want?

You can pull the repository of my full code from this link if you want: https://github.com/kenkuts/javaActivity.git
I am using inheritance, polymorphism and interfaces for this practice application. So far I have done the required task the assignment wants me to do. I don't think I did this part right where the assignment wants me to create a GradedActivity array named grades with four elements as a field and store a different class type for each GradedActivity array.
public class CourseGrades implements Analyzable {
private GradedActivity labScore;
private PassFailExam passFailScore;
private Essay essayScore;
private FinalExam finalScore;
**private GradedActivity[] grades = {labScore, passFailScore, essayScore, finalScore};**
public CourseGrades(GradedActivity lab, PassFailExam score, Essay essay, FinalExam finalExam){
setLab(lab);
setPassFailExam(score);
setEssay(essay);
setFinalExam(finalExam);
}
The assignment also wants me to create 3 methods from an interface and write and call it in the main class. I know I messed up in the array part of the problem because my getAverage() method is not working and also my other two getLowest() and getHighest().
public GradedActivity getHighest(){
GradedActivity highest = new GradedActivity();
for(int x = 0; x < grades.length; x++){
if(grades[x].getScore() >= grades[x+1].getScore()){
highest.setScore(grades[x].getScore());
}
else{
highest.setScore(grades[x+1].getScore());
}
}
return new GradedActivity(highest.getScore());
}
public GradedActivity getLowest(){
GradedActivity lowest = new GradedActivity();
for(int x = 0; x < grades.length; x++){
if(grades[x].getScore() <= grades[x+1].getScore()){
lowest.setScore(grades[x].getScore());
}
else{
lowest.setScore(grades[x+1].getScore());
}
}
return new GradedActivity(lowest.getScore());
}
Holy Cow after googling and modifying some things I figured out the problems to my questions. For the GradedActivity array all I had to do was assign each array by each type of class object, which is shown:
public class CourseGrades implements Analyzable {
private GradedActivity[] grades = new GradedActivity[4];
public CourseGrades(GradedActivity lab, PassFailExam score, Essay essay, FinalExam finalExam){
setLab(lab);
setPassFailExam(score);
setEssay(essay);
setFinalExam(finalExam);
}
public void setLab(GradedActivity g){
this.grades[0] = g;
}
public void setPassFailExam(PassFailExam g){
this.grades[1] = g;
}
public void setEssay(Essay g){
this.grades[2] = g;
}
public void setFinalExam(FinalExam g){
this.grades[3] = g;
}
What I did was instead of setting the GradedActivity arrays value into the object type I had different object references that were given their own object type. Thus:
private GradedActivity labScore;
private PassFailExam passFailScore;
private Essay essayScore;
private FinalExam finalScore;
After fixing this issue my getAverage() method started working.
public double getAverage(){
double average;
double accum = 0;
for(int x = 0; x < grades.length; x++){
accum += grades[x].getScore();
}
average = accum/grades.length;
return average;
}
Next was to fix my getLowest() and getHighest() methods. My first mistake was that I had an array that went out of bounds which is grades[x+1].getScore();. After fixing this I decided that the only way to pass the get lowest and highest grades was to declare an empty GradedActivity object then call the methods then after return the methods with class reference and put a .getScore() method in a System.out.println(); hence from the main method:
System.out.println("The average score is " + grade.getAverage());
GradedActivity lowest = grade.getLowest();
System.out.println("The lowest score is " + lowest.getScore());
GradedActivity highest = grade.getHighest();
System.out.println("The highest score is " + highest.getScore());
Damn thank you all for bearing with me.

Method which takes two ArrayLists as parameters

I'm completing an exercise which asks me to write a method called totalTax, which takes as parameters two ArrayLists, one containing houses, the other containing shops, and returns the total tax payable on all those properties. Shop, and House are two classes in my program. Each has a method which returns tax as an integer.
My solution is as follows, but I'm not sure it's the most efficient way of doing it, due to the repetition, and it doesn't compile! Is there a way to achieve the same thing, but avoid duplicate code such as I have below?
private int totalTax(ArrayList<Shop> list1, ArrayList<House> list2) {
int total;
for (int a =0; a <= list1.size() -1; a++) {
total += list1.shopTax();
}
for (int a = 0; a<= list2.size() -1; a++) {
total += list2.houseTax();
}
return total;
}
Your solution won't work since you have to access to the elements in the List, you're retrieving the tax from the list directly, as shown here:
total += list1.shopTax();
It should be
total += list1.get(a).shopTax();
Similar here:
total += list2.houseTax();
It should be:
total += list2.get(a).houseTax();
Still, this approach is using your ArrayList as a wrapper for an array. Another alternative could be treating the ArrayList as a List, so you will use Iterator rather than accessing the elements through get method. There are two ways to use Iterator:
Declaring the Iterator and initializing it with List#iterator:
Iterator<Shop> shopIterator = list1.iterator();
while (shopIterator.hasNext()) {
Shop shop = shopIterator.next();
total += shop.shopTax();
}
Iterator<House> houseIterator = list2.iterator();
while (houseIterator.hasNext()) {
House house = houseIterator.next();
total += house.shopTax();
}
Using enhanced for loop:
for (Shop shop : list1) {
total += shop.shopTax();
}
for (House house : list2) {
total += house.houseTax();
}
In terms of DRY code, you can do better if you alter your class hierarchy such that House and Shop both implement a shared interface. Consider the following:
public interface Taxable{
public int getTax();
}
public class House implements Taxable{
//Other code you've written for House
public int getTax(){
return houseTax();
}
}
public class Shop implements Taxable{
//Other code you've written for Shop
public int getTax(){
return shopTax();
}
}
From there you can take in a single ArrayList of Taxables (containing both houses and shops) and total their taxes without repeating yourself.
private int totalTax(ArrayList<? extends Taxable> lst) {
int total;
for (Taxable t : lst) {
total += t.getTax();
}
return total;
}
If you absolutely must take two ArrayLists as parameters, you can still not repeat yourself creating this method, relying on the above method as its helper.
private int totalTax(ArrayList<House> list1, ArrayList<Shop> list2){
return totalTax(list1) + totalTax(list2)
}
To answer the specific problems with the code not compiling
See comments below:
class Shop {
int tax;
int shopTax() { return tax; }
}
class House {
int tax;
int houseTax() { return tax; }
}
private int totalTax(ArrayList<Shop> list1, ArrayList<House> list2) {
// Need to initialize total to 0
int total = 0;
for (int a =0; a <= list1.size() -1; a++) {
// Need to get the element from the list first
Shop shop = list1.get(a);
total += shop.shopTax();
}
for (int a = 0; a<= list2.size() -1; a++) {
// Need to get the element from the list first
House house = list2.get(a);
total += house.houseTax();
}
return total;
}
To answer "Is there a way to achieve the same thing, but avoid duplicate code such as I have below?"
interface Taxable {
double getTax();
}
class Shop implements Taxable {
public double getTax() {
return 0d;
}
}
class House implements Taxable {
public double getTax() {
return 0d;
}
}
public double totalTax(List<Taxable> thingsToTax) {
double total = 0;
for (Taxable taxable : thingsToTax) {
total += taxable.getTax();
}
return total;
}
Updated
I missed the part where 'the method must take two parameters'. So adding this part:
public double totalTax(List<Taxable> thingsToTax, List<Taxable> otherThingsToTax) {
return totalTax(thingsToTax) + totalTax(otherThingsToTax);
}
This also uses double instead of int which I have to imagine is more appropriate. Otherwise, feel free to use int if still desired.
Something like this is little bit efficient :
private int totalTax(ArrayList<Shop> list1, ArrayList<House> list2) {
int total = 0;
int miSize = Math.min(list1.size(), list2.size());
for (int a = 0; a < minSize; a++)
total += list1.get(a).shopTax() + list2.get(a).houseTax();
if(list1.size() > minSize)
for (int a = minSize; a < list1.size(); a++)
total += list1.get(a).shopTax();
else
for (int a = minSize; a < list2.size(); a++)
total += list2.get(a).shopTax();
return total;
}

Online grading says my output values are not correct but I don't see why?

I am doing some homework for my java programming class, but this code is giving me trouble. The online program that grades it says there is a problem with my output, but I really don't see why. Can anyone help?
The assignment:
Write a class named Car that has the following fields:
yearModel: The yearModel field is an int that holds the car's year model.
make: The make field is a String object that holds the make of the car.
speed: The speed field is an int that holds the car's current speed.
In addition, the class should have the following methods :
Constructor : The constructor should accept the car's year model and make as arguments .
These values should be assigned to the object 's yearModel and make fields. The
constructor should also assign 0 to the speed field.
Accessor: The appropriate accessor methods should be implemented to access the values
stored in the object 's yearModel, make, and speed fields.
accelerate: The accelerate method should add 5 to the speed field when it is called.
brake: The brake method should subtract 5 from the speed field each time it is called.
Demonstrate the class in a program that contains a Car object , and then calls the
accelerate method five times. After each call to the accelerate method , get the current
speed of the car and print it on a separate line. Then, call the brake method five times,
each time printing the current speed of the car on a separate line.
My code:
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int model, String m) {
yearModel = model;
make = m;
speed = 0;
}
public int getYearModel() {
return yearModel;
}
public String getMake() {
return make;
}
public int getSpeed() {
return speed;
}
public int accelerate() {
speed += 5;
return speed;
}
public int brake(int b) {
b -= 5;
return b;
}
}
class CarDemo {
public static void main(String[] args) {
Car c = new Car(1992, "Mustang");
int s = 0;
s = c.getSpeed();
for(int i = 0; i < 5; i++) {
System.out.println("The " + c.getYearModel() + " " + c.getMake() + "is going: " + s);
s = c.accelerate();
System.out.println("Now the " + c.getYearModel() + " " + c.getMake() + "is going: " + s);
}
}
}
Edit:
Based on the suggestions below, I have edited my code to the following; however, the system still says that my output is incorrect.
public class Car{
private int yearModel;
private String make;
private int speed;
public Car(int y, String m){
yearModel = y;
make = m;
speed = 0;
}
public int getYearModel(){
return yearModel;
}
public String getMake(){
return make;
}
public int getSpeed(){
return speed;
}
public void accelerate(){
speed += 5;
}
public void brake(){
speed -= 5;
}
}
class CarDemo{
public static void main(String[] args){
Car theCar = new Car(2010, "Porsch");
for(int i = 0; i < 5; i++){
theCar.accelerate();
System.out.println(theCar.getSpeed());
}
for(int count = 0; count < 5; count++){
theCar.brake();
System.out.println(theCar.getSpeed());
}
}
}
for brake you need to do speed -= 5, not b -= 5. Also I do not think the brake method needs an input argument.
In addition you accelerate 5 times but never brake
Your main issue is the brake method. The requirements state that it should subtract 5 from the current speed. So, you should make it like your accelerate method, but subtracting 5 instead of adding. It shouldn't take in a parameter.
Also, I don't know if this would cause an issue, but your accelerate and brake methods shouldn't return the speed, according to the requirements. Change their return types to void, and remove the return statements.
Lastly, You test main doesn't do exactly what the requirements say to do. Read it carefully to see what it should do, and do EXACTLY what it says.
Follow the specification.
The spec says:
accelerate: The accelerate method should add 5 to the speed field when it is called.
brake: The brake method should subtract 5 from the speed field each time it is called.
These 2 methods have no return type and take no arguments.
So, they should be:
public void accelerate() {
speed += 5;
}
// brake should not take an argument
public void brake() {
// this should be speed, not b
speed -= 5;
}
Additionally, your demo should follow the spec (in comments):
class CarDemo {
public static void main(String[] args) {
//Demonstrate the class in a program that contains a Car object
Car c = new Car(1992, "Mustang");
for (int i = 0; i < 5; i++) {
//and then calls the accelerate method five times.
c.accelerate();
//After each call to the accelerate method, get the current speed of the car and print it on a separate line.
System.out.println(c.getSpeed());
}
for (int i = 0; i < 5; i++) {
//Then, call the brake method five times,
c.brake();
//each time printing the current speed of the car on a separate line.
System.out.println(c.getSpeed());
}
}
}
When working off of a well-written, explicit specification as has been provided for your assignment, it can be very helpful to do what I've done above--include the spec as comments and fill in the code around them.
You're printing The " + c.getYearModel() + " " + c.getMake() + "is going: " + s 5 times. You should put that outside the loop so it's printed once only.
IMHO I don't think you need to be returning the speed from the accelerate() function either. I'd suggest making that a void function and using the getSpeed() method instead of assigning to an intermediate variable.
I am currently taking the Prog Fund I & II class. If you are using Pearson, then this should help. I had the answer correct the first time. You just have to format it correctly in the proper order as so.
import java.util.Scanner;
public class Car
{
private int yearModel; // Holds the car's year model
private String make; // Holds the make of the car
private int speed; // Holds the car's current speed
public static void main(String[] args)
{
// Creates car object
Car vehicle = new Car(2018, "Barbie Mobile");
// Creates object for user input
Scanner keyboard = new Scanner(System.in);
// Holds the speed of the car
int speed = 0;
// Calls accelerate 5 times
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
// Calls break 5 times
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
}
public Car(int year, String maker)
{
// Assigns values to car's year model and make
yearModel = year;
make = maker;
// Assigns 0 to the speed field
speed = 0;
}
/* #return gets year model */
public int getYearModel()
{
return yearModel;
}
/* #return The speed */
public int getSpeed()
{
return speed;
}
/* #return Gets the making of car */
public String getMake()
{
return make;
}
/* Adds 5 to speed when called */
public void accelerate()
{
speed += 5;
}
/* Subtracts 5 from speed when called */
public void brake()
{
speed -= 5;
}
}
I am taking the same class right now, using Pearson Revel. If anyone else comes across this problem, this should help.. Spoiler alert, I will be posting the answer to the problem below
Pearson Revel is such a pain in the butt, they do a horrible job describing how they want the programs structured and output displayed, and if anything is off by even one space or something similar, you lose all points. That being said, the problem demonstrates the calling of the program under "Sample Run" as java Car. So it sounds like the main program that creates a Car object and calls all of it's methods is within the same class (test it out in a text editor, you'll see that if you create a seperate class under the Car class and call Car.java from the command line, it will throw an error; stating the class Car does not have a main. So therefore, it's safe to say you need to create the main method inside of the Car class (wish they would just say that, right?).
Here is my graded & passing answer.
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int year, String make) {
this.yearModel = year;
this.make = make;
this.speed = 0;
}
public void brake() {
this.speed -= 5;
}
public void accelerate() {
this.speed += 5;
}
public int getSpeed() {
return this.speed;
}
public String getMake() {
return this.make;
}
public int getYearModel() {
return this.yearModel;
}
public static void main(String[] args) {
Car myCar = new Car(2019, "Tacoma");
for (int i=0;i < 5;i++) {
myCar.accelerate();
System.out.println(myCar.getSpeed());
}
for (int i=0;i < 5;i++) {
myCar.brake();
System.out.println(myCar.getSpeed());
}
}
}
And here is Revel's suggested answer after completion
public class Car {
public static void main(String[] args) {
Car batmobile = new Car(1965, "Bat Mobile");
for(int i=0; i<5; i++){
batmobile.accelerate();
System.out.println(batmobile.getSpeed());
}
for(int i=0; i<5; i++){
batmobile.brake();
System.out.println(batmobile.getSpeed());
}
}
private int yearModel;
private String make;
private int speed;
public Car(int yearModel, String make){
this.yearModel = yearModel;
this.make = make;
this.speed = 0;
}
public int getYearModel(){
return this.yearModel;
}
public String getMake(){
return this.make;
}
public int getSpeed(){
return this.speed;
}
public void accelerate(){
this.speed += 5;
}
public void brake(){
this.speed -= 5;
}
}

Categories