whenever I'm running the loop
"if loop" was running properly but, else one showing a syntax error message
does switch case support if else looping or not??
and one more doubt is how to prepare for the ocjp certification itself.
public static void main(String ah[])
{
int a,b,c,d=0,ch;
Scanner sc=new Scanner(System.in);
System.out.println("enter two number ");
a=sc.nextInt();
b=sc.nextInt();
System.out.println("enter your choise \n1.add\n2.sub\3.div\4.multi ");
ch=sc.nextInt();
switch(ch)
{
case 1:
c=a+b;
System.out.println("sum is = "+c);
break;
case 2:
c=a-b;
System.out.println("subtraction is = "+c);
break;
case 3:
System.out.println("press 1 & 2");
ch=sc.nextInt();
switch(ch)
{
case 1:
if(a>b)
d=b/a;
System.out.println("divi is = "+d);
//showing error = syntax error
else
System.out.println("");
break;
case 2:
d=a/b;
System.out.println("divistion is = "+d);
break;
}
break;
case 4:
c=a*b;
System.out.println("multiplication is = "+c);
break;
default :
System.out.println("wrong input ");
}
}
}
if(a>b)
d=b/a;
System.out.println("divi is = "+d);
//showing error = syntax error
else
System.out.println("");
The else isn't related to the if, because you've not got braces. What you've effectively written is:
if(a>b) {
d=b/a;
}
System.out.println("divi is = "+d);
else
System.out.println("");
Use braces:
if(a>b) {
d=b/a;
System.out.println("divi is = "+d);
} else {
System.out.println("");
}
Note that some (e.g. Google's style guide) would recommend always to use braces, even if there is just one statement between them.
Also note that this has nothing to do with being in a switch statement: you'd get exactly the same problem without the switch.
Try this:
case 1:
if(a>b){
d=b/a;
System.out.println("divi is = "+d);
}else
System.out.println("");
break;
In order to have more than one statement inside an if block, you need brackets to delimit it.
It's also good practice in Java to always use brackets to define blocks.
The problem is you have more than one statement for your if call before the else so you should enclose them in curly braces like this:
case 1:
if(a>b)
{
d=b/a;
System.out.println("divi is = "+d);
}
else
System.out.println("");
break;
Your problem is here:
if(a>b)
d=b/a;
System.out.println("divi is = "+d);
//showing error = syntax error
else
System.out.println("");
break;
The
System.out.println("divi is = "+d);
is between the if and else statements.
Related
I'm trying to error proof my program that basically works as a mini calculator. But I have no idea how to write a "Catch" statement that would detect when the user enters a case number that doesn't exist, in my case anything that is negative or > 4
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = operacijai.nextInt();
int n=1;
do {
try {
switch (operacija) {
case 1:
addingMethod();
n=2;
break;
case 2:
subtractingMethod();
n=2;
break;
case 3:
multiplyingMethod();
n=2;
break;
case 4:
dividingMethod();
n=2;
break;
}
}
catch(Exception e) {
System.out.print("Enter a correct number!");
}
} while(n==1);
operacijai.close();
} ```
Why do you want to throw an Exception unnecessarily? I suggest you just put a default case in your switch with the required error message. Also, move the input part inside the loop, so that it continues to take input.
I also suggest you use nextLine() instead of nextInt(). Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = 0, n = 1;
boolean valid;
do {
do {
valid = true;
try {
operacija = Integer.parseInt(operacijai.nextLine());
} catch (NumberFormatException e) {
System.out.println("Enter an integer only.");
valid = false;
}
} while (!valid);
switch (operacija) {
case 1:
System.out.println("addingMethod()");
n = 2;
break;
case 2:
System.out.println("subtractingMethod()");
n = 2;
break;
case 3:
System.out.println("multiplyingMethod()");
n = 2;
break;
case 4:
System.out.println("dividingMethod()");
n = 2;
break;
default:
System.out.println("Invalid input");
}
} while (n == 1);
}
}
A sample run:
Hello user! Which operation would you like to use?
1) +
2) -
3) *
4) /
5
Invalid input
Another sample run:
Hello user! Which operation would you like to use?
1) +
2) -
3) *
4) /
a
Enter an integer only.
5
Invalid input
2
subtractingMethod()
You can also handle the use case in default
It is totally upto your use-case how you are handling the exception, you can also create your custom exception and throw from default
something like:
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija = operacijai.nextInt();
int n=1;
do {
try {
switch (operacija) {
case 1:
addingMethod();
n=2;
break;
case 2:
subtractingMethod();
n=2;
break;
case 3:
multiplyingMethod();
n=2;
break;
case 4:
dividingMethod();
n=2;
break;
default:
System.out.print("Enter a correct number!")
throw new CustomException();
}
}
catch(CustomException e) {
System.out.print("Enter a correct number!");
}
} while(n==1);
operacijai.close();
}
Figured out a clean way of doing this with default case.
System.out.println("Hello user! Which operation would you like to use?");
System.out.println("1) + \n2) - \n3) * \n4) /");
Scanner operacijai = new Scanner(System.in);
int operacija;
do {
operacija = operacijai.nextInt();
switch (operacija) {
case 1:
addingMethod();
break;
case 2:
subtractingMethod();
break;
case 3:
multiplyingMethod();
break;
case 4:
dividingMethod();
break;
default:
System.out.print("Enter a correct number!");
}
} while(operacija < 1 || operacija > 4);
operacijai.close();
}
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()));
i have a problem i dont know what to put on case section, when ever the user input their grades from 0-100 there are output corresponds to their grades failed,good,verygood,excellent.
import java.util.Scanner;
public class ProgTestI {
public static void main (String args[]){
Scanner pao = new Scanner(System.in);
System.out.print("Grades: ");
String grades = pao.next();
int grado = Integer.parseInt(grades);
switch (grado){
case =<74: /* iwant to put 0 to 74*/
System.out.println("Failed");
case : /* 75-80*/
System.out.println("bellow average");
case : /*81-85*/
System.out.println("average");
case : /*86-90*/
System.out.println("Good");
case : /*91-96*/
System.out.println("VeryGood");
default:
}
}
}
You cannot use switch for ranges, you need to replace this chunk of code with proper if/else blocks.
Switch works only on numeric values, but it works like
if(numericVal == 40)
So writing it for ranges is... waste of code, and not readable.
You need to rewrite it:
if( g <= 74){
...
}else if( g > 74 && g <= 80 ){
...
Your case code is incorrect, you can do as Beri mentioned.
If you want to implement switch statement in your application, then you can do as follows:
public static void main(String[] args) {
Scanner pao = new Scanner(System.in);
System.out.print("Grades: ");
String grades = pao.next();
int grado = Integer.parseInt(grades);
int checkedCase=0;
if(grado<=74){
checkedCase=1;
}
else if(grado>=75&&grado<=80){
checkedCase=2;
}
else if(grado>=81&&grado<=85){
checkedCase=3;
}
else if(grado>=86&&grado<=90){
checkedCase=4;
}
else if(grado>=91&&grado<=96){
checkedCase=5;
}
switch (checkedCase){
case 1: /* iwant to put 0 to 74*/
System.out.println("Failed");
break;
case 2: /* 75-80*/
System.out.println("bellow average");
break;
case 3: /*81-85*/
System.out.println("average");
break;
case 4: /*86-90*/
System.out.println("Good");
break;
case 5: /*91-96*/
System.out.println("VeryGood");
break;
default: System.out.println("Please enter a value in range 0-96");
break;
}
}
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;
}
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.