Eclipse shows the error "The primitive type byte of Vehicle does not have a field PASSENGER_CAR" in my "Vehicle class". What does it mean? It´s the only error left in the JUnit test we have to use in class. When i write "7" or "5" which are the constants for the types it seems to work, but I´m not allowed to do that. Here is the full program:
public class Vehicle {
public static final float TANK_SIZE_PASSENGER_CAR = 40.f;
public static final float TANK_SIZE_TRUCK = 80.f;
private float fuel;
private float VehicleType;
public Vehicle(){
}
public Vehicle(byte VehicleType){
this();
if (VehicleType == VehicleType.PASSENGER_CAR){
this.VehicleType= VehicleType.PASSENGER_CAR ;
this.fuel= Vehicle.TANK_SIZE_PASSENGER_CAR;
}
if(VehicleType == VehicleType.TRUCK){
this.VehicleType= VehicleType.TRUCK;
this.fuel= Vehicle.TANK_SIZE_TRUCK;
}
public float getFuel(){
return fuel;
}
public byte getVehicleType(){
return VehicleType;
}
}
}
public final class VehicleType {
public static final byte PASSENGER_CAR = 7;
public static final byte TRUCK = 5;
/**
* This class is just an organizer for the above constants; Not instantiable.
*/
private VehicleType(){
}
}
public class CarTrader {
public static final float CAPACITY_DIESEL_LITERS = 250.f;
public static final float CAPACITY_GAS_LITERS = 180.f;
public static final int CAPACITY_PASSENGER_CARS = 15;
public static final int CAPACITY_TRUCKS = 5;
float gasStockLiters=180.f;
float dieselStockLiters=250.f;
int passengerCarsStock=15;
int trucksStock=5;
void setGasStockLiters(float gasStockLiters){
this.gasStockLiters=gasStockLiters;
}
void setDieselStockLiters(float dieselStockLiters){
this.dieselStockLiters=dieselStockLiters;
}
void setPassengerCarsStock(int passengerCarsStock){
this.passengerCarsStock=passengerCarsStock;
}
void setTrucksStock(int trucksStock){
this.trucksStock=trucksStock;
}
int getPassengerCarsStock(){
return passengerCarsStock;
}
int getTrucksStock(){
return trucksStock;
}
float getGasStockLiters(){
return gasStockLiters;
}
float getDieselStockLiters(){
return dieselStockLiters;
}
public Vehicle sellVehicle(byte vehicleType){
Vehicle soldVehicle=null;
switch (vehicleType){
case 0: //VehicleType.TRUCK:
if(this.dieselStockLiters>=Vehicle.TANK_SIZE_TRUCK && this.trucksStock>=1){
trucksStock = trucksStock - 1;
dieselStockLiters = dieselStockLiters - Vehicle.TANK_SIZE_PASSENGER_CAR;
soldVehicle = new Vehicle(VehicleType.TRUCK);
System.out.println("LKW erfolgreich verkauft");
}
else{
soldVehicle=null;
}
break;
case 1://VehicleType.PASSENGER_CAR:
if(gasStockLiters>=Vehicle.TANK_SIZE_PASSENGER_CAR && this.passengerCarsStock>=1){
passengerCarsStock = passengerCarsStock - 1;
gasStockLiters = gasStockLiters - Vehicle.TANK_SIZE_PASSENGER_CAR;
soldVehicle = new Vehicle(VehicleType.PASSENGER_CAR);
System.out.println("PKW erfolgreich verkauft");
}
else{
soldVehicle=null;
}
break;
default:
break;
}
return soldVehicle;
}
public Vehicle[] sellVehicles(byte vehicleType, int amount){
Vehicle[] soldVehicles = new Vehicle[amount];
float currentAmount=40*amount;
float currentAmount2=80*amount;
switch (vehicleType){
case 0://VehicleType.TRUCK:
if(this.dieselStockLiters>=currentAmount2 && this.trucksStock>=amount){
trucksStock = trucksStock - amount;
dieselStockLiters = dieselStockLiters - (currentAmount2);
for (int i=0; i<amount; i++){
soldVehicles[i]=new Vehicle(VehicleType.TRUCK);
}
System.out.println("LKW erfolgreich verkauft");
}
else{
soldVehicles=null;
}
break;
case 1://VehicleType.PASSENGER_CAR:
if(this.gasStockLiters>=currentAmount && this.passengerCarsStock>=amount){
passengerCarsStock = passengerCarsStock - amount;
gasStockLiters = gasStockLiters - (currentAmount);
for (int i=0; i<amount; i++){
soldVehicles[i]=new Vehicle(VehicleType.PASSENGER_CAR);
}
System.out.println("PKW erfolgreich verkauft");
}
else{
soldVehicles=null;
}
break;
default:
soldVehicles=null;
break;
}
return soldVehicles;
}
public boolean fillGas(float gas){
boolean filled=false;
if((gasStockLiters + gas)<=CarTrader.CAPACITY_GAS_LITERS){
gasStockLiters = gasStockLiters + gas;
filled=true;
}
else{
System.err.println("Die Kapazität beträgt höchstens 180 Liter");
}
return filled;
}
public boolean fillDiesel(float diesel){
boolean filled2=false;
if((dieselStockLiters + diesel)<=CarTrader.CAPACITY_DIESEL_LITERS){
dieselStockLiters = dieselStockLiters + diesel;
filled2=true;
}
else{
System.err.println("Die Kapazität beträgt höchstens 250 Liter");
}
return filled2;
}
public boolean reorderVehicles(byte vehicle, int amountVehicles){
boolean full=false;
if (vehicle==1){
if ((trucksStock + amountVehicles)<=CarTrader.CAPACITY_TRUCKS){
trucksStock = trucksStock + amountVehicles;
full=true;
}
}
if (vehicle==0){
if ((passengerCarsStock + amountVehicles)<=CarTrader.CAPACITY_PASSENGER_CARS){
passengerCarsStock = passengerCarsStock + amountVehicles;
full=true;
}
}
else {
System.out.println("Bitte 5 oder 7 wählen");
}
return full;
}
void statusOutput()
{
System.out.println("AutoHändler - Lagerbestand:");
System.out.println(" PKW: " + passengerCarsStock);
System.out.println(" - Benzin: " + gasStockLiters);
System.out.println(" LKW: " + trucksStock);
System.out.println(" - Diesel: " + dieselStockLiters);
}
}
You have a class named VehicleType, a float named VehicleType, and pass in a byte named VehicleType into the function. Change your Vehicle initualizer to public Vehicle(byte vehicleType), and the error should go away, stop naming everything VehicleType.
public class Vehicle {
public static final float TANK_SIZE_PASSENGER_CAR = 40.f;
public static final float TANK_SIZE_TRUCK = 80.f;
private float fuel;
private float mVehicleType;
public Vehicle(){}
public Vehicle(byte vehicleType){
this();
if (vehicleType == VehicleType.PASSENGER_CAR){
this.mVehicleType= VehicleType.PASSENGER_CAR ;
this.fuel= Vehicle.TANK_SIZE_PASSENGER_CAR;
}
if(vehicleType == VehicleType.TRUCK){
this.mVehicleType= VehicleType.TRUCK;
this.fuel= Vehicle.TANK_SIZE_TRUCK;
}
}
public float getFuel(){
return this.fuel;
}
public byte getVehicleType(){
return this.mVehicleType;
}
}
#popdemic It´s a error in this section in the 4th line (assertEquals(40.f....)
private void testSoldCarAttributes(byte vehicleType, final Vehicle v) {
switch (vehicleType) {
case VehicleType.PASSENGER_CAR:
assertEquals(40.f, v.getFuel(), DELTA_FLOAT);
assertEquals(VehicleType.PASSENGER_CAR, v.getVehicleType());
break;
case VehicleType.TRUCK:
assertEquals(80.f, v.getFuel(), DELTA_FLOAT);
assertEquals(VehicleType.TRUCK, v.getVehicleType());
}
and here in the second line testSoldCarAttributes(VehicleType.PASSENGER_CAR.....
public void testSoldCarAttributes() {
testSoldCarAttributes(VehicleType.PASSENGER_CAR, trader.sellVehicle(VehicleType.PASSENGER_CAR));
testSoldCarAttributes(VehicleType.TRUCK, trader.sellVehicle(VehicleType.TRUCK));
Related
Newbie here I am trying to compare the brand and display to an array of Strings. Seems to be working now but I don't know how to make the comparison case-insensitive. All the options I found so far is to compare a string to another string. There is any way I can make that comparison? Right now only accept the values as stated in the array of strings.
P.S. This was an existing homework that our instructor wanted us to build on it, hence why I am using the "isValid" methods for validation.
Thanks!
import com.entertainment.Television;
import java.util.Arrays;
import java.util.Scanner;
class TelevisionConsoleClient {
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
welcomeMessage();
}
public static void welcomeMessage() {
//Welcome message to buyer
System.out.println("Welcome to Our Online Ordering System.");
System.out.println("Please answer the questions below to submit your order.");
String brand = brandChoice();
String display = displayChoice();
int size = sizeChoice();
System.out.println("Thank you. The television you ordered is: ");
television(brand, display, size);
//close scanner
scanner.close();
}
public static String brandChoice() {
String brandChoice = null;
boolean hasBrand = false;
while (!hasBrand) {
System.out.println("Please enter the desired brand " + Arrays.toString(Television.VALID_BRANDS) + ":");
brandChoice = scanner.nextLine();
if (Television.isValidBrand(brandChoice))
hasBrand = true;
else
System.out.println("Sorry " + brandChoice + " is not a valid brand");
}
return brandChoice;
}
private static String displayChoice() {
String displayChoice = null;
boolean hasDisplay = false;
while (!hasDisplay) {
System.out.println("Please enter the desired display type " + Arrays.toString(Television.VALID_DISPLAY) + ":");
displayChoice = scanner.nextLine();
if (Television.isValidDisplay(displayChoice))
hasDisplay = true;
else
System.out.println("Sorry " + displayChoice + " is not a valid display type");
}
return displayChoice;
}
private static int sizeChoice() {
Integer sizeChoice = null;
boolean hasSize = false;
while (!hasSize) {
System.out.println("Please enter the desired size " + Arrays.toString(Television.VALID_SIZES) + ":");
sizeChoice = Integer.parseInt(scanner.nextLine());
if (Television.isValidSize(sizeChoice))
hasSize = true;
else
System.out.println("Sorry " + sizeChoice + " is not a valid size");
}
return sizeChoice;
}
private static void television(String brand, String display, int size) {
System.out.println(new Television(brand, display, size));
}
}
package com.entertainment;
public class Television {
// CLASS OR STATIC VARIABLES - STORED IN THE SHARED AREA ASSOCIATED WITH A CLASS
public static final String[] VALID_BRANDS = {"Samsung", "LG", "Sony", "Toshiba"};
public static final String[] VALID_DISPLAY = {"LED", "OLED", "PLASMA", "LCD", "CRT"};
public static final int[] VALID_SIZES = {32, 40, 43, 50, 55, 60, 65, 70, 75, 80};
// FIELDS - AKA 'INSTANCE VARIABLES', 'ATTRIBUTES', 'PROPERTIES'
private String brand;
private String display;
private int size;
// CONSTRUCTORS
// No-arg constructor.
public Television() {
// possible additional "setup" or initialization code here
// want it to run for every instance created
}
// 3-arg constructor
public Television(String brand, String display, int size) {
this.brand = brand;
this.display = display;
this.size = size;
}
// ACCESSOR METHODS (getters/setters)
public String getBrand() {
return brand;
}
public String getDisplay() {
return display;
}
public int getSize() { return size; }
public static boolean isValidBrand(String brand) {
boolean isValid = false;
for (String currentBrand : VALID_BRANDS) {
if (currentBrand.equals(brand)) {
isValid = true;
break;
}
}
return isValid;
}
public static boolean isValidDisplay(String display) {
boolean isValid = false;
for (String currentDisplay : VALID_DISPLAY) {
if (currentDisplay.equals(display)) {
isValid = true;
break;
}
}
return isValid;
}
public static boolean isValidSize(int size) {
boolean isValid = false;
for (int currentSize : VALID_SIZES) {
if (currentSize == size) {
isValid = true;
break;
}
}
return isValid;
}
public String toString() {
return "Television: " + getBrand() + ", Display: " + getDisplay() + ", Size: " + getSize() + " inches.";
}
}
Change String.equals(Object) to String.equalsIgnoreCase(String). That is,
if (currentBrand.equals(brand))
if (currentDisplay.equals(display))
to
if (currentBrand.equalsIgnoreCase(brand))
if (currentDisplay.equalsIgnoreCase(display))
I am trying to set period number 1 of every Monday of every CourseGroup to true but the object changes all the days instead of only Mondays.Kindly checkout the example below
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
class HelloWorld {
public static void main(String[] args) {
SchoolObject schoolObject;
List<LecturePeriod> lecturePeriods = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
String periodName = "Period " + i;
int periodNo = i;
boolean isPeriodAllocated = false;
lecturePeriods.add(new LecturePeriod(periodName, periodNo, isPeriodAllocated));
}
List<Day> days = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
String dayName;
switch (i) {
case 1:
dayName = "MONDAY";
break;
case 2:
dayName = "TUESDAY";
break;
case 3:
dayName = "WEDNESDAY";
break;
case 4:
dayName = "THURSDAY";
break;
case 5:
dayName = "FRIDAY";
break;
default:
dayName = "NONE";
}
int dayNo = i;
days.add(new Day(dayName, dayNo, lecturePeriods));
}
List<YearGroup> yearGroups = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
int yearGroupNumber = i;
if (Objects.equals(i, 1)) {
yearGroups.add(new YearGroup(yearGroupNumber, new ArrayList<>(Arrays.asList(new CourseGroup("Science" + 1, days)))));
} else if (Objects.equals(i, 2)) {
yearGroups.add(new YearGroup(yearGroupNumber, new ArrayList<>(Arrays.asList(new CourseGroup("Science" + 2, days)))));
} else if (Objects.equals(i, 3)) {
yearGroups.add(new YearGroup(yearGroupNumber, new ArrayList<>(Arrays.asList(new CourseGroup("Science" + 3, days)))));
}
}
schoolObject = new SchoolObject();
schoolObject.setYearGroups(yearGroups);
System.out.println("School Object Before Changing Periods="+schoolObject.toString());
schoolObject.getYearGroups().forEach(yearGroup -> {
yearGroup.getCourseGroups().forEach(courseGroup -> {
courseGroup.getDays().forEach(day -> {
String dayName = day.getDayName();
if (Objects.equals(dayName, "MONDAY")) {
day.getLecturePeriods().forEach(lecturePeriod -> {
int lecturePeriodNumber = lecturePeriod.getPeriodNumber();
if (Objects.equals(lecturePeriodNumber, 1)) {
lecturePeriod.setIsPeriodAllocated(true);
}
});
}
});
});
});
System.out.println("\nSchool Object After Changing Periods=" + schoolObject.toString());
final int[] numberOfAllocatedPeriodsExpected = {0};
schoolObject.getYearGroups().forEach(yearGroup -> {
yearGroup.getCourseGroups().forEach(courseGroup -> {
courseGroup.getDays().forEach(day -> {
day.getLecturePeriods().forEach(lecturePeriod -> {
int lecturePeriodNumber = lecturePeriod.getPeriodNumber();
if (Objects.equals(lecturePeriodNumber, 1)) {
numberOfAllocatedPeriodsExpected[0]++;
}
});
});
});
});
System.out.println("\nTest result ="+Objects.equals(numberOfAllocatedPeriodsExpected[0],3));
}
public static class SchoolObject {
List<YearGroup> yearGroups;
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("SchoolObject{");
sb.append("yearGroups=").append(yearGroups);
sb.append('}');
return sb.toString();
}
public List<YearGroup> getYearGroups() {
return yearGroups;
}
public void setYearGroups(List<YearGroup> yearGroups) {
this.yearGroups = yearGroups;
}
}
public static class YearGroup {
int yearGroupNumber;
List<CourseGroup> courseGroups;
public YearGroup(int yearGroupNumber, List<CourseGroup> courseGroups) {
this.yearGroupNumber = yearGroupNumber;
this.courseGroups = courseGroups;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("YearGroup{");
sb.append("yearGroupNumber=").append(yearGroupNumber);
sb.append(", courseGroups=").append(courseGroups);
sb.append('}');
return sb.toString();
}
public int getYearGroupNumber() {
return yearGroupNumber;
}
public void setYearGroupNumber(int yearGroupNumber) {
this.yearGroupNumber = yearGroupNumber;
}
public List<CourseGroup> getCourseGroups() {
return courseGroups;
}
public void setCourseGroups(List<CourseGroup> courseGroups) {
this.courseGroups = courseGroups;
}
}
public static class CourseGroup {
String courseGroupName;
List<Day> days;
public CourseGroup(String courseGroupName, List<Day> days) {
this.courseGroupName = courseGroupName;
this.days = days;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("CourseGroup{");
sb.append("courseGroupName='").append(courseGroupName).append('\'');
sb.append(", days=").append(days);
sb.append('}');
return sb.toString();
}
public List<Day> getDays() {
return days;
}
public void setDays(List<Day> days) {
this.days = days;
}
public String getCourseGroupName() {
return courseGroupName;
}
public void setCourseGroupName(String courseGroupName) {
this.courseGroupName = courseGroupName;
}
}
public static class Day {
String dayName;
int dayNo;
List<LecturePeriod> lecturePeriods;
public Day(String dayName, int dayNo, List<LecturePeriod> lecturePeriods) {
this.dayName = dayName;
this.lecturePeriods = lecturePeriods;
this.dayNo = dayNo;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Day{");
sb.append("dayName='").append(dayName).append('\'');
sb.append(", dayNo=").append(dayNo);
sb.append(", lecturePeriods=").append(lecturePeriods);
sb.append('}');
return sb.toString();
}
public String getDayName() {
return dayName;
}
public void setDayName(String dayName) {
this.dayName = dayName;
}
public int getDayNo() {
return dayNo;
}
public void setDayNo(int dayNo) {
this.dayNo = dayNo;
}
public List<LecturePeriod> getLecturePeriods() {
return lecturePeriods;
}
public void setLecturePeriods(List<LecturePeriod> lecturePeriods) {
this.lecturePeriods = lecturePeriods;
}
}
public static class LecturePeriod {
String periodName;
int periodNumber;
boolean isPeriodAllocated;
public LecturePeriod(String periodName, int periodNumber, boolean isPeriodAllocated) {
this.periodName = periodName;
this.periodNumber = periodNumber;
this.isPeriodAllocated = isPeriodAllocated;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("LecturePeriod{");
sb.append("periodName='").append(periodName).append('\'');
sb.append(", periodNumber=").append(periodNumber);
sb.append(", isPeriodAllocated=").append(isPeriodAllocated);
sb.append('}');
return sb.toString();
}
public String getPeriodName() {
return periodName;
}
public void setPeriodName(String periodName) {
this.periodName = periodName;
}
public int getPeriodNumber() {
return periodNumber;
}
public void setPeriodNumber(int periodNumber) {
this.periodNumber = periodNumber;
}
public boolean isPeriodAllocated() {
return isPeriodAllocated;
}
public void setIsPeriodAllocated(boolean isPeriodAllocated) {
this.isPeriodAllocated = isPeriodAllocated;
}
}
}
Observing the output of the data,you notice that the schoolObject set all lecturePeriods to true for all days in each courseGroup instead of only Mondays.
Any help will be much appreciated.
Note:I tried my best to extract the problem to the barest minimum without using gson or jackson which would have allowed a cleaner output when combing through the json generated.
For testing sake,I cramped everything into one class.
You can check the sample here http://ideone.com/3uyE5G
This is because you are assigning the same reference of lecture periods for all days:
days.add(new Day(dayName, dayNo, lecturePeriods));
Because of this, everytime you change a property in the lecturePeriods object in one of the days it will change for all of them. To solve this issue, each day has to have it's own instance of lecturePeriods
List<LecturePeriod> lecturePeriods = new ArrayList<>();
for (int j = 1; j <= 10; j++) {
lecturePeriods.add(new LecturePeriod("Period " + j, j, false));
}
days.add(new Day(dayName, dayNo, lecturePeriods));
#valarauko,what you showed me was perfectly true,each day had to have it's own instance of lecturePeriods,but a more scalable solution I found was that,since the object could have been initialized in a different number of ways,what I did was
1.Convert the Object into a json String .
2.Convert it back to the original Object before any manipulation.
I used gson for the above two steps and it works perfectly,regardless of how I initialized each day in the schoolObject.
So thanks once again for showing me the root cause #valarauko.
Im trying to fix my code which is a simple calculator in Java made using stacks and a token class. I am having an error every time I have a decimal number as an answer. For example, if I input 11/2 it will give me 1. Its an odd error and I don't know how to fix it and was wondering if someone could tell me how. Thank you for any help!
public class SimpleCalcSkeleton {
private enum TokenType {WS,LP,RP,NUM,OP};
private static class Token {
// instance variables
private String value;
private TokenType type;
// constructor
public Token(String v, TokenType t) {
this.value = v;
this.type = t;
}
// toString() is important for diagnostic output
public String toString() {
return ("[" + value + ";" + type.toString() + "]");
}
// getter or accessor methods for the instance vars or properties
// setter methods are not needed
public String getValue() {
return value;
}
public TokenType getType() {
return type;
}
}
private static TokenType getTokenType(char c) {
TokenType type=null;
if(c==' '){
type=TokenType.WS;
}
if(c=='('){
type=TokenType.LP;
}
if(c==')'){
type=TokenType.RP;
}
if((c=='+')||(c=='-')||(c=='*')||(c=='/')){
type=TokenType.OP;
}
if((c=='0')||(c=='1')||(c=='2')||(c=='3')||(c=='4')||(c=='5')||(c=='6')||(c=='7')||(c=='8')||(c=='9')){
type=TokenType.NUM;
}
return type;
}
private static int getAssoc(Token token) {
String word = token.getValue();
int number =0;
if((word.equals('+'))||(word.equals('-'))){
number=1;
}
if((word.equals('*'))||(word.equals('/'))){
number=2;
}
return number;
}
private static ArrayList<Token> parse(String s) {
if(s==null||s.length()==0){
return null;
}
ArrayList<Token> list= new ArrayList<Token>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
TokenType type = getTokenType(c);
String symbol= Character.toString(c);
if(type==null){
System.out.print("Error: null");
}
else if(!type.equals(TokenType.WS)){
list.add(new Token(symbol,type));
}
}
return list;
}
private static ArrayList<Token> infixToPostfix(ArrayList<Token> intokens) {
Stack astack = new Stack();
ArrayList<Token>outokens=new ArrayList<Token>();
for(int i=0;i<intokens.size();i++){
Token in= intokens.get(i);
if(in.getType()==TokenType.NUM){
outokens.add(in);
}
if(in.getType()==TokenType.LP){
astack.push(in);
}
if(in.getType()==TokenType.RP){
Token top=(Token)astack.peek();
while(top.getType()!=TokenType.LP){
astack.pop();
outokens.add(top);
top=(Token)astack.peek();
if(top.getType()==TokenType.LP){
astack.pop();
break;
}}}
if(in.getType()==TokenType.OP){
if(!astack.isEmpty()){
Token top = (Token)astack.peek();
while((top.getType()==TokenType.OP)&&(getAssoc(top)>=getAssoc(in))){
astack.pop();
outokens.add(top);
if(!astack.isEmpty())
top=(Token)astack.peek();
else break;
}}
astack.push(in);
}
}
while(!astack.isEmpty()){
Token top=(Token)astack.peek();
astack.pop();
outokens.add(top);
if(!astack.isEmpty())
top=(Token)astack.peek();
else break;
}
return outokens;
}
private static Token evalOp(Token op, Token t1, Token t2) {
String one = t1.getValue();
String two = t2.getValue();
String opener = op.getValue();
int output =0;
int first = Integer.parseInt(one);
int second = Integer.parseInt(two);
if(opener.equals("+")){
output = second+first;
}
if(opener.equals("-")){
output = second-first;
}
if(opener.equals("*")){
output = second*first;
}
if(opener.equals("/")){
output = second/first;
}
String last = Integer.toString(output);
Token total = new Token(last,TokenType.NUM);
return total;
}
private static String evalPostfix(ArrayList<Token> intokens) {
Stack right = new Stack();
for(int i=0;i<intokens.size();i++){
Token in=intokens.get(i);
if(in.getType()==TokenType.NUM)
right.push(in);
else if(in.getType()==TokenType.OP){
Token at = (Token) right.pop();
Token bat = (Token) right.pop();
Token cat = evalOp(in,at,bat);
right.push(cat);
}
}
return right.toString();
}
public static String evalExpression(String s) {
ArrayList<Token> infixtokens = parse(s);
System.out.println("\tinfix tokens: " + infixtokens);
ArrayList<Token> postfixtokens = infixToPostfix(infixtokens);
System.out.println("\tpostfix tokens: " + postfixtokens);
return evalPostfix(postfixtokens);
}
public static void commandLine() {
Scanner in = new Scanner(System.in);
while (true){
System.out.print("> ");
String word = in.nextLine();
if (word.equals("quit")) {
break;
}
else {
System.out.println(evalExpression(word));
}
}
}
}
class SimpleCalcTest {
public static void test() {
String[] inputs = {
"3*4 + 5",
"3 + 4*5",
"(1+1)*(5-2)",
"(3*4+5)*(3*3 + 4*4)"
};
for (int i=0; i<inputs.length; i++) {
String s = inputs[i];
System.out.println();
System.out.println();
System.out.println("test: input = " + s);
String r = SimpleCalcSkeleton.evalExpression(s);
System.out.println("\tresult = " + r);
}
}
public static void main(String[] args) {
SimpleCalcSkeleton.commandLine();
SimpleCalcTest.test();
}
}
So I have this cyclingmanager game, and I want to show a list of riders by names, and then I want to show their abilities when the user picks a rider. The program compiles and runs nicely, the problem is in my riders() method.It just does not print out c1, my first rider. Thanks in advance.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CyclingManager2 {
public static void main(String[] args) {
//menyvalgene
Menu m = new Menu();
m.choice();
}
}
class Menu {
Scanner in = new Scanner(System.in);
Cyclist cy = new Cyclist();
//choices
public void choice() {
int choice = -1;
while (choice != 0) {
System.out.println("Choose something: ");
System.out.println("-0 will exit the program" + "\n-Pressing 1 will open the database menu");
choice = in.nextInt();
switch(choice) {
case 0: choice = 0; break;
case 1: database(); break;
default: System.out.println("You have to choose either 0 or 1"); break;
}
}
}
public void database() {
System.out.println("Welcome to the database \nThese are the options:\n0 = Back to menu\n1: Riders");
int dbChoice = -1;
while (dbChoice != 0) {
System.out.println();
dbChoice = in.nextInt();
switch(dbChoice) {
case 0: dbChoice = 0; break;
case 1: cy.riders(); System.out.println("Press 0 for going back to the menu\nPress 1 for showing the riders");break;
default: System.out.println("Choose either 0 or 1"); break;
}
}
}
}
class Cyclist {
List<Cyclist> cyclists = new ArrayList<>();
private String name;
private int mountain;
private int timeTrial;
private int sprint;
private int age;
Cyclist c1 = null;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setMountain(int mountain) {
this.mountain = mountain;
}
public int getMountain() {
return mountain;
}
public void setTimeTrial(int timeTrial) {
this.timeTrial = timeTrial;
}
public int getTimeTrial() {
return timeTrial;
}
public void setSprint(int sprint) {
this.sprint = sprint;
}
public int getSprint() {
return sprint;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void riders() {
abilities();
for (int i = 0; i < cyclists.size(); i++){
System.out.print(((Cyclist) cyclists).getName());
}
}
public void abilities() {
//Pardilla is created
c1 = new Cyclist();
c1.setName("Sergio Pardilla");
c1.setMountain(75);
c1.setTimeTrial(60);
c1.setSprint(60);
c1.setAge(30);
/*System.out.println(c1.getName() + "'s abilities:");
System.out.println("Mountain - " + c1.getMountain());
System.out.println("TimeTrial - " + c1.getTimeTrial());
System.out.println("Sprint - " + c1.getSprint());
System.out.println("Age - " +c1.getAge());
cyclists.add(c1); //adds Pardilla to cyclists arraylist*/
}
}
You have this for-loop:
for (int i = 0; i < cyclists.size(); i++) {
System.out.print(((Cyclist) cyclists).getName());
}
It is not going to work. You are casting the entire cyclists (an ArrayList) to one cyclist instance. You probably want to iterate over the contents of the ArrayList and get each Cyclist-object in the cyclists array. Try a foreach-loop:
for (Cyclist cyclist : cyclists) {
System.out.print(cyclist.getName());
}
or use a for loop with index based retrieval:
for (int i = 0; i < cyclists.size(); i++) {
cyclists.get(i).getName());
}
I think you want more something like:
public void riders() {
abilities();
for (int i = 0; i < cyclists.size(); i++){
System.out.print(cyclists.get(i).getName());
}
}
Another thing, is that I'm not sure you want List<Cyclist> cyclists = new ArrayList<>(); to be part of Cyclist class.
Two issues:
The part where you add your rider to the ArrayList is commented out.
The way you loop over your ArrayList is by no means correct. Try like this:
for (Cyclist cyclist : cyclists) {
System.out.println(cyclist.getName());
}
You should get Objects from List by calling it number: cyclists.get(i).getName())
This is a fairly basic program. When I try to print the summaryOutput method and billOutput method, I get errors saying the parameters cannot be resolved as a variable.
public class PizzaDriver{
public static void main(String[] args) {
PizzaOrder order = new PizzaOrder();
PizzaOutput output = new PizzaOutput();
PizzaInput input = new PizzaInput();
System.out.println(output.menuOutput());
input.readInput(order);
System.out.println(summaryOutput1 = output.summaryOutput (numCheese, numPepperoni, numSausage, numVegetarian));
System.out.println(output.billOutput(String billOutput));
}
}
public class PizzaOutput
{
public String menuOutput()
{
String menuOutput1 = "Item \t Price \nCheese \t $2.40 \n Sausage \t $3.00 \nPepperoni \t $3.00 \nVegertarian \t $3.00";
return menuOutput1;
}
public void summaryOutput(int numCheese,int numPepperoni,int numSausage,int numVegetarian)
{
System.out.println("Cheese: " + numCheese);
System.out.println("Pepperoni: " + numPepperoni);
System.out.println("Sausage: " + numSausage);
System.out.println("Vegetarian: " + numVegetarian);
}
public void billOutput(double subTotal, double tax, double carryOut, double totalBill)
{
System.out.println("Subtotal : " +subTotal);
System.out.println("Tax : " + tax);
System.out.println("carryOut : " +carryOut);
System.out.println("Total Bill: " + totalBill);
}
import java.util.Scanner;
public class PizzaInput
{
Scanner keyboard = new Scanner(System.in);
public int numCheese, numPepperoni, numSausage, numVegetarian;
public void readInput(PizzaOrder order)
{
System.out.print("How many Cheese Pizzas would you like?");
int numCheese = keyboard.nextInt();
order.setCheese(numCheese);
System.out.print("How many Pepperoni pizzas would you like?");
int numPepeperoni = keyboard.nextInt();
order.setPepperoni(numPepperoni);
System.out.print("How many Sausage pizzas would you like?");
int numSausage = keyboard.nextInt();
order.setSausage(numSausage);
System.out.print("How many Vegetarian pizzas would you like?");
int numVegetarian = keyboard.nextInt();
order.setVegetarian(numVegetarian);
}
}
public class PizzaOrder
{
private final double CHEESE_PRICE = 2.40;
private final double PEPPERONI_PRICE = 3.00;
private final double SAUSAGE_PRICE = 3.00;
private final double VEGETARIAN_PRICE = 3.50;
private final double SALES_TAX = .025;
private final double CARRY_OUT = .10;
public int numCheese, numPepperoni, numSausage, numVegetarian;
public int getCheese()
{
return numCheese;
}
public void setCheese(int numCheese)
{
this.numCheese=numCheese;
}
public int getPepperoni()
{
return numPepperoni;
}
public void setPepperoni(int numPepperoni)
{
this.numPepperoni=numPepperoni;
}
public int getSausage()
{
return numSausage;
}
public void setSausage(int numSausage)
{
this.numSausage= numSausage;
}
public int getVegetarian()
{
return numVegetarian;
}
public void setVegetarian(int numVegetarian)
{
this.numVegetarian = numVegetarian;
}
public double calculateSubTotal()
{
double cheeseTotal= numCheese * CHEESE_PRICE;
double pepperoniTotal = numPepperoni * PEPPERONI_PRICE;
double sausageTotal = numSausage * SAUSAGE_PRICE;
double vegetarianTotal = numVegetarian * VEGETARIAN_PRICE;
double subTotal = cheeseTotal + pepperoniTotal + sausageTotal + vegetarianTotal;
double tax = (subTotal) * SALES_TAX;
double totalBill = (tax + subTotal) * CARRY_OUT;
return totalBill;
}
}
Remove "String" from the following line as you are calling a method and not defining it. Also, billOutput has been twice. Avoid name collisions.
System.out.println(output.billOutput(String billOutput));
when you say following
output.summaryOutput (numCheese, numPepperoni, numSausage, numVegetarian)
it will try to search the same variable name (numCheese, numPepperoni, numSausage, numVegetarian) in current method/class, which are not defined and hence it is not able to figure it out.
Please define those or else refer it properly
also ther is no definition for summaryOutput1 and as #pooja suggested
System.out.println(output.billOutput(String billOutput));//where is the param billOutput?
should be like
System.out.println(output.billOutput(billOutput));
Go through the following code set and identify the changers that you have to do inside of your application
public class PizzaOutput {
private int numCheese;
private int numPepperoni;
private int numSausage;
private int numVegetarian;
public PizzaOutput(){}
public PizzaOutput(int numSausage, int numCheese, int numPepperoni, int numVegetarian) {
this.numSausage = numSausage;
this.numCheese = numCheese;
this.numPepperoni = numPepperoni;
this.numVegetarian = numVegetarian;
}
public int getNumCheese() {
return numCheese;
}
public void setNumCheese(int numCheese) {
this.numCheese = numCheese;
}
public int getNumPepperoni() {
return numPepperoni;
}
public void setNumPepperoni(int numPepperoni) {
this.numPepperoni = numPepperoni;
}
public int getNumSausage() {
return numSausage;
}
public void setNumSausage(int numSausage) {
this.numSausage = numSausage;
}
public int getNumVegetarian() {
return numVegetarian;
}
public void setNumVegetarian(int numVegetarian) {
this.numVegetarian = numVegetarian;
}
public String summaryOutput(int numSausage, int numCheese, int numPepperoni, int numVegetarian){
setNumSausage(numSausage);
setNumCheese(numCheese);
setNumPepperoni(numPepperoni);
setNumVegetarian(numVegetarian);
return "Sausage : "+ getNumSausage()+ " Cheese : "+getNumCheese()+ " Pepeeroni : "+ getNumPepperoni()+ " Vegetarian : "+getNumVegetarian();
}
public String billOutPut(String bOutput){
// Enter here your code to get the bill
return "Bill Output"; // return the bill as a String
}
}
-> pay attention on the instance variables declaration
-> Your had not declared the return statements inside the both "summaryOutput" and "billOutPut" methods. Therefore you have to declare the return statement as a single statement
-> According to your code structure calling the both methods are enough to get the output and not need to call both methods inside the SOP