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);
}
Related
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/
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;
}
}
}
I'm not able to understand that why is the compiler just shows running(which is forever) when I change char to int in this program. By changing I mean using just int to take the option number and hence using int numbers itself in switch.
This one is normal char 1 which is working-
public static void main(String args[])
throws java.io.IOException{
char option; int i=0;
do{
if(i==1)
System.out.println("\nNotice: Wrong option chosen, pick again.");
i=1;
System.out.println("Help on:");
System.out.println("1. if");
System.out.println("2. switch");
System.out.println("3. while");
System.out.println("4. do-while");
System.out.println("5. for");
System.out.println("Pick any option for brief informatrion.");
option= (char)System.in.read();
}while(option<'1' || option>'5');
switch(option){
case '1':
System.out.println("The If:\n");
System.out.println("If(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The Switch:\n");
System.out.println("switch(expression){");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The While:\n");
System.out.println("while(condition statement;)");
break;
case '4':
System.out.println("The Do-While:\n");
System.out.println("do{");
System.out.println(" statement;");
System.out.println("}while(condition);");
break;
case '5':
System.out.println("The For:\n");
System.out.println("for(init; condition; iteration){");
System.out.println(" statement;");
System.out.println("}");
break;
}
}
}
This is int 1 which just keeps running forver
public static void main(String args[])
throws java.io.IOException{
int option; int i=0;
do{
if(i==1)
System.out.println("\nNotice: Wrong option chosen, pick again.");
i=1;
System.out.println("Help on:");
System.out.println("1. if");
System.out.println("2. switch");
System.out.println("3. while");
System.out.println("4. do-while");
System.out.println("5. for");
System.out.println("Pick any option for brief informatrion.");
option= System.in.read();
}while(option<1 || option>5);
switch(option){
case 1:
System.out.println("The If:\n");
System.out.println("If(condition) statement;");
System.out.println("else statement;");
break;
case 2:
System.out.println("The Switch:\n");
System.out.println("switch(expression){");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case 3:
System.out.println("The While:\n");
System.out.println("while(condition statement;)");
break;
case 4:
System.out.println("The Do-While:\n");
System.out.println("do{");
System.out.println(" statement;");
System.out.println("}while(condition);");
break;
case 5:
System.out.println("The For:\n");
System.out.println("for(init; condition; iteration){");
System.out.println(" statement;");
System.out.println("}");
break;
}
}
}
See https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read%28%29
The System.in.read return an int represent for character.
Let's say you type 1, it will read as 49.
And if you use file to be stdin when it reach EOF it will return -1
Even if the char version, the same error happens.
See this demo: https://ideone.com/Q83qxn
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
I have been struggling with this for a while. I essentially want to loop through and read in as many strings as determined by num_choices. The following code only executes the else condition.
Scanner s2 = new Scanner(System.in);
for(int i=0; i < this.num_choices; i++)
{
if(s2.hasNext())
{
System.out.println("Enter choice " + (i+1) +":");
String ch = s2.next();
//this.choices.addElement(ch);
}
else
{
System.out.println("Lets end this");
}
}
`
I am getting this: Exception in thread "main" java.util.NoSuchElementException. In the main class, this is where the error points to
choice2 = Integer.parseInt(read_choice2.next());
which is inside a while loop as well. Here is the code for that:
public class Main
{
public static void main(String args[]) throws IOException
{
Vector<Survey> mysurveys = new Vector<Survey>();
boolean carry_on = true;
int choice = 0;
Scanner read_choice = new Scanner(System.in);
System.out.println("Let's begin the Survey/Test application!");
while(carry_on)
{
System.out.println("What would you like to do?");
System.out.println("1. Create a new Survey");
System.out.println("2. Create a new Test");
System.out.println("3. Display a Survey");
System.out.println("4. Display a Test");
System.out.println("5. Save a Survey");
System.out.println("6. Save a Test");
System.out.println("7. Load a Survey");
System.out.println("8. Load a Test");
System.out.println("9. Quit");
System.out.println();
System.out.println("Please enter a number for the operation you want to perform: ");
choice = Integer.parseInt(read_choice.next());
/*try
{
choice = Integer.parseInt(buffer.readLine());
}
catch(InputMismatchException e)
{
System.out.println("Invalid input. Please Enter again.");
System.out.println();
//read_choice.nextInt();
}*/
switch(choice)
{
case 1:
System.out.println("Please Enter a Name for your Survey");
String in = buffer.readLine();
Survey s1 = new Survey();
s1.CreateNew(in);
mysurveys.add(s1);
////
add_question(s1.type);
break;
case 2:
System.out.println("Please Enter a Name for your Test");
//String in = buffer.readLine();
Test t1 = new Test();
//t1.CreateNew(in);
mysurveys.add(t1);
break;
////
//add_question(t1.type);
case 3:
break;
// call Survey.display()
case 4:
break;
case 5:
Survey s = new Survey();
ReadWriteFiles x = new ReadWriteFiles();
x.SaveSurvey(s);
break;
case 6:
Test t = new Test();
//ReadWriteFiles x = new ReadWriteFiles();
//x.SaveSurvey(t);
break;
case 7:
carry_on = false;
break;
default:
System.out.println("Incorrect Input. Try Again");
System.out.println();
break;
}
}
read_choice.close();
}
public static void add_question(String type) throws IOException, NullPointerException
{
Questions q = null;
boolean carry_on2 = true;
int choice2 = 0;
Scanner read_choice2 = new Scanner(System.in);
//BufferedReader buffer2=new BufferedReader(new InputStreamReader(System.in));
while (carry_on2)
{
//
System.out.println("1. Add a new T/F Question");
System.out.println("2. Add a new Multiple Choice Question");
System.out.println("3. Add a new Short Answer Question");
System.out.println("4. Add a new Essay Question");
System.out.println("5. Add a new Ranking Question");
System.out.println("6. Add a new Matching Question");
System.out.println("7. If you want to stop adding more questions, and go back to the main menu.");
System.out.println("Please enter a number for the operation you want to perform: ");
choice2 = Integer.parseInt(read_choice2.next());
/*try
{
choice2 = Integer.parseInt(buffer2.readLine());
}
catch(InputMismatchException e)
{
System.out.println("Invalid input. Please Enter again.");
System.out.println();
//read_choice2.nextInt();
}*/
switch(choice2)
{
case 1:
q = new TrueFalse();
break;
case 2:
q = new MultipleChoice();
break;
case 3:
q = new ShortAnswer();
break;
case 4:
q = new Essay();
break;
case 5:
q = new Ranking();
break;
case 6:
q = new Matching();
break;
case 7:
carry_on2 = false;
break;
default:
System.out.println("Incorrect Input.");
break;
}
q.createQuestion(type);
}
}
}
I realize there is a lot of messy code, and I apologize for that. I just wanted to show the entire thing, so it's easier to spot the problem. Help would be appreciated.
In general way, you should add if(read_choice.hasNext()) before invoking read_choice.next(); You have the exception java.util.NoSuchElementException because no elements found to be read. this is a good habit.
About your problem, you are getting error because you has closed scanner before finish reading. Put read_choice.close() outside of loop.
Moreover, for simplify, if you want to read integer, just simple : scanner.nextInt().
read_choice.close();
Don't close the scanner as long as you are not done reading all the inputs. Doing also closes the underlying input stream (System.in), check the documention;
You don't need to initialize the Scanner multiple times. Just create one instance and pass it around (keep using it).
Also,
for(int i=0; i < this.num_choices; i++)
{
//if(s2.hasNext())
//{
System.out.println("Enter choice " + (i+1) +":");
String ch = s2.next();
//this.choices.addElement(ch);
you don't need that condition check. The next() will block until the input is entered.