Java issue using parseInt with a try catch block - java

I am working on an exercise, where I have to select a category(genre) of movie and based on my selection, the program will return a list of movies in that category from an ArrayList of objects.
My program works when typing out a category in string format. However I am trying to use a try catch block to also allow category selection by number.
My catch block is working, however my try block is not and returns nothing. Can someone help me determine what is wrong with my code? I am guessing there is something wrong with my parseInt assignment?
System.out.print("What category are you interested in?");
String catSel = sc.next();
try //Check category for Integer, otherwise catch
{
int numSel = Integer.parseInt(catSel);
if(numSel == 1)
{catSel = "animated" ;}
if(numSel == 2)
{catSel = "drama";}
if(numSel == 3)
{catSel = "horror";}
if(numSel == 4)
{catSel = "scifi";}
if(numSel == 5)
{catSel = "musical";}
if(numSel == 6)
{catSel = "comedy";}
else catSel = "";
//Check each movie for chosen category
for(int x = 0; x < list.size() - 1; x++)
{
if(catSel.equals(list.get(x).category))
System.out.println(list.get(x).movie);
}
}
catch (NumberFormatException e)
{
//Check each movie for chosen category
for(int x = 0; x < list.size() - 1; x++)
{
if(catSel.equals(list.get(x).category))
System.out.println(list.get(x).movie);
}
}

the way your if-clauses are structured, the else clause will be called whenever numSel is not 6, replacing catSel with the empty string.
You may want to add an else after each if block or replace all of them with a switch statement.

As #Dragondraikk suggested your if-else clauses are structured in a way which is not as per your expected result .
So either use in this way :
if(someCondition){
}
else if(someCondition){
}
...........................
do whatever you want to do
...........................
else{
}
Below is the way to use Switch Statement
switch(Integer.parseInt(catSel)){
case 1 :
do Something....
break;
case 2 :
do Something....
break;
case 3 :
do Something....
break;
case 4 :
do Something....
break;
case 5 :
do Something....
break;
case 6 :
do Something....
break;
default :
catSel="";
break;
}
Note : You can use try-catch block around this
Update
Advantage of Using Switch over If else
The problem with the if...else if... chain is readability , I have to look at every single if condition to understand what the program is doing. For example, you might have something like this:
if (a == 1) {
// stuff
} else if (a == 2) {
// stuff
} else if (a == 3) {
// stuff
} else if (b == 1) {
// stuff
} else if (b == 2) {
// stuff
}
(obviously, for a small number of statements like this, it's not so bad)
but I'd have no way of knowing that you changed condition variable half-way through without reading every single statement. However, because a switch limits you to a single condition variable only, I can see at a glance what's happening.
Another advantage is JumpTable
A switch is often compiled to a jump-table (one comparison to find out which code to run), or if that is not possible, the compiler may still reorder the comparisons, so as to perform a binary search among the values (log N comparisons). An if-else chain is a linear search .
Here is more about Switch Statement

Related

Proper Format for a Switch/Case in a Class

Good Evening,
I created this method for a class. I used a switch/case to execute depending on the value of expression. I included an if-else method for each case. I do get an error on case 1-> switch rules are a preview feature and are disabled by default. I attempted to add a : after case 1 and case 2but my results reached high numbers for the sets. I changed the : to -> and it worked appropriately. Now I am wondering if this was a proper way to set the case statements or should it be written differently.
private void playGame()
{
double winCheck = Math.random();
switch (matchServer) {
case 1 ->{
if (winCheck <= player1WinProb)
player1GamesWon++;
else
player2GamesWon++;
matchServer = 2;
}
case 2 ->{
if (winCheck <= player2WinProb)
player2GamesWon++;
else
player1GamesWon++;
matchServer = 1;
A correct switch statement must use ':'
Also, 'break' is missing. This to avoid executing next cases.
You can add 'default' that means that case 1 and case 2 were not presented.
switch (matchServer) {
case 1:
if (winCheck <= player1WinProb)
player1GamesWon++;
else
player2GamesWon++;
matchServer = 2;
break;
case 2:
if (winCheck <= player2WinProb)
player2GamesWon++;
else
player1GamesWon++;
matchServer = 1;
break;
default:
//If it was not 1 or 2
//Printing the values can help
}

Breaking out of nested if

I have a bit of code that contains nested if statements:
if(numberOfNeighbors == 1){
//go through comparison again, add Pixel(i,j) to current linked list -> complist[numberOfComponents]
// break out of large check ??
if(ji.getPixelColor(i, j) == (ji.getPixelColor(i-1,j-1))){ //compare to top left
complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
}
if(ji.getPixelColor(i, j) == (ji.getPixelColor(i,j-1))){ // compare to top
complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
}
if(ji.getPixelColor(i, j) == (ji.getPixelColor(i+1,j-1))){ // compare to top right
complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
}
if(ji.getPixelColor(i, j) == (ji.getPixelColor(i-1,j))){ // compare to left
complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
}
} // end of if(numberOfNeighbors == 1)
Basically what I would like to do, however inefficient this may be, is compare a something 4 times, but if it turns out it is a match, break out of the set of the 4 nested if statements, as well as the outer if statement.
Will this work? or will it just break out of the nested if its currently at and continue to the next until its gone through all 4?
IMPORTANT: break statements are used to come out of loops but not branches
I understood your question but use break statement to go out of loops like for, while, do while. You can go out of if statement when the condition is satisfied and statements inside the if branch are executed. If you don't want to check for other conditions when your first if is satisfied you have to use if else branches instead of using 4 if statements.
These two links might be useful
if else document
break document
See the below example
if(condition) {
if(condition) { //if this evaluates to true, logic1 is executed
logic1;
}
else if(condition) { //if the above condition fails, but this condition satisfies then logic 2 is executed
logic2;
}
else { //if the above 2 conditions fail, you can execute logic3
logic3;
}
}
Are you looking for else?
if(numberOfNeighbors == 1){
//go through comparison again, add Pixel(i,j) to current linked list -> complist[numberOfComponents]
// break out of large check ??
if(ji.getPixelColor(i, j) == (ji.getPixelColor(i-1,j-1))){ //compare to top left
complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
}
else if(ji.getPixelColor(i, j) == (ji.getPixelColor(i,j-1))){ // compare to top
complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
}
else if(ji.getPixelColor(i, j) == (ji.getPixelColor(i+1,j-1))){ // compare to top right
complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
}
else if(ji.getPixelColor(i, j) == (ji.getPixelColor(i-1,j))){ // compare to left
complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
}
} // end of if(numberOfNeighbors == 1)
break; does NOT work for if statements, only loops, switch and such.
You can do this to avoid nesting:
if(mainCondition)
{
if(condition1)
goto LabelContinue;
bool condition2 = logic...;
if(condition2)
goto LabelContinue;
//Code
}
LabelContinue:
//Other code.

Looking for help on creating more efficient way on doing a lot of checks

Note: Not a duplicate of How do I compare strings in java as I am taking about going through some checks to determine if something is inheriting something something else
Is their a better and more efficient way to do this:
As you can see I am inputting 2 strings then checking them of on a list, as if current = three then it returns true for checking for one, two and three
NOTE: these values(one,two,three) are just placeholders for the example in my use their is no relation between them except that they have a different priority.
public boolean checker(String current, String check) {
if (check.equals("one")) {
if (current.equals("one") || current.equals("two")
|| current.equals("three")) {
return true;
}
}
if (check.equals("two")) {
if (current.equals("two") || current.equals("three")) {
return true;
}
}
if (check.equals("three")) {
if (current.equals("three")) {
return true;
}
}
return false;
}
Here are a few pointers
As Frisch mentioned in comments, use .equals rather than == for String comparison.
Use switch/case
switch (check) {
case "one":
if (current.equals("one")) return true;
case "two":
if (current.equals("two")) return true;
case "three":
if (current.equals("three")) return true;
}
Apart from that, there doesn't seem to be much to do.
Two things.
Don't check strings using equality. Use the .equals() method. You can call it off the string literal. So something like this. Calling it off the string literal is safe even with nulls, which is generally a good thing.
if ("one".equals(check))
You can take advantage of Java's short circuit operators && and ||
if ("one".equals(check)) {
if ("one".equals(current) || "two".equals(current) || "three".equals(current)) {
return true;
}
}
Can become
if ("one".equals(check) && ("one".equals(current) || "two".equals(current) || "three".equals(current))) {
return true;
}
Which will be evaluated from left to right. Since the "one".equals(check) is on the far most left, and is &&'ed with the rest of the statement, Java will bail out of the condition checking if "one".equals(check) is not true, and will not evaluate the rest of the statement.
Since you're just returning true or false, you can also take this a step further and reduce all of your if statements into a single one using De Morgan's laws (http://en.wikipedia.org/wiki/De_Morgan's_laws). Generally you state your boolean if statement in the way that is most natural to you, and then you start simplifying it by applying transformations that keep the logical if statement the same.
A good example of this is, stolen from the below link.
In the context of the main method's program body, suppose the following data is defined:
int score, min = 0, max = 20;
boolean bad, good;
Further suppose that a value is assigned to score, perhaps from a keyboard entry, and I would like to test, with a Boolean expression whether the score is a valid number or not. A good score is in the closed range [0 .. 20], which includes 0 and 20.
good = (score >= min && score <= max);
I would like to get the score from the keyboard in a do while loop, so that I can validate the entry. The logic in my control structure is to demand another entry for the score while the entry is bad. I have a definition of a good entry, and I will use definitions of operators and De Morgan's Law to help me write an expression that represents a bad entry.
good = (score >= min && score <= max); // original definition of good from the logic of my task
good = !(score < min) && !(score > max); // by definition, >= means ! < , <= means ! >
good = !(score < min || score > max); // by De Morgan's' Law
bad = !good ; // bad is not good
bad = !!(score < min || score > max); // substituting for good
bad = score < min || score > max; // double negation is dropped
http://fcmail.aisd.net/~JABEL/1DeMorgansLaw.htm
I would like to update you some thing.
1. We can apply switch cases only on primitive data types but not on objects. As string is object we can't use strings in case/switch statement.
I would like to suggest you to enums/maps in this case.
Please find the below sample programm how i implemented using maps.
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<String, Integer>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
String current = "one";
String check = "one";
if(map.get(check)<=map.get(current)){
System.out.println("Our condition is success");
}
}
Instead of multiple comparison this is better.
---Santhosh

Can you use conditional statements in switch-case in Android?

I can't seem to find a straight forward yes or no to this in my searching. In Android, is there a way to use a conditional statement in case-switch? For example, with age being an int value:
switch (age){
case (>79):
// Do this stuff
break;
case (>50):
// Do this other stuff
break;
etc, etc
I've tried several ways to code this (completely shooting in the dark) and come up with compiler errors, and I've also tried a nested IF statement, but it doesn't support break so the logic breaks down and it ends up also executing ELSE code lower in the nesting. I feel like switch-case is my best bet but I can't find an example of the correct syntax for what I'm trying to do! Any help would be appreciated. All the examples I find just use switch-case for a few things like if it is a 1 do this, if it's a 2 do that, but without making 100 case statements to check against age, I'm not sure how else to work this.
No. You cannot do this,
switch (age){
case (>79):
// Do this stuff
break;
case (>50):
// Do this other stuff
break;
}
You need an if and else,
if (age > 79) {
// do this stuff.
} else if (age > 50) {
// do this other stuff.
} // ...
It is not possible. Instead, Try this minimalist approach
age > 79 ? first_case_method()
: age > 50 ? second_case_method()
: age > 40 ? third_case_method()
: age > 30 ? fourth_case_method()
: age > 20 ? fifth_case_method()
: ...
: default_case_method();
You can't do this use if then statement.
if(age > 79)
{
//do stuff
}
else if(age > 50)
{
//do stuff
}
else
{
/do stuff
}
etc...
If you are using a loop you might want to look at What is the "continue" keyword and how does it work in Java?. This is not a good place to use switch.
if(age > 79)
{
//do stuff
continue; // STOP FLOW HERE AND CONTINUE THE LOOP
}
else if(age > 50)
{
//do stuff
continue; // STOP FLOW HERE AND CONTINUE THE LOOP
}
each case of switch is supposed to be an integer or String since JavaSE 7 and you are trying to feed a boolean value to it so its not possible .Read oracle doc to know about java switch in detail
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
You can't use conditional statements with switch.
But you CAN do it with if statements! If you have a loop you can use continue to stop any upcoming lines and start from the beginning of the innermost loop.
if(age>76){
// Code...
continue;
}else if(age>50){
// More Code...
continue;
}else{
// Even more code...
continue;
}
It can be done.
The code needs to be slightly altered.
public static void main(String[]arguments)
{
int x=1, age=55;
switch(x)
{
case 1: if((age>=60)&&(age<200))
System.out.println("Senior Citizen");
case 2: if((age>=18)&&(age<60))
System.out.println("Adult");
case 3: if((age>=12)&&(age<18))
System.out.println("Teenager");
break;
default :
System.out.println("Child");
break;
}
}

How to execute code based on integer value

I have an int, int minion1Hp, which can be a value of 0 -> 20. Depending on the value it is, a certain image resource will be set for an ImageView, using bar1.setImageResource(R.drawable.hpa);. However, my code currently looks like this:
if (minion1Hp == 0) {
bar1.setImageResource(R.drawable.hp);
}
if (minion1Hp == 1) {
bar1.setImageResource(R.drawable.hpa);
}
if (minion1Hp == 2) {
bar1.setImageResource(R.drawable.hpb);
}
if (minion1Hp == 3) {
bar1.setImageResource(R.drawable.hpc);
}
if (minion1Hp == 4) {
bar1.setImageResource(R.drawable.hpd);
}
if (minion1Hp == 5) {
bar1.setImageResource(R.drawable.hpe);
}
... and so on. Is there a more efficient way of doing this, rather than a long list of if statements?
Suggestion: initialize a map at startup (say in onCreate()). Like this:
mDrawables = new HashMap<Integer, Integer>();
mDrawables.put(0, R.drawable.hp);
mDrawables.put(1, R.drawable.hpa);
...
then just do:
bar1.setImageResource(mDrawables.get(minion1Hp));
You can use a switch statement with a separate case for each instance. On a side note, you shouldn't be using just if statements up there, your code will run slowly, you should be using else if to make it run faster (since your hp can never be 1 and 2 at the same time.
Ex for switch statements:
switch (minion1Hp){
case 1:
bar1.setImageResource(R.drawable.hp);
break;
case 2:
bar1.setImageResource(R.drawable.hpa);
break;
etc.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
An improvement here would be to change each if after the first one to an else if as minion1Hp can't be multiple values at the same time, but you might find it slightly neater to have the whole thing in a switch-case block instead.

Categories