Java Switch Statement: creating a calculator error - java

I was wondering if anyone can see what is wrong with my code. It works except that the program is not acknowledging my switch statement - I searched lots of questions but as I am a novice I am clearly missing something.
import java.util.Scanner;
class Calmlr1 {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String anotherOption = "y", operatorOpt= "a";
int no1=0, no2=0;
double result= 0;
System.out.println ("Welcome to the online calculator! Let's begin...");
while (anotherOption.equalsIgnoreCase ("y")) {
System.out.println ("Please enter your 1st number: ");
no1 = input.nextInt();
System.out.println ("Please confirm your operator:\n1 = +\n2 = - \n3 = *\n4 = /");
operatorOpt = input.next ();
System.out.println ("Please enter your 2nd number: ");
no2 = input.nextInt();
switch(no1) {
case 1:
result=no1+no2;
break;
case 2:
result=no1-no2;
break;
case 3:
result=no1*no2;
break;
case 4:
result=no1/no2;
default:
result = 0 ;
break;
}
System.out.println("Your total calculation is: "+result);
System.out.println("Would you like to do another sum? y/n ");
anotherOption=input.next();
}
}
}

You should be using switch(operatorOpt). Right now you are switching on the first number.
You also need to change:
int operatorOpt= 0;
operatorOpt = input.nextInt();
That is, if you want to keep your switch statement the same. Please also see #Daniel Imms answer for an additional bug fix.

Try adding a break at the end of case 4
case 4:
result=no1/no2;
break;
EDIT J L's answer is the main issue, but this is another problem that will break division.

Your switch should be on the operatorOpt and not on no1.
Also, you're missing a break in the case 4. So, if you want to do a division, you'll get 0 as result.
The input from the user for operatorOpt should be done with input.nextLine(). Or, if you want to keep the same switch statement, with input.nextInt().
It should be like this:
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}

Your switch statement should be on "operatorOpt" and not on "no1" as you suppose to check the operator and based on that you want to do the calculation. However, you must use JDK1.7 to use String in Switch statement since previous versions of JDK do not support String Switch.
Also, you should use "break" in case 4.

Your switch should be on the operatorOpt and not on no1.
You can use like this
switch(operatorOpt)
{
case "+":
result=no1+no2;
break;
case "-":
result=no1-no2;
break;
case "*":
result=no1*no2;
break;
case "/":
result=no1/no2;
break;
default:
result = 0 ;
break;
}

Related

How can I make the program stop after entering a value from a user?

I am trying to write a program that receives the number of sides from the
user and determines the type of figure using switch structure and a while sentinel-controlled loop, but every time I get an infinite loop. How can that be fixed?
import java.util.Scanner;
public class P1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of sides:");
int s = input.nextInt();
while ( s!=-1)
{
switch (s)
{
case 1: System.out.println("Line");
break;
case 2:System.out.println("Angle");
break;
case 3:System.out.println("Triangle");
break;
case 4:System.out.println("Quadrilateral");
break;
case 5:System.out.println("Pentagon ");
break;
case 6:System.out.println("Hexagon");
break;
case 7:System.out.println("Heptagon");
break;
case 8:System.out.println("Octagon");
break;
case 9:System.out.println("Nonagon");
break;
case 10:System.out.println("Decagon");
break;
default: System.out.println("Enter a valid value:");
}
}
}
}
The while loop is written to continue as long as s!=-1; so you need to change s so that this expression is no longer true.

Conditional wont be read in do while statement

For my program I am trying to have the loop run until the letter n is entered. But for some reason i keep receiving the error cannot find symbol in the condition for my loop. All help is greatly appreciated.
import java.io.*;
import java.util.*;
public class Prog213c
{
public static void main(String[] args) {
Scanner kbReader=new Scanner(System.in);
do{
System.out.println( "Enter student number");
int studentNumber = kbReader.nextInt();
System.out.println(" Enter credits ");
int credits = kbReader.nextInt();
switch (credits)
{
case 30:
System.out.println("Grade Level code = 2");
break;
case 29:
System.out.println("Grade Level code = 1");
break;
case 70:
System.out.println("Grade Level code = 3");
break;
case 103:
System.out.println("Grade Level code = 4");
break;
default: System.out.println("invalid number");
}
System.out.print("Do again(y/n)");
String answer = kbReader.next();
} while (answer == 'y'); // error received here
You have a few problems here:
String answer = kbReader.next();
} while (answer == 'y'); // error received here
Technically, answer is out of scope when you try to use - you can only use answer inside the loop itself. You should declare answer prior to starting your while loop so that it's in scope. Also, answer is a string and you're trying to "directly" compare it to a char.
This is also performing a case-sensitive comparison; while this isn't technically incorrect, it would be more user-friendly to accept accept either "Y" or "y".
Also, your switch statement won't work correctly. For example, case 30 will only be called if credits is exactly 30, which I assume isn't what you want.
You could do something like:
case 30:
case 31:
case 32: // ...
but that seems like a thoroughly painful way to do that. See also this question for more details.
This answer is particularly interesting and could be useful for your purposes. This is the code from that answer:
switch ((int) num/10) {
case 1:
System.out.println("10-19");
break;
case 2:
System.out.println("20-29");
break;
case 3:
System.out.println("30-39");
break;
case 4:
System.out.println("40-49");
break;
default:
break;
}
(Again, just to give credit where credit's due the above isn't my code, it was from the linked answer).
Also:
int studentNumber = kbReader.nextInt();
You never actually do anything with studentNumber, just prompt the user for it. Did you mean to do this?
Single quotes are character literals in Java. So you can't compare a
String with a char directly.
Your answer variable has to be declared before the do-while loop.
you have to use the equals method to compare strings.
answer.equals("y")
Problem 1:
since answer is a string object, this is not working (answer == 'y');
you can do "y".equals(answer) is you get the nextLine from the scanner
or if you need to work with chars
char x = kbReader.next().charAt(0);
while (x == 'y');
Problem 2:
answer must be declared before the do-while loop...
your final code can look like
Scanner kbReader = new Scanner(System.in);
char answer = 'y';
do {
System.out.println("Enter student number");
int studentNumber = kbReader.nextInt();
System.out.println(" Enter credits ");
int credits = kbReader.nextInt();
switch (credits) {
case 30:
System.out.println("Grade Level code = 2");
break;
case 29:
System.out.println("Grade Level code = 1");
break;
case 70:
System.out.println("Grade Level code = 3");
break;
case 103:
System.out.println("Grade Level code = 4");
break;
default:
System.out.println("invalid number");
}
System.out.print("Do again(y/n)");
answer = kbReader.next().charAt(0);
} while (answer == 'y');
Change your while condition to:
while ("y".equals(kbReader.next()));

switch with character, how to convert character to work with switch ?

when i try to print out the result with switch i can't get any result
so i thought to convert char to integer so the switch statement gona work but isn't so any ideas about how to find solution
echar guestGuess = input.next().charAt(0);
int x = (int)guestGuess;
switch(x){
case '1':
System.out.println(answer.isfirstGuessRight(guestGuess) + "\n");
break;
case '2:
'System.out.println("We are kontrol your answer" + answer.issecandGuessRight(guestGuess));
There's not problem in Java to use char for switch.
You don't have to cast to int for that.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter something, and I'll take the first char only");
char c = scan.next().trim().charAt(0);
switch (c) {
case '1':
System.out.println("1 for sure");
break;
case '2':
System.out.println("I think it's 2");
break;
default:
System.out.println("I don't know");
}
}

Adding Elements in to a queue individually from text file

I would like to add a name to a queue (linked), one name at a time from a text file. If the user selects choice 1 then it should take the next name in from the lists.
Case 1 is not letting me input another choice if I want to add another name.
int choice = console.nextInt();
FileReader names = new FileReader("Customer.txt");
Scanner lookup = new Scanner(names);
Queue a = new Queue();
String customerName;
// This loop was just to verify that
while(lookup.hasNextLine() ){ // It was actually reading
customerName = lookup.next();
System.out.println(customerName);
}
while(true){
switch(choice){
case 1:
customerName = lookup.next();//For some reason its not giving me
a.enqueue(customerName); // The choice to enter another number
break; //even though I made the case while(true)
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
System.out.println(" Exiting......");
break;
default:
continue;
}
break;
}
The problem here is that there is a break after the switch statement. This is causing your code to jump out of the while loop after one pass of the switch statement.
The solution is to remove the break, as such:
while(true){
switch(choice){
case 1:
customerName = lookup.next();//For some reason its not giving me
a.enqueue(customerName); // The choice to enter another number
break; //even though I made the case while(true)
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
System.out.println(" Exiting......");
break;
default:
continue;
}
}

Having trouble with user input validation

This is a small part of my program that I am working on. I'm trying to check if the user enters the correct number.
They have five choices to choose from so they can either hit 1, 2, 3, 4, or 5. Then press enter.
So I want to check to make sure the user doesn't type anything in < 1 or > 5. I got that part to work... But I just want to know if there is a easier way to do it then from what I did in code below.
The next part is that I also want to make sure the user doesn't type in letters. like "gfgfadggdagdsg" for a choice.
Here is my code of the part I am working on....
public void businessAccount()
{
int selection;
System.out.println("\nATM main menu:");
System.out.println("1 - View account balance");
System.out.println("2 - Withdraw funds");
System.out.println("3 - Add funds");
System.out.println("4 - Back to Account Menu");
System.out.println("5 - Terminate transaction");
System.out.print("Choice: ");
selection = input.nextInt();
if (selection > 5){
System.out.println("Invalid choice.");
businessAccount();
}
else if (selection < 1){
System.out.println("Invalid choice.");
businessAccount();
}
else {
switch(selection)
{
case 1:
viewAccountInfo3();
break;
case 2:
withdraw3();
break;
case 3:
addFunds3();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
}
}
}
You may get rid of checking < 1 and > 5 by adding a default case.
try{
selection = input.nextInt();
switch(selection){
case 1:
viewAccountInfo3();
break;
case 2:
withdraw3();
break;
case 3:
addFunds3();
break;
case 4:
AccountMain.selectAccount();
break;
case 5:
System.out.println("Thank you for using this ATM!!! goodbye");
break;
default:
System.out.println("Invalid choice.");
businessAccount();
}
}catch(InputMismatchException e){
//do whatever you wanted to do in case input is not an int
}
Using BufferedReader you can do something like this:
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
int selection = 0;
try{
selection = Integer.parseInt(s);
if(selection > 5 || selection < 1){
System.out.println("Invalid choice.");
businessAccount();
}else{
// your switch code here
}
// you can use #Nishant's switch code here. it is obviously better: using switch's default case.
}catch(NumberFormatException ex){
// throw new Exception("This is invalid input"); // or something like that..
System.out.println("Invalid choice.");
businessAccount();
}
Hope that helps.
Note: you must import java.lang.NumberFormatException import java.io.InputStreamReader and import java.io.BufferedReader
Use the switch case it's better and more speed the if statement when you check selection from a Specific.
an alternative would to use regular expressions to get it work.
Say you have a string x then
String x = "something";
if(x.matches("regex")){
}
Another way to do this is surround with try catch.

Categories