switch case in implementation of stack using array in java - java

import java.io.*;
import java.util.*;
public class Stack1{
static final int MAX=100;
int top=-1;
int[] stack=new int[MAX];
public static void main(String args[])
{
Stack1 s1=new Stack1();
int opt, val;
System.out.println("1. PUSH ");
System.out.println("2. POP ");
System.out.println("3. PEEP ");
System.out.println("4. DISPLAY STACK ");
System.out.println("5. EXIT ");
System.out.println("\n Enter Your Option: ");
Scanner s=new Scanner(System.in);
opt=s.nextInt();
do{
switch(opt)
{
case 1: System.out.println("Enter the value to be added to the stack: ");
val=s.nextInt();
s1.push(val);
break;
case 2: s1.pop();
break;
/*
case 3: s1.peep();
break; */
case 4: s1.display();
break;
}
}while(opt!=5);
}
public void push(int val)
{
if(top==MAX-1)
{
System.out.println("Stack is FULL!");
}
else
{
top++;
stack[top]=val;
System.out.println("Element added to the stack is: "+val);
display();
}
}
public void pop()
{
int x;
if(top==-1)
{
System.out.println("Stack is EMPTY!");
}
else
{
x=stack[top];
System.out.println("The element deleted from the stack is: "+x);
top--;
display();
}
}
public void peep()
{
int n;
n=stack[top];
System.out.println("The value at the top of the stack is: "+n);
}
public void display()
{
int i;
if(top==-1)
System.out.println("STACK IS EMPTY!");
else
{
for(i=0; i<=top; i++)
System.out.println("The elements in the stack are: "+stack[i]);
}
}
}
I wrote this java code to implement stack. But once I select any option, only that method gets executed and the program ends. I want the program to provide me to enter another option once the current method is executed. What should I do?

As #LordWilmore pointed out in his comment, the opt value will be set just once causing program to spin forever in a corresponding case (unless the value is 5). Moving opt = s.nextInt(); inside loop will fix the issue.
do {
System.out.println("Enter Your Option: ");
opt = s.nextInt();
switch(opt) {
//...
}
} while (opt != 5);

You can modify your main method in a manner like this:
public static void main(String args[]){
int option;
Scanner sc = new Scanner(System.in);
MyStack1 s = new MyStack1();
while(true){
System.out.println("Enter the choice You want to perform on the stack: ");
System.out.println(" 1. push \n 2. Pop \n 3. Display \n 4. peep \n 5. Exit");
System.out.println("Enter your option: ");
option = sc.nextInt();
switch(option){
case 1: System.out.println("Enter the element you want to push into the stack: ");
s.push(sc.nextInt());
break;
case 2: s.pop();
break;
case 3: System.out.println("Displaying the stack contents: ");
s.display();
break;
case 4: System.out.println("The top element in the stack is: ");
s.peek();
break;
case 5: System.out.println("You selected Exit!!");
break;
default: System.out.println("Wrong choice!! Please enter a valid option!!");
return;
}
}
}

Related

how to implement returning to previous menu from a menu implemented through switch?

I am writing a program where the user inputs a choice in the main menu and it takes them to another sub-menu. I want one of the options to be "return to previous menu" i.e. the menu first shown to the user. I can not really figure out how to do this in the way I have set up my code. Here is my code for the PrintMenu method:
public static void PrintMenu(){
Scanner input = new Scanner (System.in);
int option = 0;
while(option != 3){
System.out.println("Menu Please enter an option given bellow: ");
System.out.println("Option Operation Completed");
System.out.println("--------------------------------");
System.out.println("1 Stack");
System.out.println("2 Queue");
System.out.println("3 Quit");
option = input.nextInt();
switch(option){
case 1:
{
//add code for stack
System.out.println("You are currently using a stack. \n");
System.out.println("Enter the maximum size you want for your stack: ");
maxSize = input.nextInt();
int option_stack = 0;
while(option_stack != 5){
System.out.println("Menu Please enter an option given
bellow: ");
System.out.println("Option Operation Completed");
System.out.println("--------------------------------");
System.out.println("1 Add to Stack");
System.out.println("2 Remove from Stack");
System.out.println("3 Clear Stack");
System.out.println("4 Return to previous menu");
System.out.println("5 Quit");
option_stack = input.nextInt();
switch(option_stack){
case 1:
{
//add code for Add to Stack
break;
}
case 2:
{
//add code for Remove from Stack
break;
}
case 3:
{
//add code for Clear Stack
break;
}
case 4:
{
//add code for Return to previous menu
break;
}
case 5:
System.exit(0);
break;
//Error message if user inputs anything other
than 1-5
default:
System.out.println(option + " is not a
correct choice.\n"
+ "please enter
another option. \n");
break;
}
}
break;
}
case 2:
{
//add sub-menu and corresponding code for queue in the same
//way as stack
}
}
}
What can I put in case 4 that would take the user to the main menu?
A good point to start is this skeleton below.
Let me explain some points:
Don't use static methods if you have no good reason to do!
Please have a look to this discussion
Keep your switch statements as short as possible and avoid nesting!
The longer the switch statement the more difficult is it to keep track of it.
The deeper the nesting the higher the complexity.
A good way to avoid both is to put the code of each case in a seperate method or to encapsulate in it's own class.
Don't use curly brackets for case blocks.
They are avoidable noise (especially if you follow bullet point 2).
In the Main class create a instance of it self to get out of the 'static trap'.
The startable Main class containing the main menu:
package joker5309;
import java.util.Scanner;
public class Menu {
public void mainMenu() {
Scanner input = new Scanner(System.in);
int option = 0;
while (option != 3) {
System.out.println("do stuff for main menu ... ");
System.out.println("Menu Please enter an option given bellow: ");
System.out.println("Option Operation Completed");
System.out.println("--------------------------------");
System.out.println("1 Stack");
System.out.println("2 Queue");
System.out.println("3 Something else");
System.out.println("4 Quit");
option = input.nextInt();
switch (option) {
case 1:
StackHandler stackHandler = new StackHandler();
stackHandler.doIt(input);
break;
case 2:
// add sub-menu and corresponding code for queue in the same
// way as stack
QueueHandler queueHandler = new QueueHandler();
queueHandler.doIt(input);
break;
case 3:
// add any other submenue ...
SomethingElseHandler seHandler = new SomethingElseHandler();
seHandler.doIt(input);
break;
case 4:
System.exit(0);
} // hctiws
} // elihw
} // mainMenu()
public static void main(String[] args) {
// create an instance of Menu class to leave the 'static trap'
Menu mySelf = new Menu();
mySelf.mainMenu();
} // main()
} // sslac
A seperate handler class for each meun item:
package joker5309;
import java.util.Scanner;
public class StackHandler implements Handler {
#Override
public void doIt(Scanner input) {
// add code for stack
System.out.println("You are currently using a stack. \n");
System.out.println("Enter the maximum size you want for your stack: ");
input.nextInt();
int optionStack = 0;
while (true) {
System.out.println("do stuff for stack ... ");
System.out.println("Menu Please enter an option given bellow: ");
System.out.println("Option Operation Completed");
System.out.println("--------------------------------");
System.out.println("1 Add to Stack");
System.out.println("2 Remove from Stack");
System.out.println("3 Clear Stack");
System.out.println("4 Return to previous menu");
System.out.println("5 Quit");
optionStack = input.nextInt();
switch (optionStack) {
case 1:
// add code for Add to Stack
stackAdd();
break;
case 2:
// add code for Remove from Stack
stackRemove();
break;
case 3:
// add code for Clear Stack
stackClear();
break;
case 4:
// add code for Return to previous menu
return;
case 5:
System.exit(0);
break;
// Error message if user inputs anything other than 1-5
default:
System.out.println(optionStack + " is not a correct choice.\n" + "please enter another option. \n");
break;
} // hctiws
} // elihw
} // stackParameter()
private void stackAdd() {
System.out.println("stackAdd()");
}
private void stackRemove() {
System.out.println("stackRemove()");
}
private void stackClear() {
System.out.println("stackClear()");
}
}
package joker5309;
import java.util.Scanner;
public class QueueHandler implements Handler {
#Override
public void doIt(Scanner input) {
int optionQueue = 0;
while (true) {
System.out.println("do stuff for queue ... ");
System.out.println("Menu Please enter an option given bellow: ");
System.out.println("Option Operation Completed");
System.out.println("--------------------------------");
System.out.println("1 ...");
System.out.println("2 Return to previous menu");
System.out.println("3 Quit");
optionQueue = input.nextInt();
switch (optionQueue) {
case 1:
// add code for ...
break;
case 2:
// add code for Return to previous menu
return;
case 3:
System.exit(0);
break;
// Error message if user inputs anything other than 1-5
default:
System.out.println(optionQueue + " is not a correct choice.\n" + "please enter another option. \n");
break;
} // hctiws
} // elihw
} // queueParameter()
}
package joker5309;
import java.util.Scanner;
public class SomethingElseHandler implements Handler {
#Override
public void doIt(Scanner input) {
int optionStack = 0;
while (true) {
System.out.println("do stuff for something else ... ");
System.out.println("Menu Please enter an option given bellow: ");
System.out.println("Option Operation Completed");
System.out.println("--------------------------------");
System.out.println("1 ...");
System.out.println("2 Return to previous menu");
System.out.println("3 Quit");
optionStack = input.nextInt();
switch (optionStack) {
case 1:
// add code for ...
break;
case 2:
// add code for Return to previous menu
return;
case 3:
System.exit(0);
break;
// Error message if user inputs anything other than 1-5
default:
System.out.println(optionStack + " is not a correct choice.\n" + "please enter another option. \n");
break;
} // hctiws
} // elihw
} // queueParameter()
}

I had error in Department constructor in if else in dept function

I had an error in the Department constructor in the if else statement in dept() method. How can I solve this?
I tried several tries by making the function abstract using different function name but it doesn't work.
class Book
import java.util.*;
class Book
{
int Book_id;
String Book_Name;
String Author_Name;
int pages;
float prices;
void getbook()
{
Scanner SC=new Scanner(System.in);
System.out.println("Enter the Book ID");
Book_id=SC.nextInt();
System.out.println("Enter the Book Name");
Book_Name=SC.next();
System.out.println("Enter the Author Name");
Author_Name=SC.next();
System.out.println("Enter the pages");
pages=SC.nextInt();
System.out.println("Enter the prices");
prices=SC.nextFloat();
}
void display()
{
System.out.println("Book Id"+Book_id);
System.out.println("Book Name"+Book_Name);
System.out.println("Author Name"+Author_Name);
System.out.println("Pages"+pages);
System.out.println("Prices"+prices);
}
}
class Student
class Student extends Book
{
String Student_N;
int roll_no;
}
class Department
class Department extends Student
{
int choice;
String Dept_Code;
Department(int roll,String C)
{
System.out.println(""+C+""+roll_no);
}
void dept()
{
Scanner SC=new Scanner(System.in);
System.out.println("1.Civil Enginerring");
System.out.println("2.Computer Enginerring");
System.out.println("3.Information Tecnology");
System.out.println("4.Mechanical Engineering");
System.out.println("5.Electorics Enginerring");
System.out.println("6.Electrical Enginerring");
System.out.println("Enter the choice");
choice=SC.nextInt();
switch (choice)
{
case 1:
dept_data();
break;
case 2:
dept_data();
break;
case 3:
dept_data();
break;
case 4:
dept_data();
break;
case 5:
dept_data();
break;
case 6:
dept_data();
break;
}
}
void dept_data()
{
Scanner SC=new Scanner(System.in);
System.out.println("Enter the Student Details");
System.out.println("Enter the Student Name");
SC.next();
System.out.println("Enter the Student Roll No");
SC.nextInt();
System.out.println("Enter the Book ID");
SC.nextInt();
System.out.println("Enter the Book Name");
SC.next();
}
int dept_del(String C)
{
Scanner SC=new Scanner(System.in);
if(C.compareTo("ci")==0||C.compareTo("CI")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("IT")==0||C.compareTo("it")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("CO")==0||C.compareTo("co")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("ME")==0||C.compareTo("me")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("EC")==0||C.compareTo("ec")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
else if(C.compareTo("EE")==0||C.compareTo("ee")==0)
{
System.out.println("Enter the roll no");
roll_no=SC.nextInt();
Department(roll_no,C); //error
}
}
}
class Project
class Project
{
public static void main(String[] args)
{
int i=1,flag=0;
Department A[]=new Department[100];
Scanner SC=new Scanner(System.in);
System.out.println("Enter the Choice");
System.out.println("1.Add a Book\n2.Display the Book");
while(flag==0)
{
int choice=SC.nextInt();
switch (choice)
{
case 1 :
A[i].getbook();
i++;
case 2:
int n=i;
for(i=0;i<n;i++)
A[i].display();
case 3:
flag=1;
break;
default:
System.out.println("Wrong Choice");
}
}
}
}
The problem in your constructor is that it receives int roll, String C and does nothig with them and the instance vars int choice& String Dept_Codeare not defined after the constructor executes.
Maybe you wanted to do:
Department(int choice, String Dept_Code) {
this.choice = choice;
this.Dept_Code = Dept_Code;
System.out.println("" + Dept_Code + " - " + choice);
}
In the switch(choice) some breaks are missing after case 1 & 2 if you want to separate add a book fom display the book and from case 3:
switch(choice) {
case 1 :
A[i].getbook();
i++;
break;
case 2:
int n=i;
for(i=0;i<n;i++)
A[i].display();
break;
case 3:
flag=1;
break;
default:
System.out.println("Wrong Choice");
}
And in the other switch it makes no sense to create a switch if all the cases just execute the same dept_data()
code.
And as a suggestion it's better to always use the constant first when comparing to prevent from possible null pointers:
"ci".compareTo(C) is better than C.compareTo("ci") as the second option could throw a null pointer exception if C is undefined. Also, have a look at naming conventions: https://www.geeksforgeeks.org/java-naming-conventions/

Use switch case within while loop

I'm trying to code simple calculator (all in one) using Switch cases in java. I came up with following code so far. However I'm stuck with while loop. I want to keep showing main menu after each case execution until user decides to exit the program.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result=0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is "+result);
}
}
Above code works fine. Program ends itself after execution of user selected choice. I want to put main menu on a repeat.
Add a while loop like this:
public static void main(String[] args) {
// Moved this outside the while loop as davidxxx pointed out +1
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i = s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;//'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is " + result);
System.out.println("Go again?");
String goAgain = s.next();
if (!goAgain.equals("y")) {
break;
}
}
}
Try this:
import java.util.Scanner;
public class Calculator {
private static final String EXIT = "EXIT";
public static void main(String[] args) {
Calculator calc = new Calculator();
Scanner s = new Scanner(System.in);
while (true) {
String res = calc.runCalc(s);
if (res.equals(EXIT)) {
break;
} else {
System.out.println(res);
}
}
}
private String runCalc(Scanner s) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.println("Enter your choice: ");
int i = s.nextInt();
if (i == 5) {
return EXIT;
}
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;// 'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
return "Wrong Choice.";
}
return "Answer is " + result;
}
}
There is more than one way to achieve this, you can use
while loop.
do-while loop.
for loop.
I think do-while loop is better for your situation. Because either user wants to continue or not you have to proceed one time(before loop false). And you do not want to use another variable for quit the loop.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int result=0;
do{
System.out.println("Main Menu:");
System.out.println("-1. complete and calculate");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
if(i ==-1){
System.out.println("Answer is "+result);
return;
}
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
break;
}
}while(true);
}

Exiting switch back to main method

I have a method which uses a switch statement to give the user options to select, once they have selected an option and the code in the case has been executed how do I get back into the main method which offers another menu?
Part of my code:
static void modifyStudent() {
System.out.println("Wish student would you like to change?");
for(int i=0;i<10;i++){
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
System.out.println("1: Change name.");
....
int detailChange = input.nextInt();
switch (detailChange) {
case 1:
String newName = input.next();
studentNamesArray[studentChoice] = newName;
break;
....
}
public static void main(String[] args) {
while (1 == 1) {
System.out.println("Please select an option:");
System.out.println("1: Add a student.");
....
int choice = input.nextInt();
switch (choice) {
case 1:
....
}
EDIT (full code requested):
/**
* User: Colin Shewell
* Date: 26/11/13
* Time: 10:32
*/
import java.util.Scanner;
import java.util.Arrays; //REMOVE THIS!!!
public class StudentMarks {
static Scanner input = new Scanner(System.in);
static String[] studentNamesArray = new String[10];
static int[][] studentMarksArray = new int[10][3];
static int nameArrayCount, markArrayCount = 0;
static int markOne, markTwo, markThree;
static String studentName;
static void printArrays(){
System.out.println(Arrays.toString(studentNamesArray));
for (int index=0;index<10;index++)
{
System.out.println(studentMarksArray[index][0]);
System.out.println(studentMarksArray[index][1]);
System.out.println(studentMarksArray[index][2]);
}
}
static void addStudent() {
if (nameArrayCount < 10) {
System.out.println("Enter the student's name in the following format - surname, forename: ");
studentName = input.next();
studentNamesArray[nameArrayCount] = studentName;
nameArrayCount = nameArrayCount + 1;
}
else if (nameArrayCount == 10) {
System.out.println("******Array is full, please delete a student before adding another.*****");
}
if (markArrayCount < 10){
System.out.println("Enter the first mark: ");
markOne = input.nextInt();
System.out.println("Enter the second mark: ");
markTwo = input.nextInt();
System.out.println("Enter the third mark: ");
markThree = input.nextInt();
studentMarksArray[markArrayCount][0] = markOne;
studentMarksArray[markArrayCount][1] = markTwo;
studentMarksArray[markArrayCount][2] = markThree;
markArrayCount = markArrayCount + 1;
}
}
static void modifyStudent() {
System.out.println("Wish student would you like to change?");
for(int i=0;i<10;i++){
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
System.out.println("1: Change name.");
System.out.println("2: Change first mark.");
System.out.println("3: Change second mark.");
System.out.println("4: Change third mark.");
System.out.println("5: Change all marks.");
int detailChange = input.nextInt();
switch (detailChange) {
case 1:
System.out.println("Enter the new student name.");
String newName = input.next();
studentNamesArray[studentChoice] = newName;
return;
case 2:
System.out.println("Enter the new mark for mark one.");
int newMarkOne = input.nextInt();
studentMarksArray[studentChoice][0] = newMarkOne;
return;
case 3:
//two
break;
case 4:
//three
break;
case 5:
//all
break;
default:
System.exit(0);
break;
}
}
public static void main(String[] args) {
while (true) {
System.out.println("Please select an option:");
System.out.println("1: Add a student.");
System.out.println("2: Modify the details of an existing student.");
System.out.println("3: Delete an existing student.");
System.out.println("4: Sort in alphabetical order by name.");
System.out.println("5: Output the student name and corresponding marks in ascending name order.");
System.out.println("6: Output the student name and corresponding marks in descending name order.");
System.out.println("7: Display the student with the highest average mark.");
System.out.println("8: Display the student with the lowest average mark.");
System.out.println("9: Display the average score of all students recorded.");
System.out.println("10: Exit.");
int choice = input.nextInt();
switch (choice) {
case 1:
addStudent();
System.out.println(Arrays.toString(studentNamesArray));
break;
case 2:
modifyStudent();
break;
case 3:
printArrays();
break;
/* case 4:
sortAlphabetical();
break;
case 5:
outputNameMarksAsc();
break;
case 6:
outputNameMarksDsc();
break;
case 7:
highestStudentAvgMark();
break;
case 8:
lowestStudentAvgMark();
break;
case 9:
displayAvgScore();
break; */
case 10:
System.exit(0);
break;
default:
System.exit(0);
break;
}
}
}
}
Just return to the main method. return just exits the method and continues executing code from the line it was called.
case 1:
String newName = input.next();
studentNamesArray[studentChoice] = newName;
return; //exits this method
//break; <-- not needed after a return!
Your code will run in an infinite loop, you can make it run with a conditional flag like this
boolean isRunning = true;
while (isRunning) {
System.out.println("Please select an option:");
System.out.println("1: Add a student.");
....
int choice = input.nextInt();
switch (choice) {
case 1:
isRunning = false;
//your code for case 1
....
}
//rest of the code in main executes now
This will exit the while loop back to the main method

Need assistence displaying value from a different private class

Okay, first off I am very, very new to java. For this project I need to design a program that takes a product number, an amoutn sold, calculates the total, and then displays it. However, I need to to display when I select option 2, which is a seperate private class, to be honest I don't even know where to begin. Any help would be appreciated.
import java.util.Scanner;
public class Attempt1
{
//method to pause until a key is pressed
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}//end pause
public static void main(String[] args)
{
//variables to capture keyboard input
Scanner keyBd = new Scanner( System.in );
char selection;
//int selection;
do{//display menu
System.out.println("\n--------------");
System.out.println("Retail Sales\n");
System.out.println("1. Enter Products Sold");
System.out.println("2. Display Total Retail Sales");
System.out.println("3. Exit\n");
System.out.print ("Selection: ");
//get menu selection
selection = keyBd.next().charAt(0);
//selection = keyBd.nextInt();
//process menu selection
switch (selection){
case '1':
enterProducts();
break;
case '2':
displaySales();
break;
case '3':
//recognize as valid selection but do nothing
break;
default :
//System.out.printf("%c\n",7);
System.out.println("Invalid Selection");
}//end switch
}while( selection != '3');
}//end main()
private static void enterProducts()
{
Scanner inp = new Scanner(System.in);
int product,quantity;
double total = 0.00;
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
while(product !=0)
{
System.out.print("Enter quantity: ");
quantity=inp.nextInt();
switch( product ){
case 1:total+=quantity*2.98;
break;
case 2:total+=quantity*4.50;
break;
case 3:total+=quantity*3.98;
break;
case 4:total+=quantity*4.49;
break;
case 5:total+=quantity*6.87;
break;
default:System.out.println("Invalid Product Number");
System.out.println("Product Number Does not Exist");
if(product<0 && product>=6)
{
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
System.out.print("Enter quantity: ");
quantity=inp.nextInt();
}
break;
}
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
}
pause();
}
private static void displaySales()
{
System.out.println( "The total retail value was: " + total );
pause();
}
}//end MenuDemo
Here is an algorithm for improving your code:
At the beginning of your your main add a variable total and initialize it with 0: double total=0;
Change the enterProducts method's return type to double: private static double enterProducts() and return the local variable total at the end from this method after the call to pause: return total;
In the case for the input of 1 add the returned value from enterProducts to the current value of total (it's the total inside your main): total += enterProducts();
Add to the method displaySales an double argument: private static void displaySales(double total) and change the call to it in the main's case for 2 to displaySales(total);
I think you mean private method. You could pass the total like so:
private static void displaySales(double total) {
...
total is defined in enterProducts but not in the main method where the loop is displayed, so you could return this:
double enterProducts() {
...
return total;
}
so that you can pass it to displaySales.
The problem with the code is that you're trying to access a local variable, declared in the static enterProducts() method, inside of the static displaySales() method.
The code below solves that "problem".
With that being said, I recommend that you work through some Java tutorials to understand why the code now works... Have a look at Variable Scope.
public class Attempt1
{
//use a static variable to store the total
static double total = 0.00;
//method to pause until a key is pressed
public static void pause()
{
try
{
System.out.print("Press <Enter> to continue...");
System.in.read();
}
catch (Exception e)
{
System.err.printf("Error %s%c\n",e.getMessage(),7);
}
}//end pause
public static void main(String[] args)
{
//variables to capture keyboard input
Scanner keyBd = new Scanner( System.in );
char selection;
//int selection;
do{//display menu
System.out.println("\n--------------");
System.out.println("Retail Sales\n");
System.out.println("1. Enter Products Sold");
System.out.println("2. Display Total Retail Sales");
System.out.println("3. Exit\n");
System.out.print ("Selection: ");
//get menu selection
selection = keyBd.next().charAt(0);
//selection = keyBd.nextInt();
//process menu selection
switch (selection){
case '1':
enterProducts();
break;
case '2':
displaySales();
break;
case '3':
//recognize as valid selection but do nothing
break;
default :
//System.out.printf("%c\n",7);
System.out.println("Invalid Selection");
}//end switch
}while( selection != '3');
}//end main()
private static void enterProducts()
{
Scanner inp = new Scanner(System.in);
int product,quantity;
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
while(product !=0)
{
System.out.print("Enter quantity: ");
quantity=inp.nextInt();
switch( product ){
case 1:total+=quantity*2.98;
break;
case 2:total+=quantity*4.50;
break;
case 3:total+=quantity*3.98;
break;
case 4:total+=quantity*4.49;
break;
case 5:total+=quantity*6.87;
break;
default:System.out.println("Invalid Product Number");
System.out.println("Product Number Does not Exist");
if(product<0 && product>=6)
{
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
System.out.print("Enter quantity: ");
quantity=inp.nextInt();
}
break;
}
System.out.print("Enter product #(1-5)(0 to stop): ");
product=inp.nextInt();
}
pause();
}
private static void displaySales()
{
System.out.println( "The total retail value was: " + total );
pause();
}
}//end MenuDemo

Categories

Resources