I am working on a project where you enter the abbreviation for a state into a scanner and then the program tells you what region of the U.S. the state is in. I think that the majority of my code is correct, but I have never used switch before.
I have polished my work down to one error, a missing return statement in my first block of code (the switch section). I do not know if any other code is affecting it, so I am just going to post most of it here. Thanks in advance.
import java.util.Scanner;
public class Regions {
public static String getRegion (String stateName){
String region = "";
switch(stateName){
case "ME":
case "VT":
case "NH":
case "MA":
case "CT":
case "RI":
region = "New England";
break;
case "NY":
case "NJ":
case "DE":
case "MD":
case "VA":
case "NC":
case "SC":
region = "Atlantic";
break;
case "GA":
case "FL":
case "MS":
case "AL":
case "LA":
case "TN":
region = "Southeast";
break;
case "PA":
case "OH":
case "MI":
case "IN":
case "IL":
case "WI":
case "MN":
case "KY":
case "WV":
case "IA":
region = "Midwest";
break;
case "ND":
case "SD":
case "KS":
case "NE":
case "MO":
region = "Great Plains";
break;
}
}
public static void main (String[]args){
Scanner s = new Scanner(System.in);
System.out.println("Enter a two-letter state abbreviation:");
String stateName = s.nextLine();
String region = getRegion(stateName);
System.out.print("The state " + stateName);
if (region == "New England"){
System.out.print(" is in the New England region!");
}
else if (region == "Atlantic") {
System.out.print(" is in the Atlantic region!");
}
else if (region == "Southeast") {
System.out.print(" is in the Southeast region!");
}
else if (region == "Midwest") {
System.out.print(" is in the Midwest region!");
}
else if (region == "Great Plains") {
System.out.print(" is in the Great Plains region!");
}
else {
System.out.println ("That's not a state.");
}
}
}`
First Problem : Missing return in getRegion()
Just add
return region;
add the end of that method.
Second Problem : Comparing strings with == instead of equals
In your main replace all
if (region == "..."){
with
if (region.equals("...")){
You eventually need to add a result when to the method is passed an invalid state.
The rest of the code is correct, but you need to return region at the end of the method.
A better code is to return directly instead of using a locale variable region.
public static String getRegion (String stateName){
switch (stateName) {
case "ME":
case "VT":
case "NH":
case "MA":
case "CT":
case "RI":
return "New England";
case "NY":
case "NJ":
case "DE":
case "MD":
case "VA":
case "NC":
case "SC":
return "Atlantic";
case "GA":
case "FL":
case "MS":
case "AL":
case "LA":
case "TN":
return "Southeast";
case "PA":
case "OH":
case "MI":
case "IN":
case "IL":
case "WI":
case "MN":
case "KY":
case "WV":
case "IA":
return "Midwest";
case "ND":
case "SD":
case "KS":
case "NE":
case "MO":
return "Great Plains";
}
throw new IllegalArgumentException("invalid state");
// Or return a special string value
}
As other said there are errors also in the main, but I focused only in the getRegion method that was the question asked. Don't use == operator to compare strings, use the method equals.
== check if two strings are the same object, equals check if two string objects have the same content.
Looks like you just want to put a
return region;
at the end of your getRegion method.
That's it.
Related
This question already has answers here:
Why do we need break after case statements?
(17 answers)
why is the wrong "case" being executed after "default" in a switch statement
(5 answers)
Closed 4 years ago.
So I have this piece of code:
void go() {
String x = "Hi";
switch (x) {
case "Hi":
System.out.println("Hi");
}
}
And this returns: Hi
But when I run
void go() {
String x = "Hi";
switch (x) {
case "Hi":
System.out.println("Hi");
case "Bye":
System.out.println("Bye");
}
}
It returns:
Hi
Bye
Why is this.Is there something I missed?
As already stated before, you have to add break; statements for each case if you want to stop at that special one. Your code would then look like this:
void go() {
String x = "Hi";
switch (x) {
case "Hi":
System.out.println("Hi");
break;
case "Bye":
System.out.println("Bye");
break;
}
}
Another thing you really should do is adding a default case for any non matching input (imagine someone input "Hy" instead of "Hi", there wouldn't be any output for that...):
void go() {
String x = "Hi";
switch (x) {
case "Hi":
System.out.println("Hi");
break;
case "Bye":
System.out.println("Bye");
break;
default:
System.out.println("Your input was \"" + x
+ "\", please enter either \"Hi\" or \"Bye\" instead!");
}
}
The default statement is an option for anything that isn't handled in the case statements.
Now back to the breaks... You can handle different cases just the same if you set the breaks only to some of the cases:
void go() {
String x = "Hi";
switch (x) {
case "Hi":
case "Hy":
System.out.println("Hi");
break;
case "Bye":
case "By":
System.out.println("Bye");
break;
default:
System.out.println("Your input was \"" + x
+ "\", please enter either \"Hi\", \"Hy\", \"By\" or \"Bye\" instead!");
}
}
Doing like this, you will receive the same output for "Hi" and "Hy" without duplicating the code that handles both cases.
You should put some break statements at the end of case statements or the execution will propagate to the next case statements. Even if it is counter intuitive, it is sometimes useful.
switch(int n) {
case 1: System.out.println("Hello");
case 2: System.out.println("World");
}
Here switch(1) will display :
Hello
World
And switch(2) will display :
World
But with break statements :
switch(int n) {
case 1:
System.out.println("Hello");
break;
case 2:
System.out.println("World");
break;
}
Here switch(1) will display :
Hello
And switch(2) will display :
World
In switch statement you have to write break at the end of each case.
If you do not write break then it prints all cases.
switch(value)
{
case X:
//do something
break;
case Y:
//do something
break;
default:
//do something
break;
}
I am trying to change the text in a TextView I am about to display, but if the input does not match any of the cases, I do not want to call the method.
How can I write this in as few lines of code as possible?
switch (integer) {
case 1:
case 2:
replyOne.setText("string 1 & 2");
break;
case 3:
replyOne.setText("string 3");
break;
default:
Toast.makeText(this, "incorrect typing", Toast.LENGTH_LONG).show();
}
makeContactMessage(replyOne, messagesLayout);
In terms of fewer lines of code, just simply use if/else statements instead as follows:
if (integer == 1 || integer == 2) {
replyOne.setText("string 1 & 2");
} else if (integer == 3) {
replyOne.setText("string 3");
} else {
Toast.makeText(this, "incorrect typing", Toast.LENGTH_LONG).show();
}
Keep things simple; no need to overcomplicate things :-)
Put the String logic in your Model and set the Textview only once. Your presenter should not have any logic.
String reply = model.getReply();
replyOne.setText(reply)
//in your model,
String getReply(){
switch(){
}
return ...
}
There are at least 2 ways to achieve that.
Using a return
Using a simple boolean flag.
.
1. Using a return
If your code is a method, you can use return statement something like this:
private void myCheckMethod(int value) {
switch (value) {
case 1:
case 2:
replyOne.setText("string 1 & 2");
break;
case 3:
replyOne.setText("string 3");
break;
default:
Toast.makeText(this, "incorrect typing", Toast.LENGTH_LONG).show();
return; // here the method will be terminated if checking is not valid.
}
makeContactMessage(replyOne, messagesLayout);
}
2. Using a simple boolean flag.
Use a simple flag for calling the method. Here we using isValid variable:
boolean isValid = true; // always set checking as valid.
switch (integer) {
case 1:
case 2:
replyOne.setText("string 1 & 2");
break;
case 3:
replyOne.setText("string 3");
break;
default:
Toast.makeText(this, "incorrect typing", Toast.LENGTH_LONG).show();
isValid = false; // false, because we can't match anything.
}
if(isValid) {
makeContactMessage(replyOne, messagesLayout);
}
I have my code written in if/else Statement and it is working but I have a problem in writing it using switch statement as it appears that there are problems in my variables and symbols.
Can you please spot what is wrong and help me correct it?
My source code below.
import java.util.Scanner;
import java.io.*;
public class CourseCodeSWITCH {
public static void main(String[] a) {
Scanner in = new Scanner (System.in);
String code;
System.out.print("Enter Course Code: ");
code = in.nextLine();
switch (code) {
case A: code = "Accounting";
break;
case B: code = "Banking and Finance";
break;
case C: code = "Computer Science";
break;
case D: code = "Dentistry";
break;
case E: code = "Engineering";
break;
default:
System.out.println("Invalid Course Code");
break;
}
}
}
You're using A, B, C, as labels, but that's not how a switch statement works. Let's take a look at just one statement:
switch (code) {
case A: code = "Accounting";
break;
You're switching on code... this means you're going to be examining the contents of the code variable.
Next, you declare a case. In the case above, you're effectively saying
if (code == A)
code = "Accounting";
break;
Now, there's a couple things wrong with that. First of all, A is not defined anywhere, so you're immediately going to run into compile-time errors. You probably wanted to use a String value ("A") instead. Second, you're just reassigning code instead of outputting like you did in your original if-statement.
You probably want a switch that looks closer to the following:
switch(code) {
case "A":
System.out.println("Assignment");
break;
case "B":
System.out.println("Banking and Finance");
break;
// and so forth
}
In Java 7/8 you can define the String to compare code to. In earlier versions you may want to use a char or enum.
public static void main(String[] a) {
Scanner in = new Scanner (System.in);
String code;
System.out.print("Enter Course Code: ");
code = in.nextLine();
switch (code) {
case "A":
code = "Accounting";
break;
case "B":
code = "Banking and Finance";
break;
case "C":
code = "Computer Science";
break;
case "D":
code = "Dentistry";
break;
case "E":
code = "Engineering";
break;
default:
System.out.println("Invalid Course Code");
break;
}
Additionally here is an example from Oracle.
Just starting Java so it's probably a simple question but couldn't find any questions like mine so figured I would post one.
I am writing a "main menu" with options 1-8. I figured out how to error handle when someone types a number larger than 8 and less than 1 but I can't figure out how to give them an error message if they type a character or letter...
while(menuChoice != 8)
{
//main menu that loops
switch(menuChoice)
{
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
case 4:
//code
break;
case 5:
//code
break;
case 6:
//code
break;
case 7:
//code
break;
case 8:
//code
break;
default:
System.out.println("Error: Invalid Menu Selection.");
}
}
Assuming this compiles, what you're asking would be impossible. You're switching on a number, so you can't check if the number is a character. Your code wouldn't compile if that were possible.
You should take the user input as a String and validate the String. If the String has non-numeric values in it, then throw an error. If it doesn't, convert it to a number then execute your switch.
A better design would be to have a validation layer. Once the input is validated, just assume it's valid thereafter.
Pseudocode:
String input = //
if (containsNonNumerics(input))
throw error
inputAsInt = castToInt(input)
if (outOfRange(inputAsInt)
throw error
switch //your current code goes here
First off, having that while loop is not going to give you the functionality that you want. You should look into how to use KeyAdapter in order to be able to receive input events from the keyboad, e.g. a number being pressed, and then you can validate that it is actually a number, and if it is you can then use your switch statement to determine the proper code to execute.
I am guessing that menuChoice is a character. In which case, you can either do a manual check that
if('0' <= mc && mc <= '9') {
// do your regular checks
}
If it is a string then do a
try {
Integer.parseInt(mc)
} catch (NumberFormatException e) { // Not a number. Do your error reporting stuff }
HTH.
Switch statment work only with numeric types (int, byte, char, short). If you try add in switch anything else the compailer wouldent allowe you in general. But if you somehow (cating or other way) want to add in switch statment varible you must befor check it with if statment if the varible is type that you want.
Example:
if(var instanceof String){
System.out.println("Error we don't acceped type string");
}
else{
switch(var){
....
}
}
Use this function before entering into while loop and display the error message.
public static boolean isNumeric(String str)
{
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}
int menuChoice ;
//Now get input from customer in menuChoice
//Your logic goes herr... example menuChoice = ..whateverinput
//After the input is captured then validate
if(menuChoice <1 || menuChoice >8 )
{
//main menu that loops
switch(menuChoice)
{
case 1:
//code
break;
case 2:
//code
break;
case 3:
//code
break;
case 4:
//code
break;
case 5:
//code
break;
case 6:
//code
break;
case 7:
//code
break;
case 8:
//code
break;
default:
System.out.println("Error: Invalid Menu Selection.");
}
else {
System.out.println("Please Enter Valid Entry");
}
I am trying to test if my user submits sensible data , which is later formatted to integer.
Where is the problem with the switch statement? :)
void convert(String str)
{
int i=0;
String x=str.startsWith();
switch (x) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 0:
int i = Integer.parseInt(str);
break;
default:
System.out.println ("Should start with fixnumber");
}
System.out.println (i);
}
You're switching on x which is a String - unless you're using Java 7, you can't use String in a Switch statement.
I expect the error is actually coming from str.startsWith(), where that method is expecting to take a String (which you're checking what it starts with) and returns a boolean, which you can't switch on either.
UPDATE Correcting your code to do what I think you're trying to do:
void convert(String str)
{
int i = 0;
switch (str.charAt(0)) {
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
i = Integer.parseInt(str);
break;
default:
System.out.println ("Should start with fixnumber");
}
System.out.println (i);
}
Although the shorter way is just to do the Integer.parseInt call, and handling the NumberFormatException that may occur - then you don't need to do the switch at all.
void convert(String str)
{
try {
int i = Integer.parseInt(str);
System.out.println (i);
} catch (NumberFormatException e) {
System.out.println ("Should start with fixnumber");
}
}
You need to either return i; and convert the method signature from void to int, or otherwise expose the data in i to make it worthwhile.
x is a string and in case you test number.
try:
case "string1"
..
break;
case "string2"
..
break;
etc...
If you're trying to test to see if the string entered is an Integer, then I see no reason to have the switch() in the first place. It would be far better behavior to catch the exception raised when trying to work with the function.
Example:
void convert(String str) { // Heads-up: convert has <package> visibility
int i = 0;
try {
i = Integer.parseInt(str);
System.out.println(i);
} catch (NumberFormatException nfe) {
System.out.println ("Should start with fixnumber");
}
}
Your x is a String. The switch statement is attempting to compare it against integer values. You need something like this:
switch (Integer.parseInt(x))
{
// etc...
EDIT: Actually, now that I see that the string is supposed to be the result of a startsWith call, I'm totally confused about what this code is trying to do.