Not able to take input in java [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
This is my code, here when i input the Product name i.e. Laptop/Mobile and then input the price. after that the program does not input eask and simply goes to the eask if-else case and prints the Invalid option as:
import java.util.*;
class Main {
public static void main(String[] args) {
int discount=0,ediscount=1;
Scanner sc = new Scanner(System.in);
String Product = sc.nextLine();
int Price = sc.nextInt();
String eask = sc.nextLine();
if(Price>100){
if(eask == "Yes" || eask == "No"){
if(Product == "Mobile"){
discount = 10;
if(eask == "Yes")
ediscount=12;
}
else if(Product == "Laptop"){
discount = 20;
if(eask == "Yes")
ediscount=10;
}
else if(Product == "gadgets"){
discount = 0;
if(eask == "Yes")
ediscount=0;
}
else System.out.println("Invalid product");
}
else
System.out.println("Invalid option");
}
else System.out.println("Invalid price");
float TBA = discount * Price;
System.out.println(TBA);
}
}

Try this:
int discount=0,ediscount=1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter product name : ");
String Product = sc.next();
System.out.print("Enter product price : ");
int Price = sc.nextInt();
System.out.print("Enter eask : ");
String eask = sc.next();
if(Price>100){
if(eask.equals("Yes") || eask.equals("No") ){
switch (Product) {
case "Mobile":
case "mobile":
discount = 10;
if("Yes".equals(eask))
ediscount=12;
break;
case "Laptop":
case "laptop":
discount = 20;
if("Yes".equals(eask))
ediscount=10;
break;
case "Gadgets":
case "gadgets":
discount = 0;
if("Yes".equals(eask))
ediscount=0;
break;
default:
System.out.println("Invalid product");
break;
}
}
else
System.out.println("Invalid option");
}
else System.out.println("Invalid price");
float TBA = discount * Price;
System.out.println("The price is : " + TBA);

Related

Im not sure whats the problem with my code, as it displays invalid when i enter a valid date input

Im using Java and mySql
I have already done my code to prompt user to enter a date in the format DDMMYY and then store the info into the database, however, when i enter a valid date such as 121221, it will say "invalid date, please re-enter" Im not sure whats the problem..
this is my validation class
public class Validation {
public static boolean isValidDate(String date) {
String day = date.substring(0,2);
String month = date.substring(2,4);
String year = date.substring(4,6);
int i = Integer.parseInt(day);
int j = Integer.parseInt(year);
int k = Integer.parseInt(month);
if (k%2 !=0 || k == 8 || k == 10 || k == 12) {
if(i<=0 || i>31) {
return false;
}
}else if (k == 2) {
if(i<=0 || i>28) {
return false;
}
}else if (k%2 == 0 || k == 9 || k == 11) {
if (i<=0 || i>30) {
return false;
}
}
if(j<22 || j>100) {
return false;
}
return true;
}
public boolean isValidTransactionId(int transactionId) {
return true;
}
}
my UI class
package view;
import java.util.*;
import java.text.*;
import controller.DBController;
import controller.Validation;
import model.Transaction;
import model.Member;
public class UserInterface {
DBController db;
Validation vd;
Scanner scan;
Random rand;
String date;
boolean invalid;
int menuChoice, memberChoice;
Transaction transaction;
public UserInterface()throws Exception{
db= new DBController();
scan = new Scanner(System.in);
rand = new Random();
transaction = new Transaction();
}
public void MainMenu()throws Exception {
System.out.println("Welcome to SuperFun Theme Park!");
do {
System.out.print("Main Menu\n");
System.out.println("1. New Ticket Transaction");
System.out.println("2. Modify a Ticket Transaction");
System.out.println("3. Delete a Ticket Transaction");
System.out.println("4. View Ticket Transactions");
System.out.println("5. Exit");
System.out.print("Enter a number (1-5): ");
menuChoice = scan.nextInt();
scan.nextLine();
switch(menuChoice) {
case 1: newTicket(); break;
case 2: modifyTicket(); break;
case 3: deleteTicket(); break;
case 4: viewAllTransactions(); break;
case 5: System.out.println("Thank you. Have a nice day!"); break;
default: System.out.println("Invalid input. Please re-enter.\n");break;
}
}while(menuChoice!=5);
}
public void dateInput()throws Exception{
do {
if(menuChoice ==1 ) {
System.out.print("Enter ticket date (DDMMYY): ");
date = scan.nextLine();
transaction.setDate(date);
}else if (menuChoice == 4) {
System.out.print("Enter start date (DDMMYY): ");
date = scan.nextLine();
transaction.setDate(date);
}
invalid = false;
if(!vd.isValidDate(date)) {
invalid = true;
}else
invalid = false;
}while(invalid);
}
public void displayMemberInfo()throws Exception{
String result[] = null;
System.out.printf("\n%s %17s %20s\n","Index","Name", "Phone Number");
result = db.retrieveMemberInfo();
for(String temp: result)
System.out.println(temp);
}
public void newTicket() throws Exception{
int member=0, numOfMemberTickets=0, transactionId =0;
int memberTicket=80, nonMemberTicket=100, total=0, num=0;
boolean full = false, repeat= false;
//auto generate transaction id //100-200
int upperbound = 200;
int lowerbound = 100;
do {
transactionId = rand.nextInt(upperbound - lowerbound)+ lowerbound;
transaction.setId(transactionId);
}while(db.idExists(transaction.getId()));
//display transaction id
System.out.println("\nTransaction Id: " + transaction.getId());
//prompt user to enter ticket date
//validation for date
do {
dateInput();
db.maximumTicket(transaction.getDate());
if(db.sum>=100) {
System.out.println("Tickets are fully booked for the day. Please re-enter date.\n");
full = true;
}else {
System.out.printf("Number of tickets left for %s are %d\n" , date, 100-db.sum);
full = false;
}
}while(full);
//ask for total number of tickets then ask for members tickets
do {
System.out.print("Enter number of ticket(s) wanted: ");
num = scan.nextInt();
scan.nextLine();
transaction.setTicketNum(num);
if(transaction.getTicketNum() > 100-db.sum)
System.out.println("Number of ticket(s) wanted exceeded availability. Please re-enter. ");
}while(transaction.getTicketNum() > 100-db.sum);
//if member, must choose which member
//loop through member info for validation
do {
repeat=false;
do {
System.out.print("Are there ticket(s) for member(s)? (1-yes 2-no): ");
member = scan.nextInt();
scan.nextLine();
if(member !=1 && member !=2)
System.out.println("Invalid input. Please re-enter.");
}while(member !=1 && member !=2);
if(member==1) {
do {
System.out.print("Enter the number of member tickets: ");
numOfMemberTickets = scan.nextInt();
scan.nextLine();
if(numOfMemberTickets<=0)
System.out.println("Invalid number of tickets. Please re-enter.");
}while(numOfMemberTickets<=0);
//display member info table
displayMemberInfo();
for(int cnt=0; cnt<numOfMemberTickets; cnt++) {
do {
System.out.print("\nPlease enter index number of member: ");
memberChoice = scan.nextInt();
// if(db.memberExists(transaction.getId())) {
// System.out.println("Member are only allowed to purchase one ticket in a day. Please re-enter.");
// repeat = true;
// }else
db.insertNumber(memberChoice, transaction.getId());
}while(memberChoice<=0);
}
}
}while(repeat);
//calculate and display total price
total = (numOfMemberTickets * memberTicket) + (Math.abs((transaction.getTicketNum() - numOfMemberTickets)) * nonMemberTicket);
transaction.setTotal(total);
System.out.println("Total price: RM" + transaction.getTotal());
//save data into database
boolean success = db.insertInfo(transaction.getDate(), transaction.getId(), transaction.getTicketNum(), transaction.getTotal());
if(success)
System.out.println("Transaction record inserted successfully.\n");
else
System.out.println("Error in inserting record.\n");
}
public void modifyTicket() throws Exception{
int transactionId=0, newTicketNum=0, newNumOfMemberTicket=0, newTotal=0, change=0;
String newDate="";
//enter transaction id
do {
System.out.print("Enter transaction id: ");
transactionId = scan.nextInt();
scan.nextLine();
transaction.setId(transactionId);
if(!db.idExists(transaction.getId()))
System.out.println("Transaction id does not exists. Please re-enter.");
}while(!db.idExists(transaction.getId()));
//display details
System.out.printf("\n%-4s %20s %25s %20s\n","Ticket Date", "Transaction Id", "Number of Tickets", "Total Price");
db.displayRecord(transaction.getId());
//user can edit date, number and members' phone number
System.out.print("\nEnter new ticket date: ");
newDate = scan.nextLine();
transaction.setDate(newDate);
System.out.print("Enter new number of tickets(including members' tickets): ");
newTicketNum = scan.nextInt();
scan.nextLine();
transaction.setTicketNum(newTicketNum);
System.out.print("Enter new number of member ticket(s): ");
newNumOfMemberTicket = scan.nextInt();
scan.nextLine();
System.out.print("Is there a change in member(s)? (1-yes 2-no): ");
change = scan.nextInt();
scan.nextLine();
if(change==1) {
displayMemberInfo();
for(int cnt=0; cnt<newNumOfMemberTicket; cnt++) {
do {
System.out.print("\nPlease enter index number of member: ");
memberChoice = scan.nextInt();
db.updateNumber(memberChoice, transactionId);
}while(memberChoice<=0);
}
}
//recalculate total price
newTotal = (newNumOfMemberTicket * 80) + (Math.abs(newTicketNum - newNumOfMemberTicket)* 100);
transaction.setTotal(newTotal);
//update database
boolean success = db.updateInfo(transaction.getDate(), transaction.getTicketNum(), transaction.getTotal(), transaction.getId());
if(success)
System.out.println("Information updated successfully.\n");
else
System.out.println("Error in updating information.\n");
}
public void deleteTicket()throws Exception{
int transactionId=0, choice =0;
//enter transaction id
do {
System.out.print("Enter transaction id: ");
transactionId = scan.nextInt();
scan.nextLine();
if(!db.idExists(transactionId))
System.out.println("Transaction id does not exists. Please re-enter.");
}while(!db.idExists(transactionId));
transaction.setId(transactionId);
//display all information of that transaction
System.out.printf("\n%-4s %20s %25s %20s\n","Ticket Date", "Transaction Id", "Number of Tickets", "Total Price");
db.displayRecord(transactionId);
//re-confirm whether to delete
do {
System.out.print("\nConfirm delete? (1-yes 2-no): ");
choice = scan.nextInt();
}while(choice !=1 && choice !=2);
//delete from database
if(choice == 1) {
boolean success = db.deleteInfo(transaction.getId());
if (success)
System.out.println("Transaction Info deleted successfully.\n");
else
System.out.println("Error in deleting transaction info.\n");
}else
System.out.println("Returning to main menu...\n");
}
public void viewAllTransactions() throws Exception{
String result[] = null;
String date2 ="", letter="";
//enter start date
dateInput();
switch(date.substring(2,4)) {
case "01": letter = "Jan"; break;
case "02": letter = "Feb"; break;
case "03": letter = "Mar"; break;
case "04": letter = "Apr"; break;
case "05": letter = "May"; break;
case "06": letter = "June"; break;
case "07": letter = "July"; break;
case "08": letter = "Aug"; break;
case "09": letter = "Sep"; break;
case "10": letter = "Oct"; break;
case "11": letter = "Nov"; break;
case "12": letter = "Dec"; break;
}
date2 = date.substring(0,2) + letter + "20" + date.substring(4,6);
//show all records from start date
//display error if no matching one
boolean success = db.matchingDate(transaction.getDate());
if(success) {
System.out.println("\nTransaction Report from " + date2);
System.out.printf("%-4s %20s %25s %20s\n","Ticket Date", "Transaction Id", "Number of Tickets", "Total Price");
result = db.retrieveAllInfo(date);
for(String temp: result)
System.out.println(temp);
}else
System.out.println("Error in finding date entered.");
System.out.println("\nReturning to main menu...\n");
}
}
transaction class
public void setDate(String date) {
if(Validation.isValidDate(date))
this.date = date;
else
System.out.println("Date is invalid. Please re-enter.");
}
Honestly, those if checks are kind of hard to look at. Try this:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class dateTime {
public static void main(String[] args) throws ParseException {
SimpleDateFormat datefr = new SimpleDateFormat("dd-MM-yy");
datefr.setTimeZone(TimeZone.getTimeZone("UTC"));
datefr.setLenient(false);
try {
Date date = datefr.parse("12-10-21");
System.out.println(true);
} catch (ParseException e) {
System.out.println(false);
System.out.println(e.getMessage());
}
}
}

Menu keeps repeating in Java

All menu options work besides menu option 1 when i select 1 it just repeats the menu instead of asking me to type the name and repeat it 20 time, if anyone can help me debug I would appreciate it.
Get the user’s first name and echo it back out 20 times.
Get the Store user’s age and double it and display the age and the doubled age.
Using the age from #2 output one of the following statements.Since you are 99 years old, you are a teenagerb. Since you are 99 years old, you are NOT a teenager
Get a single integer between 3 and 50 from the user. Create a triangle of X’s with the integer inputted rows. The triangle needs to be displayed on the screen and in a text document named triangle.txt.
The code :
//Menu.java
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("\n::MENU::");
System.out.println("1.Echo Name");
System.out.println("2.Double Your Age");
System.out.println("3.Check Teenager or not");
System.out.println("4.Display Triangle");
System.out.println("5.Exit");
System.out.print("Enter Choice:");
choice = sc.nextInt();
switch (choice) {
case 1: {
System.out.print("Enter your name");
String name = sc.nextLine();
for (int i = 1; i <= 20; i++) {
System.out.println(name);
}
break;
}
case 2: {
int age;
System.out.print("Enter age :");
age = sc.nextInt();
System.out.println("Your age :" + age);
System.out.println("Doubled age :" + (2 * age));
break;
}
case 3: {
int age;
System.out.print("Enter age :");
age = sc.nextInt();
if (age >= 13 && age <= 19) {
System.out.println("Since you are " + age + " years old.Your are a Teenager");
} else {
System.out.println("Since you are " + age + " years old.Your are not a Teenager");
}
break;
}
case 4: {
int rows;
do {
System.out.print("Enter a number (between 3 and 50):");
rows = sc.nextInt();
if (rows < 3 || rows > 50) {
System.out.println("** Invalid.Must be between 3 and 50 **");
}
} while (rows < 3 || rows > 50);
printTriangle(rows);
break;
}
case 5: {
break;
}
default: {
System.out.println("** Invalid Choice **");
break;
}
}
} while (choice != 5);
}
private static void printTriangle(int size) {
char ch = '*';
for (int a = 0; a < 2 * size - 1; a++) {
if (a % 2 == 0) {
for (int b = 0; b < (2 * size - 1) - a; b++) {
System.out.print(" ");
}
for (int c = 0; c <= a; c++) {
System.out.print(ch + " ");
}
System.out.println();
}
}
}
}
After taking input for choice you have to write sc.nextLine() like
choice = sc.nextInt();
sc.nextLine();
switch (choice) {
because nextInt() only reads in until it's found the int and then stops.
You have to do nextLine() because the input stream still has a newline character and possibly other non-int data on the line. Calling nextLine() reads in whatever data is left, including the enter the user pressed between entering an int and entering a String.
To read both strings and integer value, a solution is to use two Scanners:
//Menu.java
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner intScanner = new Scanner(System.in);
//added new separate scanner for string
Scanner stringScanner = new Scanner(System.in);
int choice;
do {
int age;
System.out.println("\n::MENU::");
System.out.println("1.Echo Name");
System.out.println("2.Double Your Age");
System.out.println("3.Check Teenager or not");
System.out.println("4.Display Triangle");
System.out.println("5.Exit");
System.out.print("Enter Choice: ");
choice = intScanner.nextInt();
switch (choice) {
case 1: {
System.out.print("Enter your name: ");
String name = stringScanner.nextLine();
for (int i = 1; i <= 20; i++) {
System.out.println(name);
}
break;
}
case 2: {
System.out.print("Enter age :");
age = intScanner.nextInt();
System.out.println("Your age :" + age);
System.out.println("Doubled age :" + (2 * age));
break;
}
case 3: {
System.out.print("Enter age :");
age = intScanner.nextInt();
if (age >= 13 && age <= 19) {
System.out.println("Since you are " + age + " years old.Your are a Teenager");
} else {
System.out.println("Since you are " + age + " years old.Your are not a Teenager");
}
break;
}
case 4: {
int rows;
do {
System.out.print("Enter a number (between 3 and 50):");
rows = intScanner.nextInt();
if (rows < 3 || rows > 50) {
System.out.println("** Invalid.Must be between 3 and 50 **");
}
} while (rows < 3 || rows > 50);
printTriangle(rows);
break;
}
case 5: {
System.out.println("You pressed Exit");
break;
}
default: {
System.out.println("** Invalid Choice **");
break;
}
}
} while (choice != 5);
}
private static void printTriangle(int size) {
char ch = '*';
for (int a = 0; a < 2 * size - 1; a++) {
if (a % 2 == 0) {
for (int b = 0; b < (2 * size - 1) - a; b++) {
System.out.print(" ");
}
for (int c = 0; c <= a; c++) {
System.out.print(ch + " ");
}
System.out.println();
}
}
}
}

Exception Handling for no user input in Java

I am trying to get my program to exception handle for if the user inputs nothing so they will get an error message of "Error, enter a dollar amount greater than 0" or "Error, Enter a 1, 2 or 3". As of now, the program does nothing if the user just hits "enter" with no input....
import java.util.Scanner;
import java.util.*;
import java.text.DecimalFormat;
public class Candleline
{
public static void main(String[] args)
{
//initiate scanner
Scanner input = new Scanner(System.in);
System.out.println("\tCandleLine - Candles Online");
System.out.println(" ");
//declare variables and call methods
double candleCost = getCandleCost();
int shippingType = getShippingType();
double shippingCost = getShippingCost(candleCost, shippingType);
output(candleCost, shippingCost);
}
public static double getCandleCost()
{
//get candle cost and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
double candleCost = 0;
while(!done)
{
System.out.print("Enter the cost of the candle order: ");
try
{
inputCost = input.next();
candleCost = Double.parseDouble(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (candleCost <=0) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println("Error, enter a dollar amount greater than 0");
input.nextLine();
}
}
return candleCost;
}
public static int getShippingType()
{
//get shipping type and error check
Scanner input = new Scanner(System.in);
boolean done = false;
String inputCost;
int shippingCost = 0;
while(!done)
{
System.out.println(" ");
System.out.print("Enter the type of shipping: \n\t1) Priority(Overnight) \n\t2) Express (2 business days) \n\t3) Standard (3 to 7 business days) \nEnter type number: ");
try
{
inputCost = input.next();
shippingCost = Integer.parseInt(inputCost);
if (inputCost == null) throw new InputMismatchException();
if (shippingCost <=0 || shippingCost >= 4) throw new NumberFormatException();
done = true;
}
catch(InputMismatchException e)
{
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
catch(NumberFormatException nfe)
{
System.out.println(" ");
System.out.println("Error, enter a 1, 2 or 3");
input.nextLine();
}
}
return shippingCost;
}
public static double getShippingCost(double candleCost, int shippingType)
{
//calculate shipping costs
double shippingCost = 0;
if (shippingType == 1)
{
shippingCost = 16.95;
}
if (shippingType == 2)
{
shippingCost = 13.95;
}
if (shippingType == 3)
{
shippingCost = 7.95;
}
if (candleCost >= 100 && shippingType == 3)
{
shippingCost = 0;
}
return shippingCost;
}
public static void output(double fCandleCost, double fShippingCost)
{
//display the candle cost, shipping cost, and total
Scanner input = new Scanner(System.in);
DecimalFormat currency = new DecimalFormat("$#,###.00");
System.out.println("");
System.out.println("The candle cost of " + currency.format(fCandleCost) + " plus the shipping cost of " + currency.format(fShippingCost) + " equals " + currency.format(fCandleCost+fShippingCost));
}
}
Replace input.next();
with input.nextLine();
You can write a method that validates the input before proceeding. It can keep asking for inputs if user enters something that is not valid. E.g. below example demonstrates how to validate an integer input:
private static int getInput(){
System.out.print("Enter amount :");
Scanner scanner = new Scanner(System.in);
int amount;
while(true){
if(scanner.hasNextInt()){
amount = scanner.nextInt();
break;
}else{
System.out.println("Invalid amount, enter again.");
scanner.next();
}
}
scanner.close();
return amount;
}

Reading user input as a String and comparing it to any ArrayList for validation

I'm working on a program for a plant nursery that has two classes; PlantNursery and Plant. The user gets promoted 4 questions. 1) Add a plant, 2) List all the plants, 3) Edit a plant, and 4) Quit. I got 1, 2, and 4 working fine. My problem lies within option 3. I display the current list of plants in the array and ask the user to pick one by it's common name. Then I store the String and compare it with an if statement. The if statement is not working as expected. I get the error message:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at plantnursery.PlantNursery.main(PlantNursery.java:92)
C:\Users\diggz\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 52 seconds)
Plant class:
package plantnursery;
public class Plant
{
//Variables
private String commonName, scientificName;
private double maxHeight, price;
private boolean fragile;
//Constructor
public Plant(String commonName, String scientificName, double maxHeight,
double price, boolean fragile)
{
this.maxHeight = maxHeight;
this.price = price;
this.commonName = commonName;
this.scientificName = scientificName;
this.fragile = fragile;
}
public double getMaxHeight()
{
return maxHeight;
}
public void setMaxHeight(double maxHeight)
{
this.maxHeight = maxHeight;
}
public double getPrice()
{
return price;
}
public void setPrice(double price)
{
this.price = price;
}
public String getCommonName()
{
return commonName;
}
public void setCommonName(String commonName)
{
this.commonName = commonName;
}
public String getScientificName()
{
return scientificName;
}
public void setScientificName(String scientificName)
{
this.scientificName = scientificName;
}
public boolean isFragile()
{
return fragile;
}
public void setFragile(boolean fragile)
{
this.fragile = fragile;
}
#Override
public String toString() {
return "Plant{" + "commonName= " + commonName + ", scientificName= "
+ scientificName + ", maxHeight= " + maxHeight + ", price= "
+ price + ", fragile= " + fragile + '}';
}
}
PlantNursery class:
package plantnursery;
import java.util.ArrayList;
import java.util.Scanner;
public class PlantNursery
{
public static void main(String[] args)
{
//Variables to hold user input.
double userHeight, userPrice;
String userComName, userSciName, blankLine;
boolean userFragile;
int ans, choice;
//Reference variable to an object.
Plant p;
//Scanner for user input.
Scanner scan = new Scanner(System.in);
//ArrayList to store all the plants in.
ArrayList<Plant> plantList = new ArrayList<>();
//While loop asking the user to create new plants and store them
//in the the ArrayList. Edit any of the plants already in the ArrayList
//or quit the program.
while(true)
{
//Ask the user what they want to do.
System.out.println("What do you want to do?\n1. Add a plant. "
+ "\n2. List all plants.\n3. Edit a plant. \n4. Quit.");
//Store answer
ans = scan.nextInt();
//Choice 1. Add a new plant into the ArrayList.
if(ans == 1)
{
//Get rid of buffer overflow from int ans.
blankLine = scan.nextLine();
//Ask the user for input for a new plant object.
System.out.println("Please enter the common name of the plant:");
userComName = scan.nextLine();
System.out.println("Please enter the scienitific name of the plant: ");
userSciName = scan.nextLine();
System.out.println("Please enter the maximum height (in feet) of the plant: ");
userHeight = scan.nextDouble();
System.out.println("Please enter the price of the plant: ");
userPrice = scan.nextDouble();
System.out.println("Please enter if the plant is fragile (true or false): ");
userFragile = scan.nextBoolean();
//Create the new plant object.
p = new Plant(userComName, userSciName, userHeight, userPrice,
userFragile);
//Add the plant object to the ArrayList.
plantList.add(p);
}
//Choice 2. Display all plant(s) in the ArrayList.
if(ans == 2)
{
//List all the current plants in the ArrayList.
for(Plant curList : plantList)
{
System.out.println(curList);
}
}
//Choice 3. Edit information on plant(s) in ArrayList.
if(ans == 3)
{
//Allows the user to edit until they wish to quit.
while(true)
{
//Counter for ArrayList
int i;
//String to hold which plant the user wishes to edit.
String userAns;
//Ask the user which plant they wish to edit.
System.out.println("Which plant to wish to edit (choose the common name)?");
//Display the plant(s).
for(i = 0; i < plantList.size(); i++)
{
System.out.println(plantList.get(i));
}
//Get the user input and compare it to the Common Name
blankLine = scan.nextLine();
userAns = scan.nextLine();
if(userAns.equalsIgnoreCase(plantList.get(i).getCommonName())) //PROBLEM CODE
{
//Ask what the user wishes to edit.
System.out.println("What do you wish to edit?\n1. Common Name."
+ "\n2. Scientific Name.\n3. Maximum Height.\n4. Price"
+ "\n5. Is it fragile (true or false)?\n6. Quit.");
//Get user choice.
choice = scan.nextInt();
//Choice 1
if(choice == 1)
{
System.out.println("What is the new Common Name? ");
String newComName = scan.nextLine();
plantList.get(i).setCommonName(newComName);
}
//Choice 2
if(choice == 2)
{
System.out.println("What is the new Scientific Name? ");
String newSciName = scan.nextLine();
plantList.get(i).setScientificName(newSciName);
}
//Choice 3
if(choice == 3)
{
System.out.println("What is the new Maximum Height? ");
double newHeight = scan.nextDouble();
plantList.get(i).setMaxHeight(newHeight);
}
//Choice 4
if(choice == 4)
{
System.out.println("What is the new Price?");
double newPrice = scan.nextDouble();
plantList.get(i).setPrice(newPrice);
}
//Choice 5
if(choice == 5)
{
System.out.println("Is the plant Fragile (true or false)? ");
boolean newFragile = scan.nextBoolean();
plantList.get(i).setFragile(newFragile);
}
//Choice 6
if(choice == 6)
{
break;
}
}
}
}
//Choice 4. End program.
if(ans == 4)
{
break;
}
}
}
}
Okay so I changed the third choice into a switch statement. Now the problem I have is I can only do one edit. After that first edit when I try to pick another plant or the same one to edit it doesn't read it and keeps asking me the same question.
Code:
//Choice 3. Edit information on plant(s) in ArrayList.
if(ans == 3)
{
OUTER:
while (true) {
int i;
String userAns;
System.out.println("Which plant to wish to edit (choose the common name)?");
for(i = 0; i < plantList.size(); i++)
{
System.out.println(plantList.get(i));
}
blankLine = scan.nextLine();
userAns = scan.nextLine();
if (userAns.equalsIgnoreCase(plantList.get(i-1).getCommonName())) {
System.out.println("What do you wish to edit?\n1. Common Name."
+ "\n2. Scientific Name.\n3. Maximum Height.\n4. Price"
+ "\n5. Is it fragile (true or false)?\n6. Quit.");
choice = scan.nextInt();
//Choices
switch (choice)
{
//Choice 1
case 1:
System.out.println("What is the new Common Name? ");
blankLine = scan.nextLine();
String newComName = scan.nextLine();
plantList.get(i-1).setCommonName(newComName);
break;
//Choice 2
case 2:
System.out.println("What is the new Scientific Name? ");
blankLine = scan.nextLine();
String newSciName = scan.nextLine();
plantList.get(i-1).setScientificName(newSciName);
break;
//Choice 3
case 3:
System.out.println("What is the new Maximum Height? ");
double newHeight = scan.nextDouble();
plantList.get(i-1).setMaxHeight(newHeight);
break;
//Choice 4
case 4:
System.out.println("What is the new Price?");
double newPrice = scan.nextDouble();
plantList.get(i-1).setPrice(newPrice);
break;
//Choice 5
case 5:
System.out.println("Is the plant Fragile (true or false)? ");
boolean newFragile = scan.nextBoolean();
plantList.get(i-1).setFragile(newFragile);
break;
//Choice 6
case 6:
break OUTER;
default:
break;
}
}
}
}
ArrayList index starts with 0, so you have to do plantList.get(i-1).setPrice(newPrice);
You are starting index 0. So if you type 2 it means you trying to access 3 values
array[0], array[1], array[2].
Change for(i = 0; i < plantList.size(); i++)
to for(i = 1; i < plantList.size(); i++)
if you do not wish to change your for loop then you need to change plantList.get(i) to plantList.get(i-1) to make sure it is within the range
for(i = 0; i < plantList.size(); i++)
{
System.out.println(plantList.get(i));
}
You've incremented i to plantList.size(). When you access the list with plantList.get(i).getCommonName(), i is already larger that the largest index.
You probably shouldn't use a variable defined outside the loop as the counter in the loop.
Have you considered a Map instead of seaching through the list?

Fixing my class name & one method in Java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I know these must be basic errors, but I'm not sure how to fix them.
I changed my class name to Interface & now Java has a problem with it.
Also, in my switch statement, I've tried to call the enterData method, but I'm getting an error on this line as well as on this line... "private static void enterData()" <-- it says a "token" is missing on this line?
I'm trying to call a method from case 0, but it isn't working.
import java.util.Scanner;
public class Interface {
private void run()
{
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
do {
System.out.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch(option)
{
case 0: enterData();
break;
case 1:
break;
case 2:
break;
case 9: System.out.println("You chose to exit the program.");
break;
default: System.out.println("Please choose a valid option.");
}
} while (option != 9);
private static void enterData()
{
System.out.println("Product name between 3 & 10 characters long: ");
name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
You can't define method in another method.
Change your code to this:
public class Interface {
private void run()
{
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
do {
System.out.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch(option)
{
case 0: enterData();
break;
case 1:
break;
case 2:
break;
case 9: System.out.println("You chose to exit the program.");
break;
default: System.out.println("Please choose a valid option.");
}
} while (option != 9);
}
private static void enterData()
{
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
Scanner console = new Scanner(System.in);
System.out.println("Product name between 3 & 10 characters long: ");
String name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
Try making a separate method and make those fields global. Something like this
import java.util.Scanner;
public class Interface {
int demandRate, option, end;
double setupCost, unitCost, inventoryCost;
double sellingPrice, optimalOrder;
String name;
private void run() {
Scanner console = new Scanner(System.in);
Store store1 = new Store(); // MUST DO THIS
do {
System.out
.println("Enter product data (0), Show product data (1), Show product strategy (2), Exit program (9).");
option = console.nextInt();
switch (option) {
case 0:
enterData(console);
break;
case 1:
break;
case 2:
break;
case 9:
System.out.println("You chose to exit the program.");
break;
default:
System.out.println("Please choose a valid option.");
}
} while (option != 9);
}
private void enterData(Scanner console) {
System.out.println("Product name between 3 & 10 characters long: ");
name = console.nextLine();
while ((name.length() < 3) || (name.length() > 10)) {
System.out
.println("Please put in a name between 3 & 10 characters long.");
name = console.nextLine();
}
name = name.toLowerCase();
System.out.println("Demand rate: ");
demandRate = console.nextInt();
while (demandRate <= 0) {
System.out.println("Please put in a positive integer.");
demandRate = console.nextInt();
}
System.out.println("Setup cost: ");
setupCost = console.nextDouble();
while (setupCost <= 0) {
System.out.println("Please put in a positive number.");
setupCost = console.nextInt();
}
System.out.println("Unit cost: ");
unitCost = console.nextDouble();
while (unitCost <= 0) {
System.out.println("Please put in a positive number.");
unitCost = console.nextInt();
}
System.out.println("Inventory cost: ");
inventoryCost = console.nextDouble();
while (inventoryCost <= 0) {
System.out.println("Please put in a positive number.");
inventoryCost = console.nextInt();
}
System.out.println("Selling price: ");
sellingPrice = console.nextDouble();
while (sellingPrice <= 0) {
System.out.println("Please put in a positive integer.");
sellingPrice = console.nextInt();
}
}
public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}
}
Interface is some kind of an abstract class definition keyword in java.
You can use a keyword to name your class with capitalized letters, but seriously, don't do this.
And you are not calling a method, you are implementing it in another method. You should go over writing and calling a method in java once again ;)

Categories