Prevent Orphaned Case Error in Java

Sarwan Soomro Jan 03, 2023 Mar 11, 2022
  1. Orphaned Case Errors in Java
  2. Best Practices to Avoid switch Case Errors in Java
  3. Get User Input With the Java Scanner Input Stream
  4. Get User Input and Apply switch Case Using Scanner in Java
  5. Use a while Loop in a switch and Get User Data Repeatedly in Java
Prevent Orphaned Case Error in Java

This article explains how to prevent orphaned case errors in Java switch statements. It will demonstrate switch cases in examples and use a scanner input stream to make the examples more dynamic.

Orphaned Case Errors in Java

In Java, the orphaned error is not frequent. It arises with the switch statement.

Common errors and solutions:

  1. Scanner cannot be resolved to a type. - If your compiler throws this error, it means you must import: import java.util.Scanner; to make use of this function.
  2. java.util.InputMismatchException - A Scanner will throw this error if the token retrieved does not match the sequence for the specified type or if the token is out of bounds for the expected type.

Best Practices to Avoid switch Case Errors in Java

We put syntax examples in the following code blocks to avoid all the switch statements’ errors.

Incorrect:

Switch(demo); {
Case(demo);
Case;
Note
Never use upper cases when dealing with switch cases. Always use lower cases to avoid the most common error.

Correct:

switch(demo){
    case 1: // for integer type
	case "String": // for string type
Note
Never use a semicolon ; after the switch() and case statement. Always use a colon : after case and nothing after the button.

Best practices:

  1. Your case should be inside your switch statement.
  2. Never apply conditions inside a case statement.
  3. Declare a type, then pass it in your switch. Do not expect a switch to determine your type by itself.

Code:

//Int Example
int num = 0;
switch(num){
    case 1: // your code
	break; // if the condition is true, the case breaks
}
//String Example
String str ="A";
switch(str){
case "str": // our code
//break;
}

Let’s make excellent programs with switch cases while avoiding the rare orphaned error if it is clear now.

Get User Input With the Java Scanner Input Stream

Here are a few additional methods and parameters you should know to understand this example fully.

  1. Scanner - Creates a new Scanner that scans the provided input stream and returns values.
  2. next(); - This scanner finds and returns the next full token ("").
  3. nextInt(); - It scans the next token of the input as an int.

Parameter: A stream of data to be scanned.

Syntax:

import java.util.Scanner;
	public static void main(String[] args)
	{
//Extend Scanner in Java
	Scanner demo = new Scanner (System.in);
	System.out.println("Print Something");
	String a=demo.next(); //used for string
	int b=demo.nextInt(); //used for integers
	}
//(System.in): Theinput stream.

We are simply taking the input stream with the help of the scanner and assigning it to the demo variable.

Get User Input and Apply switch Case Using Scanner in Java

Example 1:

//example1
package AvoidError;
import java.util.Scanner;
public class PreventOrphanedCaseErrorExample1 {
	@SuppressWarnings("resource")
	public static void main(String[] args)
	{
		Scanner demo = new Scanner (System.in);
		System.out.println("A");
		System.out.println("B");
		System.out.println("C");
		System.out.println("D");
		String a=demo.next();
		switch(a)
		{
		case "A":System.out.println("You chose A");
		break;
		case "B":System.out.println("You chose B");
		break;
		case "C":System.out.println("You chose C");
		break;
		case "D":System.out.println("You chose A");
		break;
		default:System.out.println("You did not choose any value!");
		break;
		}
	}
}

Output:

Get User Input and Apply Switch Case using scanner

Use a while Loop in a switch and Get User Data Repeatedly in Java

The difference in this example is only a more dynamic approach, and we will also use the equals(); method, which compares the strings.

If true, it returns the given object; else, it returns false. Check the following code carefully.

Example 2:

//Example 2
package AvoidError;
import java.util.Scanner;
public class PreventOrphanedCaseErrorExample2 {
	public static void main(String[] args) {
		try (
				Scanner nxt = new Scanner(System.in)) {
			while (true) {
				System.out.println("1: Fruits");
				System.out.println("2: Vegies");
				System.out.println("3: Chicken");
				System.out.println("Please select your choice!");
				String i = nxt.next();
				switch (i) {
				case "1":System.out.println("You chose Fruits");
				break;
				case "2":System.out.println("You chose Vegies");
				break;
				case"3":System.out.println("You chose Chicken");
				break;
				default:
					System.out.println("Sorry! You did not choose from given options");
				}
				System.out.println("Do you want to repeat this operation?");
				String REPEAT = nxt.next();
				if (!REPEAT.equals("YES")) {
					break;
				}
			}
		}
	}
}

Output:

Use While Loop in Switch and Get User Data Repeatedly

Note
Everything in this example is the same as the previous program except for the equals();.

We stored nxt.next(); in the string REPEAT and later set a simple condition to check if the equals(); function returned true. In this case, it returned the string’s YES; thus, we got a more dynamic program using points in the switch statement.

There is no limit to what you can do with a few Java and switch statements functions with this comprehension.

Sarwan Soomro avatar Sarwan Soomro avatar

Sarwan Soomro is a freelance software engineer and an expert technical writer who loves writing and coding. He has 5 years of web development and 3 years of professional writing experience, and an MSs in computer science. In addition, he has numerous professional qualifications in the cloud, database, desktop, and online technologies. And has developed multi-technology programming guides for beginners and published many tech articles.

LinkedIn

Related Article - Java Error