Im facing problem when i use to run this program.this is continuously repeating the case 1 .`
import java.util.Scanner; //importing
public class DynamicStackByArray { // name of class
private static String[] a;
private static int size;
public DynamicStackByArray(){} // end of the null constructor
public DynamicStackByArray(int capacity){
a=new String[capacity];
}// end of the parameterized constructor
private static String peek(){
if(size==0)
throw new IllegalStateException("Stack is Empty");
else
return a[size-1];
}// end of the displaying method
private static String pop(){
if(size==0)
throw new IllegalStateException("Stack is Empty...");
else{
String o=a[--size];
a[size]=null;
return o;
}
}// end of the pop method
private static void push(String o){
if(size==a.length)resize();
else
a[size++]=o;
}// end of the push method
private static void resize(){
String aa[]=a;
a=new String[1+aa.length];
System.arraycopy(aa, 0, a, 0, size);
aa=null;
}// end of the resize method
public static void main(String[] args){
Scanner in=new Scanner(System.in);
System.out.println("Enter the size of dynamic stack :");
int cap=in.nextInt();
DynamicStackByArray d=new DynamicStackByArray(cap);
System.out.println("Enter your choice \n1) for push\n2) for pop\n3) for peek");
System.out.println("Enter -999 to exit");
int choice=in.nextInt();
while(choice!=-999){
switch(choice){
case 1:{
System.out.println("Enter your desire data");
System.out.println("Note that -999 will let u escape out of it... :)");
String input;
input=in.nextLine();
String as="-999";
if(!input.equalsIgnoreCase(as)){
d.push(input);
}// end of checker
System.out.println("Enter your choice \n1) for push\n2) for pop\n3) for peek");
System.out.println("Enter -999 to exit");
choice=in.nextInt();
break;
}// end of case 1
case 2:{
System.out.println("Value "+d.peek()+" has been poped ");
d.pop();
System.out.println("Enter your choice \n1) for push\n2) for pop\n3) for peek");
System.out.println("Enter -999 to exit");
choice=in.nextInt();
break;
}// end of the case 2
case 3:{
System.out.println("Value "+d.peek()+" has been peeked");
System.out.println("Enter your choice \n1) for push\n2) for pop\n3) for peek");
System.out.println("Enter -999 to exit");
choice=in.nextInt();
break;
}// end of the case 3
default:{
System.out.println("Sorry this is a wrong choice...");
System.out.println("Enter your choice \n1) for push\n2) for pop\n3) for peek");
System.out.println("Enter -999 to exit");
choice=in.nextInt();
break;
}// end of default
}// end of the switch statement
}// end of the repetation of the program
System.out.println("GOOD BYE... !!!");
}// end of the main method
}// end of the class
`
you forgot to ask scanner for input inside your loop. You can fix it :
int choice = 0;
while ((choice = in.nextInt()) != -999) {
//... your loop
}
One more important thing :
in case 1: when you read input=in.nextLine(); it will consume \n symbol that was used to terminate "1" input and your String input will be always empty string. (just put a breakpoint and verify it yourself)
Therefore, you have to add extra nextLine() statement inside case 1:
in.nextLine(); // read `\n` symbol;
String input = in.nextLine();
It is not executing just case1 all the time. The program is running correct. You just made mistake by take peek method in both cases, u should use pop method in case2 as u desired for.
Related
I have a project that I want it to go back to the first menu if it is selected from the second menu.
The following is just an example:
import java.util.Scanner;
public class SAMPLE {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
This is the first menu:
System.out.println("Enter choice: ");
System.out.println("1 = A");
System.out.println("2 = B");
int choice1 = input.nextInt();
do {
This is the second menu:
System.out.println("Another choice:");
System.out.println("1 = C");
System.out.println("2 = D");
System.out.println("3 = Go back");
int choice2 = input.nextInt();
switch (choice2) {
case 1: System.out.println("nice");
break;
case 2: System.out.println("nicee");
break;
If I selected 3, it should go back to the first menu but I don't know how.
case 3: System.out.println("How can I go back to the first menu? HELP!");
break;
}
} while (choice1 > 2);
System.out.println("END OF THE PROGRAM");
}
}
I would suggest splitting your code into functions.
Upon case 3 - You shall call your new function.
Something like this:
static int mainMenu(Scanner inputScanner)
{
System.out.println("Enter choice: ");
System.out.println("1 = A");
System.out.println("2 = B");
return inputScanner.nextInt(); //Assume valid input. you should add a valid check
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Choice1 = mainMenu(input);
do {
System.out.println("Another choice:");
System.out.println("1 = C");
System.out.println("2 = D");
System.out.println("3 = Go back");
int Choice2 = input.nextInt();
switch (Choice2) {
case 1: //DO Y
break;
case 2: //DO X
break;
case 3: Choice1 = mainMenu(input);
break;
}
} while (Choice1 > 2);
//END logic
}
Aha You want to go back to the first menu of choosing A and B in the process of choosing C and D!
There are many ways(such as use another method or recursion),
but I recommend this method which will be easier to understand now.
First, Let's check the code to organize what we want to do
<I changed it slightly to make it more recognizable! I'm sorry!>
import java.util.Scanner;
public class StackOver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
////main_menu///-Select A or B
System.out.println("Please input Enter Choice: ");
System.out.println("input '1' to Select A");
System.out.println("input '2' to Select B");
int choice1 = input.nextInt();
////////////////////////////
////second_Menu Choose C or D, or Back to main_menu
System.out.println("Another choice: ");
System.out.println("input '1' to Select C");
System.out.println("input '2' to Select D");
System.out.println("input '3' to Go back");
int choice2 = input.nextInt();
//According to 'choice2'
switch(choice2) {
case 1: System.out.println("nice, you Select C");
break;
case 2: System.out.println("nicee, you Select D");
break;
case 3: System.out.println("Now, you can go to Back");
break;
}
//I'm sorry, but I can't understand the meaning of
//'while (choice1 > 2);' ㅠㅅㅠ
System.out.println("END OF THE PROGRAM");
}
}
So the code above is the one you asked for, right?
There are so many ways to implement it in the direction you want.
Let's try to get it back to the main menu through the While statement you were trying to use.
The code progresses.
(1) Choosing A and B
(2) Choosing C and D or (1)
It consists of going to (1) or ending the program, depending on the result of (2).
how about use do{ }while(boolean);??
The process in do{} will continue until 'boolean' is false.
now We can change code in this way
import java.util.Scanner;
public class StackOver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int choice2 = 0; //init for NullPointerError
do {
//below do{
////main_menu///-Select A or B
System.out.println("Please input Enter Choice: ");
System.out.println("input '1' to Select A");
System.out.println("input '2' to Select B");
int choice1 = input.nextInt();
////////////////////////////
////second_Menu Choose C or D, or Back to main_menu
System.out.println("Another choice: ");
System.out.println("input '1' to Select C");
System.out.println("input '2' to Select D");
System.out.println("input '3' to Go back");
choice2 = input.nextInt();
//According to 'choice2'
switch(choice2) {
case 1: System.out.println("nice, you Select C");
break;
case 2: System.out.println("nicee, you Select D");
break;
case 3: System.out.println("Now, you can go to Back");
break;
}
}while(choice2 == 3);
//if choice2 == 3, then the progress of code return back to below 'do{'
System.out.println("END OF THE PROGRAM");
}
}
This is the result of the changed code.
I hope you understood it well and If there's anything that's hard to understand, please leave a comment!
I hope you have a pleasant and peaceful day today.😻😻
So basically in the case 1 of main function, I am trying to store the two values the user input into another class. Then if I go to case 2 immediately, the output will be the sum of the two values that were input earlier. My question is how to change my code such that case 2 and 3 are able to use the values that I have stored in case 1 earlier? Thank you.
Code for main function:
import java.util.Scanner;
public class calculatorfinal
{
public static void main(String args[])
{
int number1,number2,choice,sum,product;
while(true)
{
Scanner scan = new Scanner(System.in);
operations myoperations=new operations();
System.out.println("\n1. Get numbers");
System.out.println("\n2. Addition");
System.out.println("\n3. Multiplication");
System.out.println("\n4. Exit");
choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("enter the two numbers:");
number1=scan.nextInt();
number2=scan.nextInt();
myoperations.getnumbers(number1,number2);
break;
case 2:
myoperations.addnumbers();
break;
case 3:
myoperations.multiplynumbers();
break;
case 4:
System.exit(0);
break;
}
}
}
}
Code for another class(the operations)
public class operations
{
int a,b;
public void addnumbers()
{
int sum = a+b;
System.out.println("ans is "+sum);
}
public void multiplynumbers()
{
int product = a*b;
System.out.println("ans is "+product);
}
public void getnumbers(int number1,int number2)
{
a=number1;
b=number2;
System.out.println("the first number is "+number1);
System.out.println("the second number is "+number2);
}
}
The problem is that you discard your variable myoperations every time the while-loop ends and creating a new myoperations. Your variable has to stay outside the loop like your ints do. Also the Scanner should stay outside, as long as you do not want to let the garbage collector work unnecessarily.
public static void main(String args[]) {
int number1, number2, choice, sum, product;
operations myoperations = new operations();
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("\n1. Get numbers");
System.out.println("\n2. Addition");
System.out.println("\n3. Multiplication");
System.out.println("\n4. Exit");
choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("enter the two numbers:");
number1 = scan.nextInt();
number2 = scan.nextInt();
myoperations.getnumbers(number1, number2);
break;
case 2:
myoperations.addnumbers();
break;
case 3:
myoperations.multiplynumbers();
break;
case 4:
System.exit(0);
break;
}
}
}
You just have to use the initialisation operations myoperations=new operations(); outside of the while loop. Otherwise you override the instance of the class each time. And so your stored values get lost each time you choose a case.
1.Make your instance variable static to avoid reinitialization
import java.util.Scanner;
class operations
{
static int a,b; //Add static KeyWord
public void addnumbers()
{
int sum = a+b;
System.out.println("ans is "+sum);
}
public void multiplynumbers()
{
int product = a*b;
System.out.println("ans is "+product);
}
public void getnumbers(int number1,int number2)
{
a=number1;
b=number2;
System.out.println("the first number is "+number1);
System.out.println("the second number is "+number2);
}
}
2.Write operations myoperations=new operations(); line out of while loop
class Main {
public static void main(String args[])
{
int number1,number2,choice,sum,product;
Scanner scan = new Scanner(System.in);
operations myoperations=new operations();
while(true)
{
//Scanner scan = new Scanner(System.in);
//operations myoperations=new operations();
System.out.println("\n1. Get numbers");
System.out.println("\n2. Addition");
System.out.println("\n3. Multiplication");
System.out.println("\n4. Exit");
choice = scan.nextInt();
switch(choice)
{
case 1:
System.out.println("enter the two numbers:");
number1=scan.nextInt();
number2=scan.nextInt();
myoperations.getnumbers(number1,number2);
break;
case 2:
myoperations.addnumbers();
break;
case 3:
myoperations.multiplynumbers();
break;
case 4:
System.exit(0);
break;
}
}
}
}
the following code terminate after try catch block catches exception.its not allowing me to make choice from the menu option. so my question is what changes do i have to make on this code so that i can loop back so that i can get user input again.
public class Main {
public static void main(String[] args) {
Modify modifyObj = new Modify();
int choice = 0 ;
Scanner input = new Scanner(System.in);
//begin loop
do {
try{
//display menu
System.out.println("Choose one option from following option available: ");
System.out.println("0) Exit program. ");
System.out.println("1) Create a Roster");
System.out.println("2) Modify a Roster");
System.out.println("3) Delete a Roster");
choice = input.nextInt(); //gets user input
switch (choice) {
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
}// end of switch statement
break;
}//end oftry
catch(InputMismatchException inputMismatchException){
System.out.println("Enter integer value between 0 and 7:");
continue;
}
}while (choice!=0); //loop until user exit 0.
}//end of main
}// end of Main class
Make sure choice isn't 0 before you continue;
catch(InputMismatchException inputMismatchException){
System.out.println("Enter integer value between 0 and 7:");
choice = 1; // <-- not 0.
continue;
}
Note that you default choice to an initial value of 0.
You Could Use Methods
If you extracted your logic into one (or two) utility methods to display the menu and get the user's choice it would simplify things; something like
private static void showMenu() {
System.out.println("Choose one option from following option available: ");
System.out.println("0) Exit program. ");
System.out.println("1) Create a Roster");
System.out.println("2) Modify a Roster");
System.out.println("3) Delete a Roster");
}
private static int getUserOption(Scanner input) {
while (true) {
showMenu();
if (input.hasNextInt()) {
int t = input.nextInt();
switch(t) {
case 0: case 1: case 2: case 3:
return t;
}
} else {
input.nextLine();
}
}
}
Then your main could invoke it like
public static void main(String[] args) {
Modify modifyObj = new Modify();
Scanner input = new Scanner(System.in);
int choice;
// begin loop
do {
choice = getUserOption(input);
if (choice != 0) {
System.out.printf("You chose %d.%n", choice);
}
} while (choice != 0); // loop until user enters 0.
}// end of main
I'm currently creating my first game which is executed in a console.
I've been asked to validate an input which can be done with a simple code. The goal is to input, and then validate if that number is an integer, and is on a range of 1-4. If possible, the problem should be solved with basic algorithm.
The problem is that it won't give me the result I wanted. It works when I enter a string, but it loops on every number I put including the number in the range. Does anyone know why?
public class Menu {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int input = 0;
int min = 1;
int max = 4;
boolean inputValidate;
System.out.println("Main Menu");
System.out.println("=========");
System.out.println("1. Play Game");
System.out.println("2. About");
System.out.println("3. View Saved Games");
System.out.println("4. Exit");
System.out.println("");
do {
System.out.print(">> ");
if (!scanner.hasNextInt()) {
inputValidate = false;
System.out.println("Not a number. Please input number 1-4.");
scanner.nextLine();
} else if (input <= max && !(input < min)) // if input <= 4 and input is not less than 1
{
input = scanner.nextInt();
inputValidate = true;
} else {
inputValidate = false;
System.out.println("Not in range. Please input number 1-4.");
scanner.nextLine();
}
} while (!(inputValidate));
switch (input) {
case 1:
break;
case 2:
System.out.println("Good work!");
break;
case 3:
break;
case 4:
break;
}
}
}
}
Because you instantiate input to be 0, but never give the user an opportunity to change this, the conditions for the first two conditionals are always false (nothing is read from the Scanner and 0 is not between min and max). Therefore, the program falls through to the else every time. Just add a statement before the do-while that will obtain a value for input from the user.
input = scanner.nextInt();
// your do-while loop
(You'll also probably have to adjust the code slightly to get the type of interaction you're looking for. Hint - you're reading two values from the user.)
As Clint said the problem was in your input. Here's a demo how you can fix this,
try (Scanner scanner = new Scanner(System.in)) {
int input = 0;
int min = 1;
int max = 4;
boolean inputValidate = false;
System.out.println("Main Menu");
System.out.println("=========");
System.out.println("1. Play Game");
System.out.println("2. About");
System.out.println("3. View Saved Games");
System.out.println("4. Exit");
System.out.println("");
do {
System.out.print(">> ");
try {
input = scanner.nextInt();
if (input >= min && input <= max) {
inputValidate = true;
} else {
System.out
.println("Not in range. Please input number 1-4.");
scanner.nextLine();
}
} catch (InputMismatchException exception) {
System.out
.println("Not a number. Please input number 1-4.");
scanner.nextLine();
}
} while (!(inputValidate));
I am working on an example using a do-while loop and switch statement. What I basically need is to accumulate numbers and depending on user input either add, substract, multiply or divide (mini calculator type).
The problem is when I ask the user to go back to the main menu the program does not reset the value as it is before the loop. The result is always the previous result.
Here is the code, it will explain it better.
import java.util.Scanner;
public class SwitchLoopNumbers{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int numbers=0;
int result=0;
int option;
boolean quit = true;
String done="";
do{
System.out.println("CALCULATOR MENU");
System.out.println("********** ****");
System.out.println("\n1. Add");
System.out.println("2. Substract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println();
System.out.print("Enter your option >> ");
option = scan.nextInt();
while(quit){
switch(option){
case 1:
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
if(numbers==0)
quit=false;
result +=numbers;
break;
case 2:
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
result -=numbers;
if(numbers==0)
quit=false;
break;
}
}
System.out.println("The total is: "+result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
//I did reset numbers and result here to zero but it did not work
}
while("y".equalsIgnoreCase(done));
System.out.println("Thank you for using calculator");
}
}
A couple things are going on here. To answer your question concisely, it's because you didn't reassign your variables before re-looping. Since you don't reassign result and quit, quit is false so it closes the loop, and result is unchanged so it then prints the same result. Try this:
System.out.println("The total is: "+result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
numbers = 0;
result = 0;
quit = true;
I think it's the most straight-forward solution to your problem.
EDIT: I also wanted to add that using quit as the while condition seems a little counter-intuitive. If I saw a condition quit that was true, my assumption would be that it would break the loop, not continue it. You might make your code a bit clearer by designating more meaningful variable names. So instead of saying something like:
boolean quit = true;
while(quit) {
//do stuff
if (some_condition) {
quit = false;
//close loop
}
}
This may be a little clearer:
boolean quit = false;
while(!quit) {
//do stuff
if (some_condition) {
quit = true;
//close loop
}
}
Just a general suggestion.
You can try to call main() again, but I'm not sure if it will work, solution can be make your own method eg. init() - where you will set vars into init state, and eg. work(), what will be remaining code :D
EDIT: you can make it this way
import java.util.Scanner;
public class main {
//if you want work with result after user will write "y" in the end
static int result = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numbers = 0;
int option;
boolean quit = false;
String done = "";
//int result = 0; // if you want also init result
// menu
System.out.println("CALCULATOR MENU");
System.out.println("********** ****\n");
System.out.println("1. Add");
System.out.println("2. Substract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
// user menu input read
System.out.println();
System.out.print("Enter your option >> ");
option = scan.nextInt();
switch (option) {
case 1:
while (!quit) {
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
if (numbers == 0) {
quit = true;
}
result += numbers; // result = result + numbers
}
break;
case 2:
while (!quit) {
System.out.print("Enter numbers, type 0 when done >> ");
numbers = scan.nextInt();
result -= numbers; // result = result - numbers
if (numbers == 0) {
quit = true;
}
}
break;
default:
System.out.println("Bad inpout");
break;
}
System.out.println("The total is: " + result);
System.out.println("Back to main menu ? y/n ");
scan.nextLine();
done = scan.nextLine();
//recursive call - run main() again
if (done.equals("y")) {
main(args);
} else {
System.out.println("Thank you for using calculator");
}
}
}