This site requires JavaScript, please enable it in your browser!
Greenfoot back
Stalfoes
Stalfoes wrote ...

2015/9/27

How to use the act()?

Stalfoes Stalfoes

2015/9/27

#
Hi, I'm new at Greenfoot and Java in general. This'll probably be a quickly answered question if you have the time to help me. So I recently discovered this: public static java.lang.String ask(java.lang.String prompt) Now, if I did something like:
1
Greenfoot.ask("Input a number. The code cracker will crack it.");
How can I make a variable (int code), become what the user has inputted in the ask string? I honestly have no idea how to go about this. I've tried using
1
return;
but I don't know how to use that. Help would me much appreciated. Try to use easy words and not get to complicated. Thanks!
danpost danpost

2015/9/27

#
The 'return' statement is used to cause the execution of a method to instantly terminate and "return" back to the line of code that called the method. Sometimes a value is returned back to the calling method as well, but the method return type and the return statement must both be in agreement with each other as far as what is returned. The 'return' statement, however, is not what you are in need of. What you do need is to declare a variable for what value the 'Greenfoot.ask' method returns. Since it returns a String value, best, to begin with, is to save the input in a String variable:
1
String input = Greenfoot.ask("Input a number. The code cracker will crack it.");
From there, you need to convert the value within the String (the 'ask' method does nothing to ensure that the input is a valid numeric value) to your 'int code'. The Integer.parseInt(String) method might help in getting a valid value from the string.
Stalfoes Stalfoes

2015/9/27

#
Umm, your code you gave me works. But I am not sure how to use the Integer.parseInt(String) method. Could you send me code, that would ask "Input a number", then convert that string into the int variable: NumCode? I've tried numerous things to use the website you sent me. Nothing works
danpost danpost

2015/9/27

#
Stalfoes wrote...
Umm, your code you gave me works. But I am not sure how to use the Integer.parseInt(String) method. ... I've tried numerous things to use the website you sent me. Nothing works
Provided that the input was a valid numeric string:
1
int code = Integer.parseInt(input);
Stalfoes Stalfoes

2015/9/27

#
Thank you so much for your help (and patience)!
You need to login to post a reply.