How to compare Strings ignoring cases in Java - 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))

Related

Why is method printing when there is no code to print

Attempting to get this output at the 2nd last part:
/*****test finalistsToFile2 with sorted arraylist*****/
/**************check file testSorted.txt**************/
/****************************************************/
However, my actual output is:
/****************************************************/
/*****test finalistsToFile2 with sorted arraylist*****/
/**************check file testSorted.txt**************/
**ID: 85011, Final Mark: 69.2, Classification: UPPER_SECOND
Candidate is BORDERLINE
ID: 62138, Final Mark: 59.9, Classification: LOWER_SECOND
Candidate is BORDERLINE**
/****************************************************/
I've attempted debugging but still cannot find the root cause of the extra 4 lines of printing under 'check file testSorted.txt' (in bold). Any idea what I can do? I have a total of 3 classes used as shown below:
ProcessDegreeMark class
import java.util.*;
import java.io.*;
public class ProcessDegreeMark{
private ProcessDegreeMark() {}
public static ArrayList<Finalist> finalistsInList(String s) throws Exception{
ArrayList<Finalist> finalists = new ArrayList<Finalist>();
String id;
double mark;
Scanner in = null;
try
{
in = new Scanner(new FileReader(s));
try
{
while(in.hasNextLine())
{
id =in.nextLine();
mark = Double.parseDouble(in.nextLine());
finalists.add(new Finalist(id,mark));
}
}
finally
{
in.close();
}
}
catch(IOException e)
{
System.out.println(s+" not found");
}
return finalists;
}
public static void displayFinalists(ArrayList<Finalist> finalists){
for (int i = 0; i < finalists.size(); i++)
{
System.out.println(finalists.get(i));
}
}
public static void findFinalistID(ArrayList<Finalist> a, String s){
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getId().equals(s))
{
System.out.println(a.get(i));
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with ID number "+s);
}
}
public static void findFinalistClass(ArrayList<Finalist> a, String s){
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getdegreeClass().equals(s))
{
System.out.println(a.get(i));
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with degree class "+s);
}
}
public static ArrayList<Finalist> sortDegreeMark(ArrayList<Finalist> a){
ArrayList<Finalist> sortedFinalists = new ArrayList<Finalist>();
sortedFinalists.addAll(a);
Collections.sort(sortedFinalists, new FinalistComparator());
return sortedFinalists;
}
public static void finalistsToFile2(ArrayList<Finalist> finalists, String s) {
try
{
PrintStream out = new PrintStream(new FileOutputStream(s));
try
{
for(int i = 0; i < finalists.size(); i++)
{
out.println(finalists.get(i));
}
}
finally
{
out.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static void findAndSaveFinalistClass(ArrayList<Finalist> a, String s){
ArrayList<Finalist> searchFinalists = new ArrayList<Finalist>();
int count =0;
for (int i=1;i<a.size();i++)
{
if (((a.get(i))).getdegreeClass().equals(s))
{
System.out.println(a.get(i));
searchFinalists.add(a.get(i));
finalistsToFile2(searchFinalists,"testSorted.txt");
count++;
}
}
if(count==0)
{
System.out.println("No candidate found with degree class "+s);
}
}
public static void main(String[] args) throws Exception{
System.out.println("/****************************************************/");
System.out.println("/*******finalistsInList with invalid file name*******/");
System.out.println();
ArrayList<Finalist> testList = finalistsInList("file***.txt");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/********finalistsInList with valid file name********/");
System.out.println("/********display to check arraylist populated********/");
System.out.println();
ArrayList<Finalist> finalists = finalistsInList("finalMark.txt");
displayFinalists(finalists);
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*testing findFinalistID with valid and invalid data*/");
System.out.println();
findFinalistID(finalists, "75021");
findFinalistID(finalists, "21050");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*test findFinalistClass with valid and invalid data*/");
System.out.println();
findFinalistClass(finalists, "FIRST");
findFinalistClass(finalists, "THIRD");
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*****run sortedFinalists then test with display*****/");
System.out.println();
ArrayList<Finalist> sortedFinalists = sortDegreeMark(finalists);
displayFinalists(sortedFinalists);
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*****test finalistsToFile2 with sorted arraylist*****/");
System.out.println("/**************check file testSorted.txt**************/");
System.out.println();
finalistsToFile2(sortedFinalists, "testSorted.txt"); //save the sorted arraylist to a new file, check by opening file
System.out.println();
System.out.println("/****************************************************/");
System.out.println("/*test findAndSaveFinalistClass with valid and invalid data*/");
System.out.println();
findAndSaveFinalistClass(finalists, "FIRST"); //test method finds
findAndSaveFinalistClass(finalists, "THRID"); //check appropriate error message when nothing found, open new text file
System.out.println();
System.out.println("/*********************THE END************************/");
}
}
Finalist class
public class Finalist{
private String id;
private double degreeMark;
private String degreeClass;
private boolean borderline;
public Finalist(String id, double degreeMark) {
this.id = id;
this.degreeMark = degreeMark;
borderline = calcBorderline();
degreeClass = assignDegreeClass();
}
private String assignDegreeClass(){//change method name
if (degreeMark<40) return "FAIL";
if (degreeMark<50) return "THIRD";
if (degreeMark<60) return "LOWER_SECOND";
if (degreeMark<70) return "UPPER_SECOND";
return "FIRST";
}
private boolean calcBorderline(){
double x;
if (degreeMark<40){
x = 40.0-degreeMark;
if (x < 1.0) return true;
}
if (degreeMark<50){
x = 50.0-degreeMark;
if (x < 1.0) return true;
}
if (degreeMark<60){
x = 60.0-degreeMark;
if (x < 1.0) return true;
}
if (degreeMark<70){
x = 70.0-degreeMark;
if (x < 1.0) return true;
}
return false;
}
public String getId(){
return id;
}
public double getDegreeMark(){
return degreeMark;
}
public String getdegreeClass(){
return degreeClass;
}
public boolean getborderline(){
return borderline;
}
public String toString() {
String s = "ID: " + id + ", Final Mark: " + degreeMark + ", Classification: " + degreeClass + System.lineSeparator();
if(calcBorderline()==true)
{
System.out.print(s);
System.out.println("Candidate is BORDERLINE");
}
else if(calcBorderline()==false)
{
return s;
}
return "";
}
}
FinalistComparator class
import java.util.Comparator;
//sort by degree mark, descending
class FinalistComparator implements Comparator<Finalist> {
#Override
public int compare(Finalist f1, Finalist f2) {
int degreeComparisonResult = Double.compare(f2.getDegreeMark(),f1.getDegreeMark());
return degreeComparisonResult;
}
}
The unexpected output is performed in Finalist.toString() because of out.println(finalists.get(i));. Since PrintStream.println(Object x) calls toString() of the provided Object.
Update: since you stated that you need the second line: Candidate is BORDERLINE just add it to the return value and don't directly print it on System.out else you will get unexpected outputs.
#Override
public String toString() {
String s = "ID: " + id + ", Final Mark: " + degreeMark + ", Classification: " + degreeClass + System.lineSeparator();
if(calcBorderline()) {
s += "Candidate is BORDERLINE" + System.lineSeparator();
}
return s;
}
Original answer:
So avoid the use of System.out.println() in toString(), i would recommand to keep it as simple as possible and put logic in another method.
For example:
public class Finalist{
/* all the other code */
#Override
public String toString() {
return "ID: " + id + ", Final Mark: " + degreeMark + ", Classification: " + degreeClass;
}
}
public class ProcessDegreeMark {
/** Writes all non BORDERLINE candidates in the file and outputs the skipped finalists to System.out */
public static void saveToFileWithoutBorderline(List<Finalist> list, File file) {
try (PrintStream out = new PrintStream(new FileOutputStream(file))){
for(Finalist finalist : list) {
if(finalist.calcBorderline()) {
System.out.println("Skip BORDERLINE candidate: "+finalist.toString());
} else {
out.println(finalist.toString());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I only provided a sample code to skip the borderline candidates in saveToFile, since I didn't know where you have to skip or suppress them.

Simple Stack Calculator can't give proper fractional answers

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

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

Parameters cannot be resolved as a variable?

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

Categories