How to organize my Java code into classes - java

I will show you my code without any classes.
I need it divided in 3 classes which are Main class , First class , Second class.
for example ,
the main class
products class
and coding class maybe
package vending.machine.project;
import java.util.Scanner;
public class VendingMachineProject {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int n=1;
int x=1;
int exit=0;
double price = 0;
double tax = 0.15;
char choice;
double finPrice=0;
while(exit!=-1)
{
while(n!=5)
{
if(n>0&&n<5)
{
System.out.print("1.Hot Drinks\n2.Soft Drinks\n"
+ "3.Chips\n4.Sweets\n5.Exit\n\n");
System.out.print("Choose one of the types above: ");
n = keyboard.nextInt();
switch(n)
{
case 1:
System.out.print("1.Hot Chocolate (5$)\t\t\t2.Tea (2$)\n3.Caramel Latté (7$)\t\t\t"
+ "4.Turkish Coffee (6$)\n5.Espresso (8$)\t\t\t\t6.Green Tea (3$)\n\n");
System.out.print("What do you prefer to order Sir? write the number: ");
do
{
x = keyboard.nextInt();
if (x>0&&x<7)
{
switch(x)
{
case 1:
price = price + 5;
break;
case 2:
price = price + 2;
break;
case 3:
price = price + 7;
break;
case 4:
price = price + 6;
break;
case 5:
price = price + 8;
break;
case 6:
price = price + 3;
break;
}
}
else
System.out.print("Please choose one of"
+ " the hot drinks above Sir: ");
}while(!(x>0&&x<7));
break;
case 2:
System.out.print("1.Cocacola (2$)\t\t\t2.PEPSI (3$)\n3.Seven UP (1$)\t\t\t"
+ "4.Code Red (4$)\n5.Sprite (1$)\t\t\t6.Mirinda (2$)\n\n");
System.out.print("What do you prefer to order Sir? write the number: ");
do
{
x = keyboard.nextInt();
if (x>0&&x<7)
{
switch(x)
{
case 1:
price = price + 2;
break;
case 2:
price = price + 3;
break;
case 3:
price = price + 1;
break;
case 4:
price = price + 4;
break;
case 5:
price = price + 1;
break;
case 6:
price = price + 2;
break;
}
}
else
System.out.print("Please choose one of"
+ " the soft drinks above Sir: ");
}while(!(x>0&&x<7));
break;
case 3:
System.out.print("1.Lays (1$)\t\t\t2.Chips Oman (3$)\n3.Cheetos (3$)\t\t\t"
+ "4.Doritos (2$)\n5.Bugles (2$)\t\t\t6.AL Batal (1$)\n\n");
System.out.print("What do you prefer to order Sir? write the number: ");
do
{
x = keyboard.nextInt();
if (x>0&&x<7)
{
switch(x)
{
case 1:
price = price + 1;
break;
case 2:
price = price + 3;
break;
case 3:
price = price + 3;
break;
case 4:
price = price + 2;
break;
case 5:
price = price + 2;
break;
case 6:
price = price + 1;
break;
}
}
else
System.out.print("Please choose one of"
+ " the Chips above Sir: ");
}while(!(x>0&&x<7));
break;
case 4:
System.out.print("1.Oreo (1$)\t\t\t2.Kinder (4$)\n3.Bounty (3$)\t\t\t"
+ "4.Twix (3$)\n5.Galaxy (2$)\t\t\t6.Biscream (1$)\n\n");
System.out.print("What do you prefer to order Sir? write the number: ");
do
{
x = keyboard.nextInt();
if (x>0&&x<7)
{
switch(x)
{
case 1:
price = price + 1;
break;
case 2:
price = price + 4;
break;
case 3:
price = price + 3;
break;
case 4:
price = price + 3;
break;
case 5:
price = price + 2;
break;
case 6:
price = price + 1;
break;
}
}
else
System.out.print("Please choose one of"
+ " the sweets above Sir: ");
}while(!(x>0&&x<7));
break;
case 5:
exit = -1;
break;
}
System.out.print("Do you want to order anything more Sir?"
+ "type (y). If not Type (n) to Exit: ");
do{
choice = keyboard.next().charAt(0);
Character.toLowerCase(choice);
if(choice=='n'){
n = 5;
exit = -1;
}
else if(choice!='y'){
System.out.print("Please Sir choose (y) or (n): ");
}
}while(choice!='y'&&choice!='n'&&n!=5);
}
else {
System.out.print("Please choose from the list Above: ");
n = keyboard.nextInt();
}
}
}
}
}

You need to study the basics of object-oriented programming.
There is no one exact best way to organize your code into classes. Even separating the better ways from the less optimal ways takes more information about the business that you have given here. But let's walk though the basics to get you going.
Look for the things, the entities, from the real world that you are modeling in your app. Then list the attributes, the properties, that describe each particular entity.
I see products (food items) as an entity. Each product has a name, a price, and a category (hot drink, cold drink, chips, candy, and so on, as its attributes.
So write a class called Product to represent each product you are selling. In Java 16 and later, you might use a record to more briefly write the class. A record is appropriate only for a class whose main purpose is to merely communicate data transparently and immutably, with a focus on state rather than behavior, and no inheritance.
public record Product ( String name , int price , String category ) {}
If you were further advanced, I'd suggest an enum for the category. But for now use a String with text.
Instantiate your products.
Product oreo = new Product( "Oreo" , 1 , "Cookie" ) ;
Another entity is the vending machine. The vending machine holds a list of products. Make another class for this.
public class VendingMachine
{
// Member fields.
final private List< Product > products ;
…
// Constructor.
public VendingMachine()
{
this.products =
List.of(
new Product( "Oreo" , 1 , "Cookie" ) ,
new Product( "Turkish Coffee" , 6 , "Hot drink" ) ,
…
)
;
…
}
// Methods.
…
public List< Product > getProductsForCategory( String category )
{
… Loop all the products to find the ones whose assigned category matches this desired category.
}
}
That vending machine object knows how to search its list of products to produce a subset of products by category. So we have the getProductsForCategory method. That method returns an ordered collection, a List.
VendingMachine vendingMachine = new VendingMachine() ;
…
List< Product > cookies = vendingMachine.getProductsForCategory( "Cookie" ) ;
You might want a sort-order field, just an integer number, as another member field on your Product class if the business (your client) wants to list certain products ahead of others. With such a field, the getProductsForCategory method could sort the products.
Next we need to present each category’s list of products to the user. So we need a user-interface.
Make another class to interact with the user via the console. The UI class knows about public interface of the vending machine object, but the vending machine does not know about the console nor the user. The vending machine only knows about the products it offers.
The UI object will access each category of products from the vending machine, getting a list. The UI object will loop through those objects to present a menu to user. Based on user's feedback, the UI object builds a collection of the products and quantities ordered by the user. You might write another class for this "shopping cart" or "order pad" of the user's choices, with a total price calculated.
In more realistic work, a vending machine would also need to manage its inventory. But I suppose that aspect is outside the scope of your schoolwork assignment.

Related

How to ignore lettercase? [duplicate]

This question already has answers here:
Case insensitive matching in Java switch-case statement
(5 answers)
Closed 2 years ago.
So, I'm trying to make a simple menu with switches.
I have a letter choice inside it. I'm using next().charAt(0); to scan a letter.
It worked well, but I want to simplify it. you see, I have to make a case each choice both uppercase and lowercase.
So how to ignore case so I don't have to make both cases?
Also note: I'm using the old version of Java and Netbeans 8.2 as my IDE. (because my college keeps insisting not to use the newer one. Probably because they don't have the textbook yet.), so probably newer syntax wouldn't work.
my code:
import java.util.Scanner;
public class NewClass2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
char milk;
int s, h, price;
h = 0;
price = 0;
String type, size;
System.out.println("NutMart");
System.out.println("Milk selections:\n A. Milk A \n\t 1. Regular ($10) \n\t 2. Medium ($20) \n\t 3. Large ($30)");
System.out.println(" B. Milk B \n\t 1. Regular ($15) \n\t 2. Medium ($30) \n\t 3. Large ($45)");
System.out.println(" C. Milk C \n\t 1. Regular ($20) \n\t 2. Medium ($40) \n\t 3. Large ($60)");
System.out.println("Insert Milk Type: ");
milk = input.next().charAt(0);
switch(milk){
case 'a':
type = "Milk A";
h = 10;
break;
case 'b':
type = "Milk B";
h = 15;
break;
case 'c':
type = "Milk C";
h = 20;
break;
case 'A':
type = "Milk A";
h = 10;
break;
case 'B':
type = "Milk B";
h = 15;
break;
case 'C':
type = "Milk C";
h = 20;
break;
default:
System.out.println("Invalid!");
System.out.println("Please select the correct choice: ");
milk = input.next().charAt(0);
break;
}
System.out.println("Select the size: ");
while (!input .hasNextInt()) input .next();
s = input.nextInt();
switch(s){
case 1:
size = "Regular";
price = h * 1;
break;
case 2:
size = "Medium";
price = h * 2;
break;
case 3:
size = "Large";
price = h * 3;
break;
default:
System.out.println("Invalid");
System.out.println("Please select the correct choice: ");
while (!input .hasNextInt()) input .next();
s = input.nextInt();
break;
}
System.out.println("Individual Price: $" + price);
System.out.println("Please insert the quantity: ");
while (!input .hasNextInt()) input .next();
int quantity = input.nextInt();
int total = price * quantity;
System.out.println("Your total will be $" + total );
}
}
Note, that in this case converting to a consistent case is the best was to achieve your goal. But when you have a variety of results for dissimilar inputs in a switch statement you can do the following for case constructs.
case 'a':
case 'A:
type = "Milk A";
h = 10;
break;
...
The case will simply fall thru whether 'a' or 'A' was provided.

Variables aren't getting updated with the proper values

I'm making a java program for the system used at Luas Station to purchase tickets. The Luas is a type of train in the Ireland.
I have a few different types of tickets which involves various prices etc. After a customer selects what ticket to buy I give them an option to return to the beginning of the 'chooseTickets' to buy more tickets. At the end, the program I have assigned the value of all of the customer's desired tickets as the completePrice variable. the idea is to allow for the customer to continue adding tickets and for that variable to continuously add the prices of them to the variable until they're ready to pay. It works except when I go back to purchase for tickets and it is the same type, i.e a standard adult ticket twice. The price of 2.50 is not added to another 2.50, it is overwritten by another 2.5. Below is the code for the same:
import java.util.Scanner; //imports the scanner class to allow for user input
public class ticketPurchase {
//Adding global variables to be used by various methods
static Scanner input = new Scanner(System.in);
static String menuChoice;
static double childTicket = 1.20;
static double adultTicket = 2.50;
static double studentTicket = 1.70;
static double adultFlexi = 12.00;
static double childFlexi = 8.00;
static double studentFlexi;
static String ticketType;
static String ticketChoice;
static int adultTicketQty;
static int childTicketQty;
static int studentTicketQty;
static String destinationZone;
static double adultFinalPrice;
static double childFinalPrice;
static double studentFinalPrice;
static double flexiAdultFinalPrice;
static double flexiChildFinalPrice;
static double completePrice;
static String moreTicketChoice2 = "0";
public static void main(String[] args) {
menu(); //calling the menu method within the main method to start the process
}
public static void menu() {
if(moreTicketChoice2.equals("1")){
System.out.println("Press 2 to purchase Standard Tickets");
System.out.println("Press 3 to purchase Flexi tickets");
System.out.println("press 4 to purchase student tickets");
}
else if(moreTicketChoice2.equals("0")) {
System.out.println("Press 1 for information");
System.out.println("Press 2 to purchase Standard Tickets");
System.out.println("Press 3 to purchase Flexi tickets");
System.out.println("press 4 to purchase student tickets");
}
menuChoice = input.next(); //allowing user to choose what tickets to buy or just to see information of services
switch(menuChoice) { //switch statement to record and output information based on users input
case "1":{ //prints information regarding pricing, ticket age restrictions and support
System.out.println("The standard ticket may be a single or return ticket for an adult (16+) or a child");
System.out.println("The flexi ticket covers all journeys for one 24 hour period for either a child or an adult");
System.out.println("A single ticket's price depends on the journey length, single or return and if it is for an adult or a child");
System.out.println("a Flexi ticket for a child costs €8.00 and a Flexi ticket for an adult costs €12.00");
System.out.println("Our Customer Care telephone number for this terminal is 0830462920, please call if further support is required");
menu();
break;
}
case "2":{
ticketChoice = "standard"; //records the value of standard within the ticketChoice global variable
chooseTickets(); //initiates the choose tickets method
break;
}
case "3":{
ticketChoice = "flexi"; //record the value of Flexi within the ticketChoice global variable
chooseTickets();
break;
}
case "4":{
ticketChoice = "student";
chooseTickets();
}
case "a":{ //allows user to enter the admin interface
admin();
break;
}
default:{ //allows for user to input a value outside of the options and notify's them to try again
System.out.println("Invalid choice, please choose from 1 to 3");
break;
}
}
}
public static void chooseTickets() { //payment method to choose quantity, destination zone and final price
System.out.println("You have chosen to purchase " + ticketChoice + " ticket(s)");
if(ticketChoice.equals("student")) { //allows user to purchase student's tickets
ticketType = "student";
System.out.println("Please enter the quantity of tickets: ");
studentTicketQty = input.nextInt();
System.out.print("please enter your destination zone (1, 2, 3, 4): ");
destinationZone = input.next();
ticketChoice = "student";
studentFinalPrice = (studentTicket*studentTicketQty);
switch(destinationZone){ //adjusts price to account for the destination's zone chosen by user
case "1":{
studentFinalPrice = studentFinalPrice + (studentTicketQty*0);
break;
}
case "2":{
studentFinalPrice = studentFinalPrice + (studentTicketQty*0.50);
break;
}
case "3":{
studentFinalPrice = studentFinalPrice + (studentTicketQty*1.0);
break;
}
case "4":{
studentFinalPrice = studentFinalPrice + (studentTicketQty*1.50);
break;
}
default:{
System.out.println("you have entered an invalid choice please choose from 1 to 4");
chooseTickets();
break;
}
}
System.out.print("would you like to purchase more tickets? enter 1 if so, 2 if not: "); //allows user to purchase other tickets
moreTicketChoice2 = input.next();
if(moreTicketChoice2.equals("1")) {
menu();
}
else if(moreTicketChoice2.equals("2")){
System.out.println("you have chosen against purchasing more tickets");
payment();
}
}
else {
System.out.print("please enter 1 for children's tickets and 2 for adult's: ");
String ticketAgeGroup = input.next();
switch(ticketAgeGroup) { //allows user to choose quantity and destination based on choice of adult or child
case "2":{//case for adult tickets
System.out.println("you have chosen adults ticket");
ticketType = "adult";
System.out.print("Please enter the quantity of tickets: ");
adultTicketQty = input.nextInt();
System.out.print("please enter your destination zone (1, 2, 3, 4): ");
destinationZone = input.next();
if(ticketChoice == "flexi") { //if statement to calculate the finalPrice variable value if the ticketChoice is Flexi
flexiAdultFinalPrice = (adultFlexi*adultTicketQty);
}
else {
adultFinalPrice = (adultTicket*adultTicketQty); //else calculates the finalPrice variable value if the ticketChoice is standard
}
switch(destinationZone){ // switch statement to calculate the final price depending on the destination's zone and their extra amount.
case "1":{
adultFinalPrice = adultFinalPrice + (adultTicketQty*0);
break;
}
case "2":{
adultFinalPrice = adultFinalPrice + (adultTicketQty*.50); //calculation to add the extra amount for the destination
break;
}
case "3":{
adultFinalPrice = adultFinalPrice + (adultTicketQty*1.0);
break;
}
case "4":{
adultFinalPrice = adultFinalPrice + (adultTicketQty*1.50);
break;
}
default:{
System.out.println("you have entered an invalid choice please choose from 1 to 4");
break;
}
} //end of the switch statement
System.out.print("Would you like to purchase more tickets? enter 1 if so, 2 if not: "); //allows user to purchase other tickets
moreTicketChoice2 = input.next();
if(moreTicketChoice2.equals("1")) { //if statement to allow a customer to purchase more tickets if required
menu();
}
else {
System.out.println("you have chosen against purchasing more tickets");
payment(); //proceeds to the payment method
}
break;
}
case "1":{ //case for children's tickets
System.out.println("you have chosen children's ticket");
ticketType = "child";
System.out.println("Please enter the quantity of tickets: ");
childTicketQty = input.nextInt();
System.out.print("please enter your destination zone (1, 2, 3, 4): ");
destinationZone = input.next();
if(ticketChoice == "flexi") { //adjusts the price if user chooses the flexi option
flexiChildFinalPrice = (childFlexi*childTicketQty);
}
else {
childFinalPrice = (childTicket*childTicketQty);
}
switch(destinationZone){ //adjusts price to account for the destination's zone chosen by user
case "1":{
childFinalPrice = childFinalPrice + (childTicketQty*0);
break;
}
case "2":{
childFinalPrice = childFinalPrice + (childTicketQty*.50);
break;
}
case "3":{
childFinalPrice = childFinalPrice + (childTicketQty*1.0);
break;
}
case "4":{
childFinalPrice = childFinalPrice + (childTicketQty*1.50);
break;
}
default:{
System.out.println("you have entered an invalid choice please choose from 1 to 4");
chooseTickets();
break;
}
}
System.out.print("would you like to purchase more tickets? enter 1 if so, 2 if not: "); //allows user to purchase other tickets
moreTicketChoice2 = input.next();
if(moreTicketChoice2.equals("1")) {
menu();
}
else if(moreTicketChoice2.equals("2")){
System.out.println("you have chosen against purchasing more tickets");
payment();
}
break;
}
}
}
}
public static void payment() { //method to complete the payment process for the purchase
completePrice = adultFinalPrice + childFinalPrice + studentFinalPrice + flexiAdultFinalPrice + flexiChildFinalPrice;
System.out.println("the total due is €" + completePrice);
}
public static void printTickets() { //method to notify the customer that their tickets are printing
}
public static void admin() { //method to control the admin's interface
}
}
In this photo i want an output of 2.4 not 1.2

Using switch in Java to assign additional values

Im new to java and trying to write a switch. Where depending on a value of guess different prize will be given. I'm doing something wrong because compiler says variable already defined. But how can I not define it, so that switch knows what value to look for to give what prize?
if (guess == randomNom)
{
System.out.println(" You Win! ");
player.setEarning(player.getEarn() + guess * 10);
int reward = guess;
String prize = "";
switch(reward)
{
case 1: int reward = 10;
String prize = " Prize #1";
break;
case 2: int reward = 20 ;
String prize = "Prize #2";
break;
case 3: int reward = 30;
String prize = "Prize #3";
break;
...
}
compiler say OK, You try to create 'another variable with the same name', whats wrong. Delete duplicated declarations
if (guess == randomNom)
{
System.out.println(" You Win! ");
player.setEarning(player.getEarn() + guess * 10);
int reward = guess;
String prize = "";
switch(reward)
{
case 1: reward = 10;
prize = " Prize #1";
break;
case 2: reward = 20 ;
prize = "Prize #2";
break;
case 3: reward = 30;
prize = "Prize #3";
break;
...
}
The problem is in these lines
String prize = "";
String prize = " Prize #1";
String prize = "Prize #2";
When you Assign a variable in above manner i.e. data type followed by variable name compiler assumes that you want to define a new variable with some value.
Instead, you should define it once
String prize = ""; // Data type followed by variable name is to define new variable
and update subsequently
prize = " Prize #1"; //just the variable name with assignment operator to assign new value to existing variable.
prize = " Prize #2";

Interface method issue [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 5 years ago.
I am required to implement an interface as part of my final school assignment for my Java class. The overridden interface is supposed to print a short message describing how a football player celebrates being drafted in the NFL, something like this:
System.out.println("name dances to celebrate his draft");
However my interface is not printing the message when I put it into the methods which allow the user to add a player to their roster. Here is the overridden interface in the program:
//Overridden celebrate method
#Override
public void celebrate(int i, int place){
int randomInteger;
if (place == 0) //Player is offensive
{
randomInteger = random1Thru6();
//players() is a method that contains all the players in the team
//'place' refers to the players location in the array of players on the team
switch (randomInteger)
{
case 1: System.out.println(players(i).get(place) + " dances to celebrate his draft!");
break;
case 2: System.out.println(players(i).get(place) + " cartwheels to celebrate his draft!");
break;
case 3: System.out.println(players(i).get(place) + " throws a party to celebrate his draft!");
break;
case 4: System.out.println(players(i).get(place) + " sings to celebrate his draft!");
break;
case 5: System.out.println(players(i).get(place) + " gets root beer for everyone to celebrate his draft!");
break;
case 6: System.out.println(players(i).get(place) + " gets donuts to celebrate his draft!");
}
}
else if (place == 1) //Player is defensive
{
randomInteger = random1Thru6();
switch (randomInteger)
{
case 1: System.out.println(players(i).get(place) + " dances to celebrate his draft!");
break;
case 2: System.out.println(players(i).get(place) + " cartwheels to celebrate his draft!");
break;
case 3: System.out.println(players(i).get(place) + " throws a party to celebrate his draft!");
break;
case 4: System.out.println(players(i).get(place) + " sings to celebrate his draft!");
break;
case 5: System.out.println(players(i).get(place) + " gets root beer for everyone to celebrate his draft!");
break;
case 6: System.out.println(players(i).get(place) + " gets pizza to celebrate his draft!");
}
}
}
I am supposed to have one different celebratory response for offensive and defensive positions as is shown in the code above.
Here is the referenced random1Thru6() method:
public int random1Thru6() { //used to get a random number from 1 to 6
int randomInteger = (int)Math.random() * 10;
//this is supposed to call the method over and over again until it gives a number from 1-6 but it has been printing 7-9 as well
if (randomInteger > 6)
random1Thru6();
return randomInteger;
}
And here is the players() method:
//holds and prints all the players
public ArrayList<String> players(int i) {
ArrayList<String> returnedList = new ArrayList<>();
// Christian McCaffrey is a Running Back, Corn Elder is a Corner Back for the Carolina Panthers
ArrayList<String> Players1 = new ArrayList<String>();
Players1.add("Christian McCaffrey");
Players1.add("Corn Elder");
//Jake Butt is a Tight End, Brendan Langley is a Corner Back for the Denver Broncos
ArrayList<String> Players2 = new ArrayList<String>();
Players2.add("Jake Butt");
Players2.add("Brendan Langley");
//Ryan Switzer is a Wide Receiver, Taco Charlton is a Defensive End for the Dallas Cowboys
ArrayList<String> Players3 = new ArrayList<String>();
Players3.add("Ryan Switzer");
Players3.add("Taco Charlton");
//Dalvin Cook is a Running Back, Ifeadi Odenigbo is a Defensive Line for the Minnesota Vikings
ArrayList<String> Players4 = new ArrayList<String>();
Players4.add("Dalvin Cook");
Players4.add("Ifeadi Odenigbo");
switch (i)
{
case 1: returnedList.addAll(Players1);
break;
case 2: returnedList.addAll(Players2);
break;
case 3: returnedList.addAll(Players3);
break;
case 4: returnedList.addAll(Players4);
break;
}
return returnedList;
}
Here is how the celebrate() method is called:
for (int l = 0; l < players(i).size(); l++)
{
if (choosePlayer.equalsIgnoreCase(players(i).get(l)))
{
addPlayer(players(i).get(l));
celebrate(i, l);
enterRoster();
}
}
And:
addPlayer(players(i).get(place));
celebrate(i, place);
enterRoster();
addPlayer(int i, int place) is a method that adds the player for team 'i' in the position of 'place' in the team's player array into the ArrayList of the user's roster.
NOTE: I checked what number was being called by random1Thru6() as suggested in a comment and now I understand why it wasn't printing the celebrate message, since I had (int)Math.random() * 10 it was always returning 0 so I changed it to:
double randomDouble = Math.random() * 10;
int randomInteger = (int)randomDouble;
Now it prints the celebrate messages but random1Thru6() is now returning all numbers 1-9, please explain how I can make this method call itself recursively until it will return a number 1-6.
Thank you delephin for your comment!
NOTE: I have accepted delephin's answer shown below, thank you all for the help!
Add to your main class:
static Random r = new Random();
static {
r.setSeed(System.currentTimeMillis());
}
and change your randomizer method to something like this:
public int random1Thru6() {
return r.nextInt(6) + 1;
}
From a quick test, your previous randomizer was returning zeros.

How to make the switch statement more accurate?

We were ask to make a program using the switch statement..
Here is my code:
double price = 0, totalPrice;
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
default:
System.out.println("ERROR: Invalid number!");
break;
}
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
So basically, the user will input a certain number and it will have different prices... inside the switch statements.
but if the user inputs a wrong number, it will display an error message and i dont want the user to enter the quantity which will be executed after the switch statement.
we are not allowed to use any methods or functions and i dont want to code repeatedly like this:
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
break;
case 2:
price = 410.00;
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
break;
default:
System.out.println("ERROR: Invalid number!");
break;
}
is there any other way not to use if else, methods, functions or coding repeatedly?
ANY HELP WILL BE APPRECIATED.
You can use a boolean flag and make it false if invalid option is selected.
Then only ask user further if flag is true.
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
boolean flag = true;
switch (optionNumber) {
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
default:
flag = false;
System.out.println("ERROR: Invalid number!");
break;
}
if (flag) {
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
}
Use as this:
while(!valid option)
//do this stuff
Use a flag and set it to true if the number entered is valid, so it will go to your next instruction; else ask again for input.
Throw an exception
default:
throw new InvalidArgumentException("Invalid number!");
See also InvalidArgumentException vs UnexpectedValueException
You could just remove default from the switch statement and check to see if the price is equal to 0 after the switch statement
double price = 0, totalPrice;
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
}
if (price == 0)
{
System.out.println("ERROR: Invalid number!");
}
else
{
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
}
This keeps you from adding unnecessary variables (like a boolean flag) when you already have one (price) with a default value of 0 that you can check against.

Categories

Resources