On Switch How to use logic operator on case JAVA - java

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;
}
}

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.

How to catch an Error in a Switch statement when the user entered number doesn't exist

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();
}

How to switchcases inside if loop

I'm stuck at a question that requests me if the user insert something else instead "e" "x" nums between 1 to 10, then it's returning "incorrect"
here's the code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try{
int Num = 0;
Num = sc.nextInt();
String str = sc.nextLine();
switch (Num) {
case 1: case 2: case 3: case 4:
case 5: case 6: case 7: case 8:
case 9: case 10:
System.out.println("this is a volume");
break;
case : if((Num>10)||(Num <0))
System.out.println("this is incorrect");
break;
}
switch (str) {
case "e": case "E":
System.out.println("Shutting Down");
break;
case "x" : case "X":
System.out.println("Mute");
break;
case "a":case "b":case "c":case "d":case "f":case "g":case "h":case "i":case "j":
case "k":case "l":case "m":case "n":case "o":case "p":case "q":case "r":case "s":
case "t":case "u":case "v":case "w":case "y":case "z":
System.out.println("this is incorrect");
break;
default:
break;
}
}
catch(Exception e) {
System.out.println("stopped");
}
}
}
thank you
If I understand your question properly, as you did not specify how many time the user should enter the input. However, you can have a look at this example, take the idea of the approach and then create your own one.
import java.util.Scanner;
public class ParseInput {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert E for Shutdown, X for Mute and Numbers between 1 to 10 for Volume");
String input = in.nextLine().trim(); // read the entire line after removing spaces if any, then parse it
if(input.length()>0){ // that means the user entered something
try{
int volumeValue = Integer.parseInt(input); // if it's not a number, it will throw exception that will be handled in the catch block
if(volumeValue>=1 && volumeValue<=10){// then evaluate the value
System.out.println("This is a Volume");
}
else{
System.out.println("Incorrect Volume Value");
}
}catch(NumberFormatException e){ // if you reach this block that means it's not a number
if(input.equalsIgnoreCase("e")){ // to accept both uppercase and lowercase
System.out.println("Shutting Down");
}
else if(input.equalsIgnoreCase("x")){
System.out.println("Mute");
}
else{
System.out.println("Incorrect Input");
}
}
}
else{
System.out.println("You have NOT entered anything!");
}
}
}
Test
Insert E for Shutdown, X for Mute and Numbers between 1 to 10 for Volume
e -> Shutting Down
x -> Mute
5 -> This is a Volume
12 -> Incorrect Volume Value
ZzZ -> Incorrect Input
-> You have NOT entered anything!
Please try the below code
switch (Num)
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
System.out.println("this is a volume");
break;
default:
{
if ((Num > 10) || (Num < 0))
{
System.out.println("this is incorrect");
}
break;
}
}

Nested do while loop jump from one to another

I am having some logic difficulties when trying to use a do-while loop. In my main() method. I am trying to prompt user again and again if they entered anything larger than 6:
do{
System.out.println("select your option: ");
System.out.println("1.option1");
System.out.println("2.option2");
System.out.println("3.option3");
System.out.println("4.option4");
System.out.println("5.option5");
System.out.println("6.Quit");
optionChoice = sc.nextInt();
switch (optionChoice) {
case 1:
option1Method();
break;
}
} while (optionChoice > 6);
Then inside my option1Method(), I have another do while loop:
do {
System.out.println("select your option: ");
System.out.println("1.opt1 method1");
System.out.println("2.opt2 method2");
System.out.println("3.opt3 method3");
System.out.println("4.Back");
optOption = sc.nextInt();
switch (optOption ) {
case 1: //do stuffs, same for case 2 and 3
break;
case 4: return;
default: break;
}
} while (optOption > 4);
For this method, I am trying to prompt user the choice again and again as long as they entered anything larger than 4. Then, when they entered 4, it should go back to the do while loop in main() method.
However, for the second do-while loop, when I entered 4, the program itself is just terminated. Any ideas?
Thanks in advance.
In the main method set the condition as:
optionChoice != 6
I am not sure if this is what you want, but I have written the following for you:
import java.util.Scanner;
public class Answer {
static Scanner sc = new Scanner(System.in);
static int optionChoice;
public static void main(String[] args) {
do{
System.out.println("select your option: ");
System.out.println("1.option1");
System.out.println("2.option2");
System.out.println("3.option3");
System.out.println("4.option4");
System.out.println("5.option5");
System.out.println("6.Quit");
optionChoice = sc.nextInt();
switch (optionChoice) {
case 1:
option1Method();
break;
}
} while (optionChoice > 6);
}
public static void option1Method() {
int optOption;
do {
System.out.println("select your option: ");
System.out.println("1.opt1 method1");
System.out.println("2.opt2 method2");
System.out.println("3.opt3 method3");
System.out.println("4.Back");
optOption = sc.nextInt();
switch (optOption ) {
case 1: //do stuffs, same for case 2 and 3
break;
case 4:
optionChoice = 7; // you have to make this value greater than 6 if you want to continue in the loop
return;
default: break;
}
} while (optOption > 4);
}
}
The problem when you enter 4 is that you go back to the main method, and the value you entered for optionChoice is 1 which makes false the condition of the while loop.
EDIT:
In response to #Timeout who is totally right by claiming I am assuming that optionChoice is a "global variable".
To keep your functionality I guess you should just have the following condition in the do-while loop of the main() method:
optionChoice > 6 || optionChoice == 1
EDIT:
what if you add as a condition in the second while loop
optOption != 4
so that you will remain in that loop until the user enters 4
EDIT TO HANDLE optionXMethod where X is a number:
do{
System.out.println("select your option: ");
System.out.println("1.option1");
System.out.println("2.option2");
System.out.println("3.option3");
System.out.println("4.option4");
System.out.println("5.option5");
System.out.println("6.Quit")
optionChoice = sc.nextInt();
switch (optionChoice) {
case 1:
option1Method();
break;
case 2:
option2Method();
break;
case X:
optionXMethod();
break;
}
} while (optionChoice != 6);
void option1Method() {
int optOption;
do {
System.out.println("select your option: ");
System.out.println("1.opt1 method1");
System.out.println("2.opt2 method2");
System.out.println("3.opt3 method3");
System.out.println("4.Back");
optOption = sc.nextInt();
switch (optOption ) {
case 1: //do stuffs, same for case 2 and 3
break;
// you do not need the case 4: because when optOptiontakes the value of 4 it leaves the loop
default: break;
}
} while (optOption != 4);
}
....
General case:
void optionXMethod() {
int optOption;
do {
System.out.println("select your option: ");
System.out.println("1.opt1 method1");
System.out.println("2.opt2 method2");
System.out.println("3.opt3 method3");
System.out.println("4.opt4 method4");
// more options
System.out.println("X.Back"); // where X is the number option of Back
optOption = sc.nextInt();
switch (optOption ) {
case 1: //do stuffs, same for case 2 and 3
break;
// you do not need the case 4: because when optOptiontakes the value of 4 it leaves the loop
default: break;
}
} while (optOption != X); // whatever the value of X is should be consider for this condition
}

Keep getting error: '.class' expected line 40 [duplicate]

This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 4 years ago.
import java.util.*;
public class Lab04B {
public static String toMeters (int unitNumber) {
String value;
switch (unitNumber) {
case 1:
value = "Meter";
break;
case 2:
value = "Nautical mile";
break;
case 3:
value = "Furlong";
break;
case 4:
value = "Mil";
break;
case 5:
value = "Rod";
break;
case 6:
value = "Vershok";
break;
case 7:
value = "Sheppey";
break;
case 8:
return 1.702;
default:
return -1;
}
{
public static double fromMeters (int unitNumber)
{
switch (unitNumber)
{
case 1:
return 1;
case 2:
return 1/1852.0;
case 3:
return 1/201.168;
case 4:
return 1/0.0254;
case 5:
return 1/5.029;
case 6:
return 1/0.04445;
case 7:
return 1/1408.0;
case 8:
return 1/1.702;
default:
return -1;
}
{
public static String getUnitName (int unitNumber)
{
String value;
switch (unitNumber)
{
case 1:
value = "Meter";
case 2:
value = "Nautical mile";
case 3:
value = "Furlong";
case 4:
value = "Mil";
case 5:
value = "Rod";
case 6:
value = "Vershok";
case 7:
value = "Sheppey";
case 8:
value = "Smoot";
default:
value = "faulty input";
}
{
public static void main (String[] args)
Scanner input = new Scanner (System.in);
System.out.println("Converting Measurements");
System.out.println("By: Ashleigh Pacewicz");
System.out.println("1.\tMeter");
System.out.println("2.\tNautical Mile");
System.out.println("3.\tFurlong");
System.out.println("4.\tMil");
System.out.println("5.\tRod");
System.out.println("6.\tVershok");
System.out.println("7.\tSheppey");
System.out.println("8.\tSmoot");
System.out.println("From what unit would you like to convert? ");
int = input.nextInt();
System.out.println("To what unit would you like to convert? ");
int = input.nextInt();
System.out.print("What measurement would you like to convert? ");
double = input.nextDouble();
}
}
}
I am just learning how to code. I'm trying to write a program to convert meters but I keep receiving error on line 40 and line 63 and line 96. Error:
'.class' expected.
What am I doing wrong?
First of all
int = input.nextInt();
System.out.println("To what unit would you like to convert? ");
int = input.nextInt();
You didn't give them a name
and look at your braces
}
{
public static String getUnitName (int unitNumber)
{
It's the same at every method
it should be like this
public void methodName() {
}
but you're doing this
{
public void methodName()
{
and you forgot breaks;
1 more thing you should really use an IDE
I want to be honest. I do not know why you are getting this error...
I've just copied your code and compiled. After removing 2 to 3 braces and adding one, your code compiled without errors. I'm sure you are getting the error, you pasted into your question, from somewhere else.
You have to apply some fixes:
System.out.println("To what unit would you like to convert? ");
int NAME_YOUR_VARS = input.nextInt();
And in a few places you are placing open braces infront of method headers:
{
public static double fromMeters(int unitNumber){
Or you forgot to close method bodys:
public static String toMeters (int unitNumber) {
switch(unitNumber) {
/* case statements were cut out here*/
}
//<- Here you forgot a brace!
Keeping track of code blocks and brace placing is very important!

Categories