I want the user to re-attempt the delivery rating only when the default case is invoked. I am facing error – Cannot invoke "String.equals(Object)" because "response" is null. Please refer to the code below –
package programs;
import java.util.Scanner;
public class DoWhileInSwitch {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String response = null;
do
{
response.equals(null);
System.out.println("Enter the rating of the delivery partner");
int rating = s.nextInt();
switch(rating)
{
case 1:
case 2:
System.out.println("Poor service");
break;
case 3:
System.out.println("Average service");
break;
case 4:
case 5:
System.out.println("Good service");
break;
default:
System.out.println("Invalid rating. Would you like to retry");
s.nextLine();
response = s.nextLine();
}
}
while(response.equals("Yes")||response.equals("Y"));
}
}
>Solution :
Just add a boolean to see if you want to redo input
EDIT:
String.equals returns a boolean.
Null.equals doesn’t exist.
You should remove these statements
EDIT 2 :
The user can choose to re-rate or not.
If he wants to re-rate, just set the boolean to true
Else, set it to false.
public static void main(String[] args) {
boolean retryInput = false;
Scanner s = new Scanner(System.in);
//String response = null; remove this
do
{
// response.equals(null); remove this
System.out.println("Enter the rating of the delivery partner");
int rating = s.nextInt();
switch(rating)
{
case 1:
case 2:
System.out.println("Poor service");
break;
case 3:
System.out.println("Average service");
break;
case 4:
case 5:
System.out.println("Good service");
break;
default:
System.out.println("Invalid rating. Would you like to retry");
s.nextLine();
response = s.nextLine();
if(response.equals("Yes")) retryInput = true;
}
}
while(retryInput);
}
This should work