I am writing some tests for a Java method which contains a switch statements but it seems that the "default statement" does not work. I only accept: Yes, No, Maybe. Everything else should return Maybe. My test always return the user input, does not matter what the user typed, so I guess my switch statement is not correct.
I have tried to move the default statement on the top
#Override
public String choice(String ans) {
getChoice = ans;
switch (ans) {
case "Yes":
break;
case "No":
break;
default:
getChoice = "Maybe";
}
return getChoice;
}
Thank you!
Your switch should work... As Kyle tells you "what are you overriding ?"
But why a switch when you can perform an "if then else" ?
Public String choice (String choice) {
If (choice.equals("yes") || choice.equals("no") {
return choice;
else {
return "maybe";
}
}
Switch is fine for multiple choices
Related
I'm having a bit of trouble getting a few parts of my code to work properly.
I'm still a bit new to java and could some direction and clues to where I went wrong.
The error comes from the if statements. I feel like i know why they are erring out because the || are undefined but I'm not sure how to fix it. What I'm trying to get it to do is take the inputs either L,R,F,B (left, right, forward and back). lowercase the input and either accept either one or the other using boolean "or".
import java.util.Scanner;
public class ChooseYourAdventure {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Choose a diection: ");
String direction = input.nextLine().toLowerCase();
System.out.printf(" %s and %s/n",getDirection (way),getYourChoice (found));
}
public static String getYourChoice (String found) {
String result = "Unknown";
switch (found)
{
case "l":
result = " now we all know you can turn left unlike Zoolander";
break;
case "left":
result = " now we all know you can turn left unlike Zoolander";
break;
case "r":
result = " you fall down a hole never to be seen again... sad.";
break;
case "right":
result = " you fall down a hole never to be seen again... sad.";
break;
case "f":
result = " YOU ARE THE KWISATZ HADERACH!!";
break;
case "forward":
result = " YOU ARE THE KWISATZ HADERACH!!";
break;
case "b":
result = " you are a scaredy cat but, you live to fight or runaway another day";
break;
case "back":
result = " you are a scaredy cat but, you live to fight or runaway another day";
break;
}
return result;
}
public static String getDirection(String way) {
String result;
if (way == "l" || "left") {
System.out.print("Your character moves left");
}
else if (way == "r" || "right") {
System.out.println("You character moves right");
}
else if (way == "f" || "forward") {
System.out.println("Your character moves forward");
}
else if (way == "b" || "back") {
System.out.println("Your character moves forward");
}
else {
System.out.println(" You cant go that way ");
}
return result;
}
}
All your if statements are wrong. When using || or &&, you need to specify the variable way on each side of the ||:
if (way == "l" || way == "left") {
System.out.print("Your character moves left");
}
This is kinda of a Noobie what about I am gonna ask but I am trying to get my Program to work I do not know how to Ask a question in a text box hit the button and it outputs the answer; I Have been researching this for a while I know how to get everything else to work.
So a simple Console app example:
static void Main()
{
bool exit = false;
string response;
while (!exit)
{
Console.Write("Command ('Exit' to end): ");
response = Console.ReadLine();
switch (response)
{
case "Hey":
Console.WriteLine("Welcome");
break;
case "unicorns":
Console.WriteLine("...are awesome!");
break;
case "Exit":
exit = true;
break;
default:
Console.WriteLine("Unrecognized command!");
break;
}
}
Console.Write("Press Enter to Quit");
Console.ReadLine();
}
My intention is to let the user decide which method to use by cheking its input.
I have the following code:
try {
String test = scan.next();
if(test == "y") {
//do stuff
}
else if (test == "n") {
//do stuff
}
} catch (Exception e) {
System.out.println("false");
}
I tried to analyze with the debugger. It is not jumping in the if-statement.
can you help me out here?
You need to use equals to compare strings
if(test == "y")
becomes
if (test.equals("y"))
Same for "n" obviously.
== test for reference equality, but you're looking for value equality, that's why you should use equals, and not ==.
I am trying to get to grips with C# having not coded for many years and my previous experience being in ANSI C.
I have read a number of books and searched online but one aspect is evading me and I am hoping someone here can help.
In the past I would declare a function and if there was a possibility of something not happening within the function (i.e. file not found etc.) declare the return to be an integer. I would then return 0 if all was well and a value if not. The value would correspond to where the function failed to execute fully and I could branch accordingly from where I called it.
if(function1())
{
// all my error stuff, maybe a switch/case etc.
}
All the examples I have found in C# seem to avoid this technique and I was hoping to get some understanding here.
Thanks in anticipation.
(I know I am a fossil). :)
Exceptions are the approach you use in C# and similar languages.
It goes like this:
try
{
function();
}
catch(FileNotFoundException e)
{
// File not found
}
catch(UnauthorizedAccessException e)
{
// User doesn't have right to access file
}
// etc...
To make this work, function shouldn't return a status code but instead throw an exception in case of an error.
Please note that the exceptions I illustrated in the code block above are thrown by the framework if you try to access a file and one of those errors is happening. So you don't actually have to do this yourself.
Furthermore, in C# there is no implicit conversion from integral values to bool, i.e. if(function()) is invalid, if function returns an int. You would need to write it like this:
if(function() != 0)
{
// all your error stuff
}
There's nothing to stop you doing this (though there are better ways of handling the errors - exceptions for example).
If you do want to carry on with this approach, the biggest problem you are having is that in C# you can't treat an integer as a boolean so your if test won't compile. What you need is:
if (function1() != 0)
{
}
But to check the value you'd need:
int result = function1();
switch (result)
{
case 1:
// Handle this case
break;
case 2:
// Handle this case
break;
default:
// All OK
break;
}
It would be better to return an enumerated type for each error case so that you don't have magic numbers, but exceptions are the way to go:
try
{
function1();
}
catch (SpecificException1 e1)
{
// Handle this case
}
catch (SpecificException2 e2)
{
// Handle this case
}
What you shouldn't have is a general exception handler:
catch (Exception e)
{
}
This just hides other potential problems.
If you want to follow that pattern of checking return value instead of managing errors, you better use enumarations than plain numbers.
For example:
public enum ResultType
{
Error = 0,
Success,
Waiting
}
public ResultType function()
{
if (still_waiting)
return ResultType.Waiting;
if (error_has_occured)
return ResultType.Error;
return ResultType.Success;
}
public void Main()
{
ResultType result = function();
switch (result)
{
case ResultType.Success:
MessageBox.Show("all is good");
break;
case ResultType.Waiting:
MessageBox.Show("still waiting...");
break;
case ResultType.Error:
MessageBox.Show("error has occurred");
break;
}
}
Behind the scenes, it's still using numbers but you put some meaning to each number.
if(function()==1)
{
}
int function()
{
int returnVal =0;
// do stuff
// if true return returnVal =1 else set returnVal =0;
return returnVal;
}
I would like to get whether (for example) the 3 key is pressed (KEY_NUM3).
I have tried getKeyStates but it only detects the game action keys.
How could I get the states of non-game action keys?
(I have overridden the keyPressed and keyReleased functions of Canvas and storing the key states in an array (I'm using a Vector for storing but I think could store them in an array too, if that's the problem), but this does not seem to be very nice)
in your keypressed use the keyCode passed in like so
protected void keyPressed(int keyCode)
{
//try catch getGameAction as can legally throw an exception
int gameAction = getGameAction(keyCode);
switch(gameAction)
{
case UP:
break;
case DOWN:
break;
case LEFT:
break;
}
switch(keyCode)
{
case KEY_NUM1:
break;
case KEY_NUM2:
break;
case KEY_NUM3;
break;
}
}
I suppose that can be
something like the code below
int key=getKeyStates();
// i mean keyStates();
if((key&down_pressed)!=0)
{
//do movements
}
but can be
if((key & Canvas.key_num3)!=0)
{
//do something
}
//you can set the super() to true in the constructor