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;
}
}
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();
}
Hi i have a txt file that have a number in bunch of rows and i get this error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
what can i add in my code to make it work it seems to be right to me but idont know why i get error
public static void main(String[] args) {
String input;
try {
Scanner scan = new Scanner(new File("andy.txt"));
while (scan.hasNextLine()) {
lineCounters++;
input = scan.nextLine();
putArray(sigFig(input));
}
calcPercentage();
makeGraph();
scan.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
here is my putArray
public static void putArray(char input) {
switch (input) {
case '1':
++digitCounters[0];
break;
case '2':
++digitCounters[1];
break;
case '3':
++digitCounters[2];
break;
case '4':
++digitCounters[3];
break;
case '5':
++digitCounters[4];
break;
case '6':
++digitCounters[5];
break;
case '7':
++digitCounters[6];
break;
case '8':
++digitCounters[7];
break;
case '9':
++digitCounters[8];
break;
}
}
It might be your putArray function which launches that exception. Can I have a look of it?
I know about the return statement and have tried it. System.exit(0) also does the same. But using it here terminates the program. Is there any way i can use so that if the user types other input except 1-7 , the program doesn't terminate , so that i don't have to recompile and rerun the program ? Or is it not possible in Java ?
import java.util.Scanner;
public class NewShoppingCart{
public static void main(String args[]) {
boolean flag = true;
long code;
String choice;
NewShop aShop = new NewShop();
Scanner sc = new Scanner(System.in);
Integer parse = 0;
System.out.println("-----ITEM------");
do {
System.out.println("1. Display all items");
System.out.println("2. Search items");
System.out.println("3. Add items to list");
System.out.println("4. Add items to cart");
System.out.println("5. Display cart");
System.out.println("6. Issue item");
System.out.println("7. Exit");
System.out.println("Choice:");
choice = sc.nextLine();
try{
parse = Integer.parseInt(choice);
}
catch(Exception e){
System.out.println("Please enter a valid integer");
return;
}
if (parse >=1 && parse <= 7 )
{
switch (parse) {
case 1:
aShop.display();
break;
case 2:
aShop.searchItem();
break;
case 3:
aShop.addItem();
break;
case 4:
aShop.addItemtoCart();
break;
case 5:
aShop.displayCart();
break;
case 6:
aShop.issueItem();
break;
case 7:
System.out.println("Thank you!\n");
flag = false;
break;
default :
System.out.println("Please enter choice relevant to context");
}
}
else return;
}
while (flag != false);
sc.close();
}
}
Change this
catch(Exception e){
System.out.println("Please enter a valid integer");
return;
}
to
catch(Exception e){
System.out.println("Please enter a valid integer");
continue;
}
also in your else block have continue instead of return.
You can never go out of main with just one thread. This is likely an XY problem. What you really want is to go back to the start of the loop if the user inputs something invalid.
The continue keyword will stop executing the current iteration of the enclosing loop and start a new iteration immediately. This is what you should use in place of return.
try{
parse = Integer.parseInt(choice);
}
catch(Exception e){
System.out.println("Please enter a valid integer");
return; // <--- change this to "continue;"
}
Also, this:
if (parse >=1 && parse <= 7 )
{
switch (parse) {
case 1:
aShop.display();
break;
case 2:
aShop.searchItem();
break;
case 3:
aShop.addItem();
break;
case 4:
aShop.addItemtoCart();
break;
case 5:
aShop.displayCart();
break;
case 6:
aShop.issueItem();
break;
case 7:
System.out.println("Thank you!\n");
flag = false;
break;
default :
System.out.println("Please enter choice relevant to context");
}
}
else return;
should really be:
if (parse >=1 && parse <= 7 )
{
switch (parse) {
case 1:
aShop.display();
break;
case 2:
aShop.searchItem();
break;
case 3:
aShop.addItem();
break;
case 4:
aShop.addItemtoCart();
break;
case 5:
aShop.displayCart();
break;
case 6:
aShop.issueItem();
break;
case 7:
System.out.println("Thank you!\n");
flag = false;
break;
}
}
else {
System.out.println("Please enter choice relevant to context");
continue;
}
The "Please enter choice relevant to context" message should really be printed in the else statement. Because in your if, you already checked whether parse is between 1 and 7, so in the switch, parse can't be anything else so the default branch is never reached. After you print the message, you continue; in order to go back to the start of the loop.
I'm trying to get the user to give input and then after everything from all the cases was read out to them, re-loop to the output.displayMainMenu(); until they were to enter 4 to exit the program.
output.displayMainMenu();
int entry = keyboard.nextInt();
while(entry >= 1 || entry <=4) {
output.displayMainMenu();
switch(entry) {
case 1:
output.displayStockChoices(portfolio);
portfolio.editPostion();
portfolio.displayPositions();
break;
case 2:
portfolio.updateCurrentPrice();
break;
case 3:
System.out.print(investor.toString() + "Account Balance: " +portfolio.calcTotalAccountValue());
break;
case 4:
System.out.print("Done.");
break;
default:
System.out.print("please enter 1-4!");
}
break;
}
It's better to use a do-while loop because the code inside the loop need to be ran at least one time. I agree with #AntonH, that are several issues in this code. I rewrote it considering the mentioned issues.
int entry = 0;
do {
output.displayMainMenu();
try {
entry = keyboard.nextInt();
} catch (InputMismatchException e) {
System.out.print("Invalid input. ");
}
switch (entry) {
case 1:
output.displayStockChoices(portfolio);
portfolio.editPosition();
portfolio.displayPositions();
break;
case 2:
portfolio.updateCurrentPrice();
break;
case 3:
System.out.print(investor.toString() + "Account Balance: "
+ portfolio.calcTotalAccountValue());
break;
case 4:
System.out.print("Done.");
break;
default:
System.out.print("please enter 1-4!");
}
} while (entry >= 1 && entry < 4);
// Don't forget to close Scanner object when program finish
keyboard.close();
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;
}
}