Why is this switch statement only returning the default? - switch-statement

switch (numYears) {
case 10:
intsRate = 0.06;
break;
case 15:
intsRate = 0.05;
break;
case 30:
intsRate = 0.04;
break;
default:
intsRate = 0.08;
break;
}
return intsRate;
}
when the input of numYears is 10, 15, or 30 its returns the according double, but its only returning the defult. its part of a larger code but everything in that code is right this is the only part returning the wrong thing.

Related

a groovy switch case statement with several variables

Is it possible to have a switch-case statement with more than a variable in groovy? I tried with tuples but the case part doesn't accept more than one argument.
I am trying to avoid several nested if statements so instead of
if (a==1) {
if (b==2) {
if (c==3) {
// do something
}
}
}
else {
if (a==4) {
if (b==5) {
if (c==6) {
//do something else
}
}
}
}
Can I do:
switch(a,b,c) {
case : (1,2,3) // if a==1, b==2 and c==3
// do something
...
case : (4,5,6)
// do something else
...
}
}
Groovy is just dirty java, you don't need any class definition. everything you write in a java method you can write it directly in groovy.
switch (num) {
case 1:
case 2:
case 3:
System.out.println("1 through 3");
break;
case 6:
case 7:
case 8:
System.out.println("6 through 8");
break;
}
To answer your question, inside the switch we need an expression, not function parameters.
Based on your edit, I believe that this should work:
if (a == 1 && b == 2 && c == 3) {
// do something
} else if (a == 4 && b == 5 && c == 6) {
// do something else
}
If you want a switch statement instead, that's possible:
def val = [a, b, c]
switch (val) {
case {it == [1, 2, 3]}:
// something
break;
case {it == [4, 5, 6]}:
// something else
break;
class Solution{
static void main (String...args){
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in))
def val=br.readLine()
switch(val){
case('E0'):
println "Basic"
break;
default:
break;
case('E1'):
println "Inter"
break;
case('E2'):
println "Advance"
break;
default:
println "not defined"
}
}
}

My switch(case) , keeps evaluating more than one case statement's

My problem is that my switch (case) statement keeps evaluating an extra switch case statement. And I don't understand why it's doing this.
My problem is in case 10:
It's always being evaluated, doesnt matter what case # i choose. It will always run to case 10: and evaluate if it's true or not.
I'v been going over it and I don't understand what's going on. Why would it read case 10.
public boolean checkIfPossible(double x, double a, double y) {
boolean pass;
int value = spinnerA.getSelectedItemPosition();
switch (value) {
case 1:
if (x > a && a == 0) {
etX.setError("Error1 ");
pass = false;
break;
} else if (x == a) {
etX.setError("Error2);
pass = false;
break;
}
case 10:
if (x == y) {
etX.setError("Error3");
pass = false;
break;
}
default:
pass = true;
}
return pass;
}
The solution to your problem is to put a break statement after your if and else statements in your case 1 like this:
case 1:
if (x > a && a == 0) {
etX.setError("Error1 ");
pass = false;
}
else if (x == a) {
etX.setError("Error2);
pass = false;
}
break;
The most likely reason you are having this problem is because the conditions for your if and else-if are both not satisfied. There is no break statement to stop the flow (since the if and else-if blocks are not executed). That's why your code eventually spills over to the next case. Try logging the value of x and a to verify.
I hope this helps.. Merry coding!

(beginner) How to use a switch statement with strings?

I'm trying to make a simple bank account program to learn classes and OOP. As you may guess, I'm new to Java.
Anyways, my switch statement is not working. I'm trying to make each case based on an inputted string.
Scanner input = new Scanner(System.in);
System.out.println("Enter your name");
//the user enters "user1", "user2", or "user3".
String user = input.next();
//swtich time
switch (user) {
case "user1":
System.out.println("Your balance is" + user1.balance);
System.out.println("Your Account numer is" + user1.acctnum);
//shows the balance and account number for user1
case "user2":
System.out.println("Your balance is" + user2.balance);
System.out.println("Your Account numer is" + user2.acctnum);
case "user3":
System.out.println("Your balance is" + user3.balance);
System.out.println("Your Account numer is" + user3.acctnum);
}
You're missing a break statement at the end of each case.
case "user1":
System.out.println("Your balance is" + user1.balance);
System.out.println("Your Account numer is" + user1.acctnum);
//shows the balance and account number for user1
break;
Without the break statement, all of these statements will be executed
Docs
You can use Strings in switch statements if you are using Java 7 or above, otherwise you can't
You can enumerate the string, and then use switch.
P.S: Please search around a bit and then post questions here ;) Your question is similar to this one (for ex - there are plenty of answers out there)
https://stackoverflow.com/a/338284/878170
You are missing break; statement and hence all statements after selected case will be executed.
Here's an example of switch-case [1]
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
[1] http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Default statement position in switch

switch(2){
default : System.out.println("I am Default block");
case 1 : System.out.println("in 1");
case 2 : System.out.println("in 2");
}
The output : in 2
and if
switch(2){
case 1 : System.out.println("in 1");
case 2 : System.out.println("in 2");
default : System.out.println("I am Default block");
}
And the output is: in 2
I am Default block.
Does the positioning of the default statement behaves differently?
It's not the position of the default block, it's the use (or non-use in your case) of the break statement.
Once a case has been matched, the default behaviour is for the code to cascade through the rest of the cases.
To achieve the behaviour you desire, try
switch (2)
{
case 1:
System.out.println("in 1");
break;
case 2:
System.out.println("in 2");
break;
default:
System.out.println("I am Default block");
break;
}
Kathy Siera SCJP book do say that position of default: matters and if present in between the case statements, it follows the fall-through.
But practically it does not follow.
int a = 10;
switch (a)
{
case 5:
System.out.println("Its 5");
default:
System.out.println("Its default");
case 10:
System.out.println("Its 10");
case 20:
System.out.println("Its 20");
}
Output:
Its 10
Its 20

try/catch does nothing in Java ME

So I have the following code:
public class Minesweeper extends MIDlet implements CommandListener {
public static String error = "";
public void startApp() throws MIDletStateChangeException {
Display display = Display.getDisplay(this);
canvas = new MCanvas();
canvas.addCommand(exitCommand);
canvas.addCommand(okCommand);
canvas.addCommand(newCommand);
canvas.setCommandListener(this);
try{
display.setCurrent(canvas);
} catch (Exception e) {
error = e.toString();
}
}
}
When I leave display.setCurrent(canvas); outside of the try block, the app fails with a NullPointerException. When I comment out that line, the app works (although obviously no canvas is added). So the error is caused by that line, or something that that line causes.
So I suround that line with try/catch. Although the error is caused by that line, the error still happens when the line is surrounded by try/catch. How can I catch the error? (I've tried this using Throwable as well, and it is still not caught.
MCanvas:
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
public class MCanvas extends Canvas {
protected void paint(Graphics g){
//Minesweeper.p("repaint");
Space[] data = Minesweeper.topaint;
for(int x=0; x<data.length; x++){
data[x].print();
int r = data[x].row * 10;
int c = data[x].col * 10;
int v = data[x].value;
String s = "";
//System.out.println("r:"+Integer.toString(r)+" c:"+Integer.toString(c)+" s:"+Integer.toString(v));
g.setColor(250, 0, 0);
//Minesweeper.p("if");
if(data[x].open){
switch(v){
case 0:
g.setColor(50, 50, 50);
break;
case 1:
g.setColor(100, 50, 50);
s = "1";
break;
case 2:
g.setColor(150, 50, 50);
s = "2";
break;
case 3:
g.setColor(200, 50, 50);
s = "3";
break;
case 4:
g.setColor(250, 50, 50);
s = "4";
break;
case 5:
g.setColor(250, 100, 100);
s = "5";
break;
case 6:
g.setColor(250, 125, 125);
s = "6";
break;
case 7:
g.setColor(250, 150, 150);
s = "7";
break;
case 8:
g.setColor(250, 175, 175);
s = "8";
break;
case 9:
g.setColor(250, 200, 200);
break;
default:
g.setColor(250, 100, 100);
}
} else {
g.setColor(0,0,0);
}
g.fillRect(c, r, 10, 10);
g.setColor(250, 250, 250);
Font font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL);
g.setFont(font);
g.drawString(s, c+5, r+8, Graphics.HCENTER | Graphics.BASELINE);
if(data[x].hover){
g.setColor(250, 250, 250);
g.drawLine(c, r, c, r+9);
g.drawLine(c, r, c+9, r);
g.drawLine(c+9, r, c+9, r+9);
g.drawLine(c, r+9, c+9, r+9);
}
//Minesweeper.p("here?");
}
//Minesweeper.p("here");
//Minesweeper.p(Minesweeper.error);
if(Minesweeper.error != null){
g.drawString(Minesweeper.error, 10, 10, Graphics.HCENTER | Graphics.BASELINE);
}
Minesweeper.p("msg:"+Minesweeper.message);
g.setColor(0, 0, 0);
Font font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_LARGE);
g.setFont(font);
g.drawString(Minesweeper.message, this.getWidth()/2, this.getHeight()-10, Graphics.HCENTER | Graphics.BASELINE);
Font fontsm = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL);
g.setFont(fontsm);
}
protected void keyPressed(int keyCode) {
int gameaction = getGameAction(keyCode);
int c = Minesweeper.selected.col;
int r = Minesweeper.selected.row;
switch (gameaction) {
case UP:
Minesweeper.p("UP");
if(r>0){
Minesweeper.selected.leavehere();
Minesweeper.getSpace(Minesweeper.selected.row - 1, Minesweeper.selected.col).gohere();
}
break;
case DOWN:
Minesweeper.p("DOWN");
if(r<Minesweeper.height-1){
Minesweeper.selected.leavehere();
Minesweeper.getSpace(Minesweeper.selected.row + 1, Minesweeper.selected.col).gohere();
}
break;
case LEFT:
Minesweeper.p("LEFT");
if(c>0){
Minesweeper.selected.leavehere();
Minesweeper.getSpace(Minesweeper.selected.row, Minesweeper.selected.col - 1).gohere();
}
break;
case RIGHT:
Minesweeper.p("RIGHT");
if(c<Minesweeper.length-1){
Minesweeper.selected.leavehere();
Minesweeper.getSpace(Minesweeper.selected.row, Minesweeper.selected.col + 1).gohere();
}
break;
}
repaint();
}
}
As explained in Display.setCurrent API javadocs,
...The setCurrent() method returns immediately, without waiting for the change to take place...
Because of above, exceptions that may occur in calls triggered by setCurrent may (and most likely will) slip through your try-catch.
To be able to catch and report such exceptions, one should study what calls are triggered by setCurrent (in your case, these are explained in API javadocs for Canvas, Event Delivery section), cover these by try-catch blocks where appropriate and design the appropriate way to report exceptions if these occur.
In your case, try-catch could likely surround code in MCanvas.paint (this is where NPE likely occurs) and exceptions could be reported for example by showing appropriate screen with error message (eg Alert) by invoking setCurrent for that screen from catch block.
If I were you I would continue to insert try/catch blocks in the MCanvas class.
It is difficult for anyone to figure out where your NullPointerException occurs without seeing more of the code.
The only question I can come up with, from the code you pasted so far, is:
Does your Minesweeper class contain a static array of object Space called topaint? Did you declare it but maybe forgot to fill it with data?
Space[] topaint = new Space[20]; // Declared, but nothing in it yet.
Trying to access Minesweeper.topaint[0] will give a NullPointerException, unless you also do
topaint[0] = new Space();

Resources