is it possible to use this switch statement in Java - java

C++ has a very handy switch statement, but I don't know if this is possible is java
switch(num)
{
case 1 ... 9:
do something
break
case 10 ... 19:
do something
break
default: something
}
is this possible in java, I've tried, but it doesn't work, at least not like c++, is there an equivalent for this?
thanks

Java's switch statement requires you to explicitly list all values that you match (except for the default: clause, of course). If you're doing substantial ranges, it is probably better to use a chain of ifs:
if (num >= 1 && num <= 9) {
do_something_A
} else if (num >= 10 && num <= 19) {
do_something_B
} else {
do_something_C
}
If your real num has side effects (or is plain expensive to compute), evaluate it once and save it to a local variable, then use that local in the chain of tests.

No, it's not possible. Probably the most straightforward equivalent is:
if (num >= 1 && num <= 9)
doSomething();
else if (num >= 10 && num <= 19)
doSomethingElse();
else
doDefault();
Marginal cleanup could be defining an inRange utility function and using it inside the if statements:
boolean inRange(int num, int min, int max) {
return num >= min && num <= max;
}
...
if (inRange(num, 1, 9))
doSomething();
else if (inRange(num, 10, 19))
doSomethingElse();
else
doDefault();

Java have switch statement, but you have to use it in this way :
switch(num)
{
case 1:
case 2:
case 3:
case 4:
//And so far with cases
//do something
break
case 10:
case 11:
case 12:
//And so far ...
//do something
break
default: something
}

Yes, there is a switch statement in Java. It is in fact quite similar to switch in C++.
However, neither C++ nor Java support ranges in case labels.
For the specific example that you present I would use a series of if statements:
if (num >= 1 && num <= 9) {
...
} else if (num >= 10 && num <= 19) {
...
} else {
...
}

No Java does not, in a situation like this it would be much more practical to use a series of if-else statements. :)
if(num >= 1 && num < 10) {
//do something
} else if(num >= 10 && num < 20) {
//do something
} else {
//do something
}

The feature you are talking about doesn't really belong to C++, it is a language extension which is present, for example, in GCC. But normally in C++ ranges are checked using if...else, and the same technique should be used in Java:
if (num >= 1 && num <= 9) {
//Do something
} else if (num >= 10 && num <= 19) {
//Do something else
} else {
//Do something by default
}

No, ranges are not allowed you would need to use an if else structure.

Related

Displays if a whole number (>0) is divisible by 2 and 3

I have tried to do this in java however the && symbols keep on giving error.
Below is the code that I used:
int d = 18;
{
if ((d % 2) && (d% 3));
{
System.out.println("True!");
}
{
System.out.println("False!");
}
}
This is my code. I am not sure why its not working. Thanks
The error message is The operator && is undefined for the argument type(s) int, int. #
I have got it to work now. I have an else error . "The error says Syntax error on token "else", delete this token"
public class CS1702_Lab3_4 {
int d = 18;
{
if ((d % 2 == 0) && (d % 3 == 0));
{
System.out.println("True!");
}
else
{
System.out.println("False");
}
}
}
Also when I add an else it says Syntax error on token "else", delete this token
Please learn about the modulus operator, and how to check divisibility in java.
if ((d % 2 == 0) && (d % 3 == 0))
{
System.out.println("True!");
}
Also, you had a rogue semi-colon at the end of your if statement.
EDIT: Fixed code
public class CS1702_Lab3_4 {
public static void main(String[] args) { // Entry into our program
int d = 18;
if ((d % 2 == 0) && (d % 3 == 0)) {
System.out.println("Divisible!");
} else {
System.out.println("Not divisible!");
}
}
}
I'd recommend looking at some basic Java tutorials, however the fixes I applied included:
Contained your code inside of a method, specifically the main method, which is the entry point to a runnable Java application. Java is not a procedural language, code outside of variable, method, class, package and import declarations need to be contained inside of a method
Fixed syntax on your if statement, removed rogue semi colon
if ((d % 2) && (d% 3)); you have a semicolon ; at the end,
remove it.
If d == 18, then ((d%2) && (d%3)) = (0 && 0) = 0 So in this
case, What java sees is: if(0){ // ... }
If I remember correctly, this is valid in C/C++, but not in Java. That is why you get error.
Anyways, to fix the problem, you can do this:
if (((d % 2) == 0) && ((d % 3) == 0)){
System.out.println("Divisible!");
} else {
System.out.println("Not divisible!");
}
if condition expects boolean. Mod operation would not return boolean, this is why compiler is intelligent and gives you this error.
if you try to run
if (1 && 2) // this will give you an error as well.
The expressions need to evaluate to a boolean (either true or false) in order to understand operators like && and ||
Moreover, you statement will not work since you are using ; at the end.

How to convert if-statements to switch statements

My code is supposed to convert scores to letter grades, so I used if statements. Just wondering if there's a way to use a switch statement instead of if-statements. I have no idea how to convert it. Also, is one better than the other?
public static void determineGrade(int numArray[], char letterArray[]) {
int scoreCount = numArray.length;
for (int i=0; i < scoreCount; i++) {
if (numArray[i] >= 90 && numArray[i] <=100) {
letterArray[i] = 'A';
}
if (numArray[i] >= 80 && numArray[i] < 90) {
letterArray[i] = 'B';
}
if (numArray[i] >= 70 && numArray[i] < 80) {
letterArray[i] = 'C';
}
if (numArray[i] >= 60 && numArray[i] < 70) {
letterArray[i] = 'D';
}
if (numArray[i] >= 0 && numArray[i] < 60) {
letterArray[i] = 'F';
}
}
displayTestScores(numArray, letterArray);
public char getGrade(int input){
switch(input/10)
{
case 9: return 'A';
case 8: return 'B';
case 7: return 'C';
case 6: return 'D';
default: return 'F';
}
}
Then
for (int i=0; i < scoreCount; i++) {
letterArray[i] = getGrade(numArray[i]);
}
You can switch statement in this case but I wouldn't recommend due to the fact you will have way too many cases. You will use at least 100 cases to input because of your if statement conditions.
case 100 ://code
break;
case 50 ://skip a bit
case 0 :
There is way too many cases and a waste of time and lines.
Your conditions are ranges. Java switch statements have cases for values, not ranges.
Since you have a limited number of cases, you could list each one of them independently. However, this would make your code much longer, with 100 cases.
And there's also some math trickery you could do to find the lower number divisible by 10, and switch on that. But the if statement is simpler to implement and read.
All that said, your second expression in the if statements is unnecessary, if you use an else statement, not an independent if. And you want to use an else, because it would be silly to continue checking all the remaining cases after the first one whose condition is met.
if (numArray[i] >= 90 ) { // Can you have values > 100?
letterArray[i] = 'A';
}
else if (numArray[i] >= 80 ) { // If we're checking this, we know numArray[i] < 90
letterArray[i] = 'B';
}
else if ...
You're looking to produce a switch statement that has cases based on ranges. It's not really what switch statements are meant for. the if route is more elegant/a better solution for your case imo.
In Java,Using switch statement with a range of value in each case?

Supposed variable cannot be resolved as variable?

I'm doing a basic Java tutorial and below is the question.
Write a method that prints the numbers from 1 to 100. But for multiples of three print ÒFizzÓ instead of the number,and for the multiples of five print ÒBuzzÓ. For numbers which are multiples of both three and five print ÒFizzBuzzÓ."
My code is below
public static void fizzBuzz(){
for(int i = 0; i < 101; i= i +1 )
System.out.println(i);
if (i%3 == 0){
System.out.println("ÒFizzÓ");
}else if (i % 5 == 0){
System.out.println("ÒBuzzÓ");
}else if (i % 15 == 0){
System.out.println("ÒFizzBuzzÓ");
}
}
Eclipse tells me that "i" cannot be resolved as a variable. This is confusing to me as I thought I already defined "i" as an integer in my for loop? Thanks for taking the time to solve this newbie question :)
Add braces or your loop body ends after the first statement. Also, for your approach you need to test 15 first because it's a multiple of 3 and 5
for(int i = 0; i < 101; i++) { // <-- i++ is short for i = i + 1
System.out.println(i);
if (i % 15 == 0) {
System.out.println("ÒFizzBuzzÓ");
} else if (i % 5 == 0) {
System.out.println("ÒBuzzÓ");
} else if (i % 3 == 0) {
System.out.println("ÒFizzÓ");
}
}
I know a funny story about Apple who lost a few million dollars because a developer updated a code with an if block but... the if statement had only one instruction and no curly brackets and he did not see it. Thus, the code he was willing to add when the condition was met were actually ALWAYS executed.
In your case, you won't lose money but you surely did the same mistake :
for(int i = 0; i < 101; i= i +1 ) {
System.out.println(i);
if (i % 15 == 0){
System.out.println("ÒFizzBuzzÓ");
} else if (i%3 == 0){
System.out.println("ÒFizzÓ");
} else if (i % 5 == 0){
System.out.println("ÒBuzzÓ");
}
}
When Java says something cannot be resolved as a variable, it is usually been used outside the scope it was declared or it was not declared at all.In your case, your braceless for-loop is causing the problem.

Convert Integer to int in Java

I find a very weird situation when writing Java code:
Integer x = myit.next();
if ((int)x % 2 == 0) {
In which myit is an Iterator and x is an Integer.
I just want to test whether x is an even number or not. But x % 2 == 0 does not work since eclipse says % not defined on Integer. Then I try to convert x to int by explicitly converting. Again, it warns me that not able to convert in this way.
Any reason why it happened and what is the right way to test if x is even ?
UPDATE:
ANYWAY,I test it that the following code works, which means all of you guys are right.
Integer x = 12;
boolean y = ( (x % 2) == 0 );
boolean z = ( (x.intValue() % 2) == 0 );
I think the problem I have before may be the context of the code. It is late night, I would update later if I find why would that thing happen.
Use :
if (x.intValue() % 2 == 0)
PS : if(x % 2==0) should also work because integer.intValue() should be called internally.
Byte code for :if(x % 2==0)
11: invokevirtual #23; //Method java/lang/Integer.intValue:()I --> line of interest
14: iconst_2
15: irem
x % 2 == 0 does not work since eclipse says % not defined on Integer
This is not true. You can use % with Integer
take a look at this
Integer x = new Integer("6");
if (x % 2 == 0) {
System.out.println(x);
}
Out put:
6
You should read about Integer in Java
public static void main(String[] args) {
List<Integer> myList = new ArrayList<Integer>();
myList.add(21);
myList.add(22);
myList.add(41);
myList.add(2);
Iterator<Integer> itr = myList.iterator();
while (itr.hasNext()) {
Integer x = itr.next();
if (x % 2 == 0) {
System.out.println("even");
} else {
System.out.println("odd");
}
}
}
Output
odd
even
odd
even
Use this:
if(((int)x)%2==0){
Note: one more (

Elegant way to code if (10 < x < 20)

Is there an elegant way in Java to code:
if (10 < x < 20) {
...
}
i.e. "if x is between 10 and 20"
rather than having to write
if ((x > 10) && (x < 20)) {
...
}
Thanks!
No. The < operator always compares two items and results in a boolean value, so you cannot chain them "elegantly". You could do this though:
if (10 < x && x < 20)
{
...
}
Kenny nailed it in the comments.
if (10 < x && x < 20)
You want to keep them either both less-than or both greater-than; reversing the direction of the comparison makes for a confusing bit of logic when you're trying to read quickly.
No but you can re-arrange it to make it better, or write a wrapper if it irks you:
if (InRange(x, 10, 20)) { ... }
Or, as Carl says:
if (new Range(10, 20).contains(x)) { ... }
Though personally, I don't see the point. It's a useless abstraction. The bare boolean statement is perfectly obvious.
Though, now that I think about it, and in light of Carl's comment below, there are times when a Range is a perfectly valid and useful abstraction (e.g. when dealing with Feeds). So, depending on the semantics of x, maybe you do want an abstraction.
if(x < 20)
{
if(x > 10)
{
//...
}
}
OR
if(x > 10)
{
if(x < 20)
{
//...
}
}
The only thing you can do is loose the extra parenthesis since the && has a lower precedence than > and <:
if (x > 10 && x < 20) {
...
}
Other than that: there's no shorter way.
The FASTEST way is a switch.
EDIT:
switch(x) {
case 10:
case 11:
case 12:
case 13:
...
case 19: System.out.println("yes");
}
is compiled into a jump table, not a long series of ifs.

Categories

Resources