I'm a beginner learning Java, and my teacher gave me this question:
Write a switch statement which assigns a value to char grade based on
the value of int variable score.
A score between 0 and 4 inclusive gets an 'F'.
A score of 5 or 6 gets a 'D'
A score of 7 gets a 'C'
A score of 8 gets a 'B'
A score of 9 or 10 gets an 'A'
Any other score gets an 'X'.
No other code than the switch statement itself should be included.
Here's what I wrote:
switch (grade) {
case 'A':
break;
case 'B':
break;
case 'C':
break;
case 'D':
break;
case 'F':
break;
case 'X':
break;
}
After running it on the website, I found that all cases worked except 'X'. So I tried:
default: grade = 'X'
But that also did not work.
How can I add 'X' as a default for this switch statement, and what can help me prevent myself from making this mistake again?
The switch may be used the other way, score > grade and not grade > ... as you did
static char scoreToGrade(int score) {
switch (score) {
case 0:
case 1:
case 2:
case 3:
case 4:
return 'F';
case 5:
case 6:
return 'D';
case 7:
return 'C';
case 8:
return 'B';
case 9:
case 10:
return 'A';
default:
return 'X';
}
}
Or with the other switch expression
static char scoreToGrade(int score) {
return switch (score) {
case 0, 1, 2, 3, 4 -> 'F';
case 5, 6 -> 'D';
case 7 -> 'C';
case 8 -> 'B';
case 9, 10 -> 'A';
default -> 'X';
};
}
Then call
char grade = scoreToGrade(4);
char grade = scoreToGrade(8);
Welcome to StackOverflow. Reading the requirement, you should rethink what is the purpose of the question. The switch statement shouldn't use the grade as a parameter, but the score. Before executing the function, you only know the score: the input is the score, and the output of your function is the grade. Using the score in the case conditions and return from there the grades. As the code executes sequentially, the last statement should be default, returning the X.
Lets try to explain this as easy as possible.
You want to check the score to assign a grade.
Switch takes a variable, in your case you placed grade, and checks if it matches with the cases, in case the grade is equal to A, to B,C...
If I explained it well, the first problem should be easy to see, you are checking the variable your are trying to assign.
You don't have a value for grade at the start, so its imposible to check a condition.
So you should check score (placing it on the switch), and assign grade inside the cases.
String grade; //no values
int score=4; //The variable we want to check
switch (score) {
case 0:
grade = "F";
break;
case 1:
grade = "F";
break;
case 2:
grade = "F";
break;
case 3:
grade = "F";
break;
case 4:
grade = "F";
break;
case 5:
grade = "D";
break;
case 6:
grade = "D";
break;
case 7:
grade = "C";
break;
case 8:
grade = "B";
break;
case 9:
case 10:
grade = "A";
break;
default:
grade = "X";
}
You can imagine it like a series of if checking for equality:
if(score==0){
grade="F";
}
if(score == 1){
grade="F";
}
if(score == 2){
grade="F";
}
if(score == 3){
grade="F";
}
if(score == 4){
grade="F";
}
if(score == 5){
grade="D";
}
if(score == 6){
grade="D";
}
//and so on
(It would more precise to use else if, but this is an example trying to make it as easy as possible, also doesn't cover all switch functionality, but you can get an idea of what I mean with checking and assigning).
At the end, your grade variable will have a value, cause you assigned it in the switch cases.
You can improve that switch, getting rid of the breaks on the firs 4 cases, so it will work like a "cascade", jumping to the next case until it finds a break:
String grade; //no values
int score=4 //The variable we want to check
switch (score) {
case 0:
case 1:
case 2:
case 3:
case 4:
grade = "F";
break;
case 5:
grade = "D";
break;
case 6:
grade = "D";
break;
case 7:
grade = "C";
break;
case 8:
grade = "B";
break;
case 9:
case 10:
grade = "A";
break;
default:
grade = "X";
}
Related
I wanna Write a program to print out the user's grade ("Excellent if grade is A, Very Good if grade is B, Good if grade is C, Fair if grade is D, Fail if grade is F"). using Switch Statement
But When User input a or b or c or d or f in lowercase Apply the Grade
I mean I wanna char = A or a Match the Grade "Excellent"
and char = B or b Match the Grade " Very Good " and so on
Thanks and I hope to Find a Quick Solution
I tried this But it doesn't Make anything
public static void main(String[] args)
{
char Grade = 'A';
switch (Grade)
{
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Very Good");
break;
case 'C':
System.out.println("Good");
break;
case 'D':
System.out.println("Fair");
break;
case 'F':
System.out.println("Fail");
break;
}
}
You have two ways:
Multiple case statements:
switch (Grade) {
case 'A':
case 'a':
System.out.println("Excellent");
break;
case 'B':
case 'b':
System.out.println("Very Good");
break;
case 'C':
case 'c':
System.out.println("Good");
break;
case 'D':
case 'd':
System.out.println("Fair");
break;
case 'F':
case 'f':
System.out.println("Fail");
break;
}
}
Converting the character to upper case:
char Grade = 'A';
Grade = Character.toUpperCase(Grade);
switch (Grade) {
...
}
You can simply covert the character entered by the user to either lower case or lower case and compare accordingly.
I am trying to do the following for a Java switch method with a series of JUnit Asserts but am stuck on using "less than" and "greater than" for two cases (see string/int error below), and am not sure how to use the ">" and "<" in my cases.
Here is the exercise followed by my code, followed by the error.
/*
Create a method which uses a switch statement to return a String representing the int passed in as a parameter to the method:
• given 1 return "One"
• given 2 return "Two"
• given 3 return "Three"
• given 4 return "Four"
• given an integer > 4, return "Too big"
• given an integer < 1, return "Too small"
*/
#Test
public void switchIntExample() {
assertEquals("One", stringRepInt(1));
assertEquals("Two", stringRepInt(2));
assertEquals("Three", stringRepInt(3));
assertEquals("Four", stringRepInt(4));
assertEquals("Too big.", stringRepInt(>4));
// assertEquals("Too small.", stringRepInt(<4));
}
//Switch statement for above:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
//TODO: question on how to do LESS THAN and GREATER THAN:
// error line:
case (numVar > 4):
numVar = "Too big.";
break;
default:
break;
}
System.out.println(numVar);
return numVar;
}
ERROR:
Error:(293, 27) java: bad operand types for binary operator '>'
first type: java.lang.String
second type: int
case statements only support constant expressions (you cannot do less than, or greater than, in a case and you can't test numVar - the String - with less than). You can use an if and something like
public String stringRepInt(int numberSize) {
String numVar = null;
if (numberSize > 4) {
numVar = "Too big.";
} else {
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
break;
}
System.out.println(numVar);
return numVar;
}
You should add it to the default section, so like this:
default:
numVar = "Too Big";
break;
The purpose of the default section is to deal with all cases not dealt with by the switch cases. You should be taking advantage of that (as #GreenMatt and #FredK mentioned in comments) by putting the 'if checks' in the default section, as follows:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
if(numberSize > 4)
numVar = "Too big";
break;
}
System.out.println(numVar);
return numVar;
}
Further, you could add else if (numberSize < 1) numVar = "Too small"; under the if statement if you want to check for number's smallest than one. This is also important because it prevents your method from returning null. (Which currently happens if the user enters a value less than 1)
The resulting code is as follows:
public String stringRepInt(int numberSize) {
String numVar = null;
switch (numberSize) {
case 1:
numVar = "One";
break;
case 2:
numVar = "Two";
break;
case 3:
numVar = "Three";
break;
case 4:
numVar = "Four";
break;
default:
if(numberSize > 4)
numVar = "Too big";
else
numVar = "Too small";
break;
}
System.out.println(numVar);
return numVar;
}
In the error line you are comparing String and int.
error line: case (numVar > 4): numVar = "Too big."; break;
you have declared numVar as String and comparing that with int value 4. Please correct that or I think you are trying to compare numberSize with value 4. Convert that String to int and compare it.
My instructor requires us to take the package from our code and make it a default package. The only problem is he taught us how to do that through Windows and I have a MacBook so his way isn't working. I can't figure out how to do it. I've attached the code to the bottom in case that will help.
package romannumeralcalculator;
import java.util.*;
public class RomanNumeralCalculator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int integer;
do {
System.out.print("Please enter an interger from 1 to 5999. Enter a negative number to exit. \n ->");
integer = input.nextInt();
} while (integer >= 6000);
while (integer == 0) {
System.out.println("");
break;
}
String results = "";
int ones = integer % 10;
int tens = (integer / 10) % 10;
int hundreds = (integer / 100) % 10;
int thousands = (integer / 1000) % 1000;
switch (thousands) {
case 1:
results += "M";
break;
case 2:
results += "MM";
break;
case 3:
results += "MMM";
break;
case 4:
results += "MMMM";
break;
case 5:
results += "MMMMM";
break;
default:
System.out.println("");
}
switch (hundreds) {
case 1:
results += "C";
break;
case 2:
results += "CC";
break;
case 3:
results += "CCC";
break;
case 4:
results += "CD";
break;
case 5:
results += "D";
break;
case 6:
results += "DC";
break;
case 7:
results += "DCC";
break;
case 8:
results += "DCCC";
break;
case 9:
results += "CM";
break;
default:
System.out.println("");
}
switch (tens) {
case 1:
results += "X";
break;
case 2:
results += "XX";
break;
case 3:
results += "XXX";
break;
case 4:
results += "XL";
break;
case 5:
results += "L";
break;
case 6:
results += "LX";
break;
case 7:
results += "LXX";
break;
case 8:
results += "LXXX";
break;
case 9:
results += "XC";
break;
default:
System.out.println("");
}
switch (ones) {
case 1:
results += "I";
break;
case 2:
results += "II";
break;
case 3:
results += "III";
break;
case 4:
results += "IV";
break;
case 5:
results += "V";
break;
case 6:
results += "VI";
break;
case 7:
results += "VII";
break;
case 8:
results += "VIII";
break;
case 9:
results += "IX";
break;
default:
System.out.println("");
}
System.out.println(results);
}
}
In the projects tab of Netbeans in the top-left:
Expand the tree for your Project.
Expand the Source Packages folder.
Expand the package with your java file.
Drag the java file from under the package to the Source Packages folder.
A dialog box will pop up with the title Move Class. On that dialog click the Refactor button.
This should be the same procedure in Windows. I am not sure why your professor told you something different.
So i have created this code to convert words into phone numbers, but when i try to run this code with letters under 7 word it will display string index out of range. But 7 or more is fine. How do i fix this? If so how do i set the string range?
{
System.out.println("Enter a word to be converted: ");
String telLetter = console.next ();
telLetter = telLetter.toUpperCase();
String telNumber="7";
int count=0;
int i=0;
while(count <7)
{switch(telLetter.charAt(i))
{case 'A':case 'B':case 'C': case 'a': case 'b': case 'c':
telNumber += "2";
count++;
break;
case 'D':case 'E':case 'F': case 'd': case 'e': case 'f':
telNumber += "3";
count++;
break;
case 'G':case 'H':case 'I': case 'g': case 'h': case 'i':
telNumber += "4";
count++;
break;
case 'J':case 'K':case 'L': case 'j': case 'k': case 'l':
telNumber += "5";
count++;
break;
case 'M':case 'N':case 'O': case 'm': case 'n': case 'o':
telNumber += "6";
count++;
break;
case 'P':case 'R':case 'S': case 'p': case 'r': case 's':
telNumber += "7";
count++;
break;
case 'T':case 'U':case 'V': case 't': case 'u': case 'v':
telNumber += "8";
count++;
break;
case 'W':case 'X':case 'Y':case 'Z': case 'w': case 'x': case 'y': case 'z':
telNumber += "9";
count++;
break;
}
if( count==3) {
telNumber += "-";
}
i++;
}
System.out.println( telNumber );
}
}}
Fixes in code:
Use while(count < telLetter.length()) in place of while(count <7)...
telLetter.charAt(i) can be removed by (telLetter.charAt(count))... By doing this you don't need to create an extra variable int i = 0;... Its a good practice to keep variable minimum.
Use a scanner to get the input... Like.. Scanner sc = new Scanner(System.in); String telLetter = sc.next();...
After you used your resources do close them by using sc.close();....
Also i can see that you are appending 7 at the begining of every number... if that's a requirement then its ok.. other wise you can use... String telNumber="";
I would recommend using StringBuilder because in one object you can do it all.. While appending a character every time in string you are continuously creating a new string and giving it the reference of telNumber.
Also in your code either remove telLetter = telLetter.toUpperCase(); or remove the cases with lowercase alphabets.. because on making toUpperCase() you are just writing extra lines by writing cases for lowercase characters that are not needed...
System.out.println("Enter a word to be converted: ");
Scanner scan=new Scanner(System.in);
String telLetter = scan.next ();
int stringLength=telLetter.length();
telLetter = telLetter.toUpperCase();
String telNumber="7";
while(count <stringLength)
{
switch(telLetter.charAt(count))
Change your code like this.
But as per your code, the 7 is always prefixed in the converted phone number.
String telNumber=""; telNumber should be declared with empty string.
while(count <7)
Your code won't end until it has run through 7 characters. Try using while(count < telLetter.length())
Your while loop condition needs to check for the length of the telLetter string.
while (count <7 && count < telLetter.length())
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i want java code using switch to same execute ? how i can do this by java
if(ave>=90.0)
return 'A';
else if(ave>=80.0)
return 'B';
else if(ave>=70.0)
return 'C';
else if(ave>=60.0)
return 'D';
else
return 'F';
The intuitive solution is: It's impossible.
A switch needs a discreet set of elements. A range of numbers is infinite and you can't do
switch(something) {
case 90.0:
case 90.000000000001:
....
There is a way you could do that though: Convert the range to some number:
private static int toRangeIndex(double d) {
if (d >= 90.0)
return 0;
else if (d >= 80.0)
return 1;
else if (d >= 70.0)
return 2;
else if (d >= 60.0)
return 3;
else
return 4;
}
public static double sumColoumn(double[][] m, int coloumnIndex) {
switch (toRangeIndex(ave)) {
case 0:
return 'A';
case 2:
return 'B';
case 3:
return 'C';
case 4:
return 'D';
default:
return 'F';
}
}
This is obviously not better in your case. But there are cases in which you could use such a technique.
Not possible directly, switch requires exact match.
What you can do is write function like:
int classify(double avg) {
// perform some if-else chain, or loop with test inside, or calculation:
return (int)(avg/10.0);
}
Then use the return value in switch:
switch (classify (avg)) {
case 10: // average of exact 100.0 gives 10, let's not F that...
case 9:
return 'A';
case 8:
return 'B';
//...
default:
return 'F';
}
But, in your specific case it is just moving the if... ladder into a different function, and probably not good idea. So don't do it :-).
Or rather, if you do it, do it because it makes code easier to understand and maintain (and here it in my opinion does not), not because you want to use switch statement.
int findIndex(double ave){
int index=(int)(ave/10.0);
if(index>=9)
return 9;
else
return index;
}
switch (findIndex(ave)) {
case 9:
return 'A';
case 8:
return 'B';
case 7:
return 'C';
case 6:
return 'D';
default:
return 'F';
}
i finded answer
switch(t1)
{
case 100: case 99: case 98: case 97:case 96:case 95:case 94:case 93:case 92:case 91:case 90:
cr='A';
break;
case 89: case 88: case 87: case 86:case 85:case 84:case 83:case 82:case 81:case 80:
cr='B';
break;
case 79: case 78: case 77: case 76:case 75:case 74:case 73:case 72:case 71:case 70:
cr='C';
break;
case 69: case 68: case 67: case 66:case 65:case 64:case 63:case 62:case 61:case 60:
cr='D';
break;
default:
cr = 'F';
break;
}