Parameters cannot be resolved as a variable? - java

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

Related

How to compare Strings ignoring cases in Java

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))

Cartrader program. 1 Junit error left but I don´t understand

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));

Difficulty on check the data when it pass to a array from text file in Java

I am creating three classes,
First, ExchangeRate class for storing the data from the text file.
code public class ExchangeRate {
private String Local;
private String Foreign;
private double Rate;
public ExchangeRate(String Px, String Py, double ER) {
Local = Px;
Foreign = Py;
Rate = ER;
}
public void setLocal(String L) {
Local = L;
}
public void setForeign(String F) {
Foreign = F;
}
public void setRate(double R) {
Rate = R;
}
public String getLocal() {
return Local;
}
public String getForeign() {
return Foreign;
}
public double getRate() {
return Rate;
}
}
Then, I creat the CurrencyExchange class for converting the exchange rate which get from the constructor.
enter code here public class CurrencyExchange {
public int ratesize = 0;
public ExchangeRate[] allrecord = new ExchangeRate[42];
private String name1;
private String name2;
private double num;
private double num2;
public void convert(String currencyCode1, String currencyCode2,
double amount, boolean printFlag) {
name1 = currencyCode1;
name2 = currencyCode2;
num = amount; //change getLocal() to static?
if (name1 == ExchangeRate.getLocal()
&& name2 == ExchangeRate.getForeign()) {
num2 = num * ExchangeRate.getRate();
}
if (printFlag == true) {
printInfo();
}
}
public void addExchangeRate(ExchangeRate exRate) {
allrecord[ratesize] = exRate;
setratesize();
}
public void setratesize() {
ratesize++;
}
public String getname1() {
return name1;
}
public String getname2() {
return name2;
}
public double getnum() {
return num;
}
public void printInfo() {
System.out.println("Direct Conversion: Converted " + name1 + " " + num
+ " to " + name2 + " "+num2);
}
}
But I have diffculty on how to check if the currenncy can convert accroding to the name of the country indicate on the texting class, such as 'eur' and 'jpy. means convert EUR to JPT according to the exchange rate on the text.file. If I change that checking part
"If(name1==ExchangeRate.getLocal()" to static, Local will become the last data from the text.It cannot be checked. Therefore, I want to know How can I solve the problem?
Testing class
enter code here import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MP2_Task1 {
public static void main(String[] args) {
CurrencyExchange currencyExchange = new CurrencyExchange();
String fileName = "exchange_rate.txt";
Scanner in = null;
try { // start reading data file
in = new Scanner(new File(fileName));
while (in.hasNextLine()) {
String line = in.nextLine();
String token[] = line.split(",");
if (token.length == 3) {
// create ExchangeRate instance for storing the exchange
// rate record
ExchangeRate exRate = new ExchangeRate(token[0], token[1],
Double.parseDouble(token[2]));
// adding the new exchange rate record to the
// CurrencyExchange instance
currencyExchange.addExchangeRate(exRate);
}
}
} catch (FileNotFoundException e) {
System.out.println(fileName + " cannot be found!");
} finally {
if (in != null) {
in.close();
}
}
String hkd = "HKD";
String usd = "USD";
String jpy = "JPY";
String gbp = "GBP";
String cny = "CNY";
String eur = "EUR";
String chf = "CHF";
// Task 1 - Simple money conversions
double oriAmount1 = 1000;
currencyExchange.convert(hkd, gbp, oriAmount1, true);
double oriAmount2 = 55;
currencyExchange.convert(cny, usd, oriAmount2, true);
double oriAmount3 = 300;
currencyExchange.convert(eur, jpy, oriAmount3, true);
double oriAmount4 = 8000;
currencyExchange.convert(hkd, chf, oriAmount4, true);
System.out.println();
}
}
Expected Output:
Direct Conversion: Converted HKD 1000.0 to GBP 83.8
Direct Conversion: Converted CNY 55.0 to USD 8.6735
Direct Conversion: Converted EUR 300.0 to JPY 39739.23
Direct Conversion: Converted HKD 8000.0 to CHF 1026.4
The whole text.file about exchange rate
HKD,USD,1.290000e-01
HKD,JPY,1.569860e+01
HKD,GBP,8.380000e-02
HKD,CNY,8.178000e-01
HKD,EUR,1.185000e-01
HKD,CHF,1.283000e-01
USD,HKD,7.750800e+00
USD,JPY,1.216885e+02
USD,GBP,6.499000e-01
USD,CNY,6.342400e+00
USD,EUR,9.187000e-01
USD,CHF,9.951000e-01
JPY,HKD,6.370000e-02
JPY,USD,8.200000e-03
JPY,GBP,5.300000e-03
JPY,CNY,5.210000e-02
JPY,EUR,7.500000e-03
JPY,CHF,8.200000e-03
GBP,HKD,1.192560e+01
GBP,USD,1.538600e+00
GBP,JPY,1.872341e+02
GBP,CNY,9.758600e+00
GBP,EUR,1.413500e+00
GBP,CHF,1.531000e+00
CNY,HKD,1.222100e+00
CNY,USD,1.577000e-01
CNY,JPY,1.918650e+01
CNY,GBP,1.025000e-01
CNY,EUR,1.448000e-01
CNY,CHF,1.569000e-01
EUR,HKD,8.437100e+00
EUR,USD,1.088600e+00
EUR,JPY,1.324641e+02
EUR,GBP,7.075000e-01
EUR,CNY,6.904000e+00
EUR,CHF,1.083100e+00
CHF,HKD,7.789700e+00
CHF,USD,1.005000e+00
CHF,JPY,1.222988e+02
CHF,GBP,6.532000e-01
CHF,CNY,6.374200e+00
CHF,EUR,9.233000e-01
if (name1.equals(ExchangeRate.getLocal())
&& name2.equals(ExchangeRate.getForeign())) {
num2 = num * ExchangeRate.getRate();
}
with == you compare the object references and not the values.

Struggling with objects, program does not work as expected(java)

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())

Scanner Input not Reading Method Calling as a Parameter

First of All here's the Codes:
Product Information:
public class ProductInformation
{
public String code;
public String itemName;
public double price;
//Constructor
public ProductInformation()
{ itemName="-";
code="-";
price=0;}
//Setter
public void setItemName(String itemName)
{ this.itemName=itemName;}
public void setCode(String code)
{ this.code=code;}
public void setPrice(double price)
{ this.price=price;}
//Getter
public String getItemName()
{ return itemName;}
public double getPrice()
{ return price;}
public String getCode()
{ return code;}
//Products
public void getProduct(String code)
{ if(code == "A001"){
setCode("A001");
setItemName("Mouse ");
setPrice(100);}
else if(code == "A002"){
setCode("A002");
setItemName("Monitor ");
setPrice(2500);}
else if(code == "A003"){
setCode("A003");
setItemName("Keyboard");
setPrice(200);}
else if(code == "A004"){
setCode("A004");
setItemName("Flash Disk");
setPrice(300);}
else if(code == "A005"){
setCode("A005");
setItemName("Hard Disk");
setPrice(1500);}
}
}
import java.util.*;
Product Display:
public class ProductDisplay
{ public ProductInformation product;
public ProductDisplay()
{
System.out.println("\t\t\t\t RG COMPUTER SHOP");
System.out.println("\t\t\t\t Makati City");
System.out.println("\t\tP R O D U C T\tI N F O R M A T I O N");
System.out.println("-------------------------------------------------------");
System.out.println("\t\tCode\t\tDescription\t\tUnit Price");
System.out.println("-------------------------------------------------------");
product = new ProductInformation();
product.getProduct("A001");
display();
product = new ProductInformation();
product.getProduct("A002");
display();
product = new ProductInformation();
product.getProduct("A003");
display();
product = new ProductInformation();
product.getProduct("A004");
display();
product = new ProductInformation();
product.getProduct("A005");
display();
}
// Display Method
public void display()
{ System.out.println("\t\t" + product.getCode()
+ "\t\t" + product.getItemName()
+ "\t\t" + product.getPrice()); }
}
My Problem is here in PointOfSale
I tried to let the buyer decide by entering a Product Code
after entering the getProduct I get is always "A005" Even if I enter "A001" or something else. I think the product.getProduct(code) is not working out. Can someone help me fix this problem so i can continue scripting this
import java.util.*;
public class PointOfSale extends ProductDisplay
{
public PointOfSale()
{ System.out.print("\nPurchase Item(y/n)?");
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
if("y".equalsIgnoreCase(line)){
OpenOrder();
}
}
//=============================================
public void OpenOrder() // New Order
{ ArrayList<String> ProductList = new ArrayList<String>();
ProductList.add("A001"); ProductList.add("A002");
ProductList.add("A003"); ProductList.add("A004");
ProductList.add("A005");
System.out.print("Select Product Code:");
Scanner sc = new Scanner(System.in);
String code = sc.next();
if(ProductList.contains(code))
{ product.getProduct(code);
display(); EnterQuantity(); }
else System.out.print("Product Code is Invalid\n"); System.exit(0);}
//==============================================
public void EnterQuantity() //Entering Quantity
{
try{
System.out.print("Enter Quantity:");
Scanner sc = new Scanner(System.in);
int quantity = sc.nextInt();
double amount = quantity * product.getPrice();
System.out.print("Amount: " + amount);}
catch (InputMismatchException nfe)
{System.out.print("\nInvalid Entry: Input must be a Number.\n"); System.exit(0);}
}
// Main Method
public static void main(String[] args)
{ new PointOfSale(); }
}
You are comparing strings for equality in your getProduct() method. Strings are objects, so you probably want to use the equals() method:
public void getProduct(String code)
{ if(code.equals("A001")){
setCode("A001");
setItemName("Mouse ");
setPrice(100);}
else if(code.equals("A002")){
setCode("A002");
setItemName("Monitor ");
setPrice(2500);}
else if(code.equals("A003")){
setCode("A003");
setItemName("Keyboard");
setPrice(200);}
else if(code.equals("A004")){
setCode("A004");
setItemName("Flash Disk");
setPrice(300);}
else if(code.equals("A005")){
setCode("A005");
setItemName("Hard Disk");
setPrice(1500);}
}
One major problem is that you're comparing Strings using == and you in general shouldn't do that as this compares if one object reference is the same as another and you don't care about this. Instead you care if the two String variables hold the same String representation, and for this use the equals() or equalsIgnoreCase() methods.

Categories