Beginner Java enthusiast here.
I wanted to take a break from structured practice stuff and start with a blank page, and no help to write something of my own to test myself.
I had to learn about console().readLine() as I had not learned how to receive user input from the console. This lead me to parsing integers etc. I was able to build, and compile a program that did what I had envisioned, and did so perfectly! (if not a little clumsily...) However, I wanted to think outside the box, and see how I could use it in ways NOT intended and break it. Inputting anything but a number at the console (for instance typing P instead of 6) it throws an error because I only told it how to handle a number.
Long story short, I stretched past my knowledge and taught myself a lot, but could not find the answer I was looking for due to my lack of knowledge. If someone can even just tell me what to read up on, I am more than happy to do the learning myself, just need a nudge in the right direction.
Here is my program:
public class mysteryDoors{
public static void main(String[] args){
int doorOne = 1;
int doorTwo = 2;
int doorThree = 3;
System.out.println("Welcome contestant, to the Mystery Doors Game!");
System.out.println("Would you like to find out what is behind door number 1?");
System.out.println("Maybe door number 2?");
System.out.println("Or perhaps, door number 3?!");
int choice = Integer.parseInt(System.console().readLine("Please Choose a door..." ));
while (choice > 3){
System.out.println("I am sorry, please choose one of the available doors.");
int guess = Integer.parseInt(System.console().readLine("Please try again..." ));
choice = guess;
}
if (choice == 1){
System.out.println("Behind door number 1 is a wonderful sofa set!");
}
else if (choice == 2){
System.out.println("Behind door number 2 is a nice shiny silverware set!");
}
else if (choice == 3){
System.out.println("Behind door number 3 is a NEW CAR!");
}
}
}
Why not use Scanner? Refer to: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Scanner scanner = new Scanner(System.in);
int choice = in.nextInt();
AFAIK System.console() doesn't work in IDEs.
Use a try/catch block to handle exceptions, like so:
try
{
int guess = Integer.parseInt(System.console().readLine("Please try again..." ));
choice = guess;
}
catch(NumberFormatException e)
{
System.out.println("Sorry, your input should be an integer. Try again.");
e.printStackTrace();
}
Related
I have a problem with my program is not with the code is how I am going to do it that's the confusing part that I am stuck with. just to let you know I am a basic java coder I do not understand complicated stuff so bear in mind that my code isn't the best.
----------------------------------------------------------- program explaintion-----------------------------------------------------------------
let's get into the point of explaining how it works before I show you my problem, ok when you execute the program it prompts you a sort of like a menu in a video game but it's a text-based, it shows you different options like enter player details, play the math game show score and then quit. enter player details it tells player 1 to enter he/she name and then tells another one to input he/she player name then prompts you back to the menu. play the math game is where a player 1 is asked to input he/she math equation after that player 2 has to solve it if he gets it right he gets 10 points if no the player gets no points at all. then repeats for another player to input he/she math equation then prompts you back to the menu. show scores it shows who got the most scores in the math game it calculates who's got the most if both of them got the same score then means a tie then prompts you back to the menu. and the last thing the quit option when you choose that option it stops the program. if the player chooses a wrong choice he gets an error message and puts you back to the menu
ok here is the first class called menu and other class which is connected with menu called game factions
menu:https://gist.github.com/LOLMEHA/86ff28b038d85030e346785e953644e0
gamefactions:https://gist.github.com/LOLMEHA/f05a51e07c8823a0e65cebbf81cc52ef
so this section of code that I have trouble fingering it out myself
import java.util.*;
public class Gamefunctions // this is a core when player choosess one of these options from the menu
{
String[] player =new String[2];
double scorea = 0; // verribles of all the objects
double scoreb = 0;
int i;
Scanner input = new Scanner(System.in);
double answer = 0;
double numA, numB;
char operator;
char operator2;
boolean quit = false;
double sum1;
double sum2;
public void enterDetails(){ // if player select enter details
for ( i=0;i<2;i++) {// tell's player to input he/she's name and stores them
int c=i;
System.out.println("Welcome to the maths quiz game please input player name "+c++);
player[i] = input.next();
}
}
public void mathGame(){ // if player select enter details
System.out.println("Please enter your equation please "+player[0]+" press enter for each number and mathematical symbol"); // tells the player 1 to input
System.out.println("");
System.out.println("such as for ex input a number or how many you like, then hit enter and input such as /*-+^ hit enter, then input any number one or how many you like ");
String s=input.next();
numA = Double.parseDouble(s); // numa and numb and operator is the aera of player to input he/she equation
operator = input.next().charAt(0);
numB = input.nextDouble();
if () {
if (operator == '+') {// this is if operator is one of these like +-*/^ and then it works out the sum
answer = numA + numB;
}
if (operator == '-') {
answer = numA - numB;
}
if (operator == '*') {
answer = numA * numB;
}
if (operator == '/') {
answer = numA / numB;
}
if (operator == '^') {
answer = Math.pow(numA, numB);
}
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
System.out.println("");
System.out.println(player[1]+"\t solve the equation"); // tells other player to slove the equation
sum2 = input.nextDouble();
if (sum2 == answer){// checks if the answer from the player is good or not if its good he/she gets 10 points if he/she gets it wrong gets no points and shows the right answer so the player learns from his/she mistakes
scoreb = scoreb + 10.00;
System.out.println("correct you got 10 points to your score");
System.out.println("");
} else{
System.out.println("incorrect you got no points the correct answer was:"+"" + answer);
}
you know when the program ask to player to input his math eqtion and outputs this and continues with the program and waiting for the user to input
public void mathGame(){ // if player select enter details
System.out.println("Please enter your equation please "+player[0]+" press enter for each number and mathematical symbol"); // tells the player 1 to input
System.out.println("");
System.out.println("such as for ex input a number or how many you like, then hit enter and input such as /*-+^ hit enter, then input any number one or how many you like ");
String s=input.next();
numA = Double.parseDouble(s); // numa and numb and operator is the aera of player to input he/she equation
operator = input.next().charAt(0);
numB = input.nextDouble();
let's say that the player inputs like this 10+10 enter but it will not work since they are stored in numA which is an int, I want to make a error message saying that you can not input like this 10+10 you have to input like this 10 enter + enter 10 enter so it will be able to work
if the player inputs it correctly it will continue the program
so if you have any problems with my explaintion of my plroblem pls ask so I can edit it thank you for time :)
Here’s the bit of your code I’m going to be looking at:
String s = input.next();
numA = Double.parseDouble(s);
operator = input.next().charAt(0);
numB = input.nextDouble();
if (/* Some condition */) {
// Calculate answer
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
First up, a couple nitpicks: Java is not C. You don’t need to declare all your variables at the beginning of your code blocks. numA, numB and operator are never used outside this bit of code, so it makes sense to declare them in here as well.
You’re also using input.next() with Double.parseDouble() once, then input.nextDouble() the next time. Stick to one or the other, it’ll make debugging easier if something doesn’t work properly.
And finally, what happens if someone enters 10 +1 0? The error is silently ignored because the 1 gets picked up as part of the operator string then discarded by charAt(0). A more resilient parsing method here would be to fetch the entire String first, then check for length == 1 before calling charAt(0).
double numA = input.nextDouble();
String operatorString = input.next();
char operator;
if (operatorString.length() == 1) {
operator = operatorString.charAt(0);
} else {
// Handle error
}
double numB = input.nextDouble();
if (/* Some condition */) {
// Calculate answer
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
Onto your question then: how do we detect an invalid input? Take a look at the documentation for Scanner#nextDouble() (emphasis mine):
public double nextDouble()
Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.
So we know nextDouble() can detect the invalid input for us. It does this in the form of an exception, which we can listen for (or catch) using a try ... catch statement:
try {
double numA = input.nextDouble();
} catch (InputMismatchException e) {
System.err.printf("Invalid input! Expected number, found '%s'.\n", input.next());
}
We could extend this and wrap the entire section of code in a single try ... catch, but then the user would have to start again if they make one mistake. A more user-friendly solution would be this:
double numA;
while (1) {
try {
numA = input.nextDouble();
break;
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected number, found '%s'.\n", input.next());
}
}
Note the even if you don’t print it, the call to input.next() is necessary to prevent an infinite loop.
Now we just need to do something similar for operator:
char operator;
while (1) {
String operatorString;
try {
operatorString = input.next();
if (operatorString.length() != 1) {
throw new InputMismatchException();
}
operator = operatorString.charAt(0);
break;
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected character, found '%s'.\n", operatorString);
}
}
This seems very similar to the previous snippet for a number - let’s try to refactor some of the common code here into a method:
#FunctionalInterface
public interface ScannerGetter<T> {
T apply() throws InputMismatchException;
}
public <T> T getValueFromScanner(ScannerGetter<T> getter, String type) {
while(1) {
try {
return getter.apply();
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected %s.");
}
}
}
There’s a lot going on in these few lines. The first part declares a functional interface - this is a basically a custom type of lambda function. We’ll come back to that in a moment.
The method itself (getValueFromScanner()) is a generic method. It allows us to use the same method with different types in place of the generic parameter (T) without duplicating it.
This is how you’d use the above method to retrieve your three inputs:
double numA = this.<Double>getValueFromScanner(() -> input.nextDouble(), "number");
char operator = this.<Char>getValueFromScanner(() -> {
operatorString = input.next();
if (operatorString.length() != 1) {
throw new InputMismatchException();
}
return operatorString.charAt(0);
}, "operator");
double numB = this.<Double>getValueFromScanner(() -> input.nextDouble(), "number");
// Once your code gets here, all three variables will have valid values.
Here is link to the problem I am working on: http://programmingbydoing.com/a/adventure2.html
I cannot seem to get it to the downstairs area. We are supposed to use mainly while and if loops, so if there is a possibility to from one area of the loop to the other, that would be great to hear input!
public class Adventure2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int nextroom = 1;
String choice = "";
System.out.println("MITCHELL'S TINY ADVENTURE 2!");
System.out.println("")
while (nextroom != 0) {
if (nextroom == 1) {
System.out.println("You are in a creepy house! Would you like to go to the \"kitchen\" or \"upstairs\"?");
System.out.print("> ");
choice = keyboard.next();
if (nextroom == 1) {
System.out.println("There is a long countertop with dirty dishes everywhere. Off to one side there is, as you'd expect, a refrigerator. You may open the \"refrigerator\" or go \"back\".");
choice = keyboard.next();
if (choice.equals("back")) {
System.out.println("You are in a creepy house! Would you like to go to the \"kitchen\" or \"upstairs\"?");
System.out.println("> ");
choice = keyboard.next();
} else {
System.out.println("The refrigerator falls on you.");
if (nextroom == 2) {
System.out.println("You are in a creepy house! Would you like to go to the \"kitchen\" or \"upstairs\"?");
System.out.println("> ");
choice = keyboard.next();
if (choice.equals("upstairs")) {
System.out.println("Upstairs you see a hallway. At the end of the hallway is the master \"bedroom\". There is also a \"bathroom\" off the hallway. Or you can go back \"downstairs\". Where would you like to go?");
System.out.println("> ");
choice = keyboard.next();
if (choice.equals("downstairs")) {
System.out.println("You are in a creepy house! Would you like to go to the \"kitchen\" or \"upstairs\"?");
}
}
}
}
}
}
}
}
}
Frankly your code is a bit of a mess, but that's not unusual for a beginner.
The trick is to carefully read the code that you have written, and to "run it in your head". In your example, you will come to this point:
System.out.println("You are in a creepy house!...");
System.out.print("> ");
choice = keyboard.next();
You read a choice. But what happens next? What do you do with that choice? Answer .... nothing! Here's what you do next.
if (nextroom == 1) {
System.out.println("There is a long countertop ...;
choice = keyboard.next();
You have ignored the first choice you read, you test nextroom again (which won't have changed because you didn't assign anything new to it.
If you read your code carefully and try to run it in your head (like a computer does), then these problems should leap out at you. If that's too hard, then using a debugger will help.
That brings us back to my original comment. When you start getting your head around what should be happening, you should realise that there general pattern that your program should follow. Something like this
while (not finished):
print description of where I am
print choices of where to go next next
get choice
if choice is valid:
change location
else:
print error message
If you do it right, you should not need to copy-and-paste the pattern in the loop body multiple times.
Hint: think about using array and array indexing.
Hint 2: nextroom could be used as an array index.
This is my first post here, so I decided to browse around various posts here in order to try and get a feel for how questions should be posted.
Hence, if I mess up please let me know so I can fix my post accordingly ASAP.
So here is my problem:
I started learning Java today and I'm working on just getting a feel for how everything works. I have the code below set to tell if kids are good or bad and display corresponding replays.
Good kids get candy, bad kids get none. I want to be able to limit the users choices to good or bad and have their answer change the Boolean to true or false to run the right if statement.
I saw a Math.random way of doing it but when I tried it I got more problems.
Thank you for your time.
The following is my code:
import java.util.Scanner;
public class Main {
public static void main (String args[]) {
//take user info
Scanner sc = new Scanner(System.in);
int candy = 12;
int kids = 4;
int bad = 1;
String a = sc.nextLine();
int answer = candy / kids;
String answer2 = "No Candy";
boolean good = false;
System.out.println(a);
//closeing the scanner
sc.close();
if(bad == 1) {
System.out.println(answer2);
} else {
if(bad == 2)
good = true;
System.out.println(answer);
}
if(good == true) {
System.out.println("Good Job");
} else {
System.out.println("Try again tomorrow!");
}
}
}
For one, it is not necessary to end the scanner before your code ends. You can leave it around, closing it is not necessary. (Unless your IDE forces you to , then yes, you should, but close it at the end just in case. I have Eclipse, so my code still runs without a glitch.)
Another comment is, just for the sake of aesthetics you should concatenate some kind of string on to the end of answer, so the reader understands what the variable means.
One more thing. I often find it helpful to name my scanner something a little more intuitive, such as input. Because after all, that's what it is. (I'm only commenting a lot about your code because you are just beginning to learn things, so you should get into good habits early.)
What you can do in this situation is convert your string inputs to booleans, by using boolean userInput = Boolean.parseBoolean(answer). Then, depending on the input the user gives by using an if statement, they can control the flow of the code.
I cleaned up your code a little bit, if you don't mind.
import java.util.Scanner;
public class lol {
public static void main (String args[]){
//take user info
Scanner sc = new Scanner(System.in);
int candy = 12;
int kids = 4;
int answer = candy / kids;
String answer2 = "No Candy";
System.out.println("Are youkids good or bad?");
System.out.println("[1] Good = true");
System.out.println("[2] Bad = false");
String a = sc.nextLine();
boolean userInput = Boolean.parseBoolean(a);
if(userInput== false){
System.out.println(answer2);
System.out.println("Try again tomorrow!");
}
else{
System.out.println("Good Job");
System.out.println("You get" +answer+"pieces.");
}
}
}
Seeing as you're just starting out, I'll try and keep it simple. There are plenty of ways to force your reader to say either "good" or "bad" that are better than below, but they require loops (which I assume you haven't touched yet).
Consider the following:
boolean good = false;
if (a.equals("good")) { // they said good
good = true;
} else if (a.equals("bad")) { // they said bad
good = false;
} else { // they said neither
System.out.println("You didn't say a correct word!");
}
You first specify that you have a boolean good (which you can either give a default value as above, or nothing). Then, depending on the user's input, you can set the boolean to be whatever is appropriate.
The reasoning behind having to declare the boolean good above the if statements has to do with the scope of a variable. If your book/teacher hasn't explained what that is, you should look it up now. The TL;DR is that if you only first declare your variable inside the if statements, then it will disappear as soon as you leave the if statements. You can see how in this case that would basically defeat the purpose of the if statements entirely.
You can limit the input by enclosing it in a loop.
List<String> accepted = new ArrayList<String>();
accepted.add("good");
accepted.add("bad");
System.out.println("Good or bad?");
String input = sc.nextLine();
while(!accepted.contains(input)) {
System.out.println("Invalid query '" + input + "'. Try again.");
input = sc.nextLine();
}
The code you have, well I don't know exactly what it's trying to do. It doesn't look functional at all. So where this fits in I'm not 100% sure.
package test;
import java.util.Scanner;
public class app {
public static void main (String args[]){
//take user info
Scanner sc = new Scanner(System.in);
String a="?";
while(!a.equals("good") && !a.equals("bad")){
System.out.println("Was the kid good or bad ?");
a = sc.nextLine();
}
boolean wasKidGood = a.equals("good");
String result = (wasKidGood ? "Good kid gets candy" : "No candy for bad kid");
System.out.println(result);
sc.close();
}
}
Hello, I wrote something, that will help you grasp a while loop and a ternary operator (alternative version of if loop). You also need to pay attention as to where you are allowed to use == and where you should use the equals() method. Regards
I am trying to check if a user entered a number and if not, then it uses a default number like 10. How do i check if the user just presses enter and doesn't enter anything in Java
input = scanner.nextInt();
pseudo code:
if(input == user just presses enter without entering anything){
input = 10;
}
else just proceed with input = what user entered
//scanner is a Scanner
int i; // declare it before the block
try {
i = scanner.nextInt();
}
catch (InputMismatchException ime) {
i = 10;
}
// i is some integer from the user, or 10
First things first, geeeeeez guys, when the OP says something like
"I don't want an exception, i want i = 10 if nothing is entered, so what do i do"
That should clue you in that he probably doesn't know too much about exceptions (maybe even java) and might need a simple answer. And if that's not possible, explain to him the difficult ones.
Alright, here's the plain and simple way to do it
String check;
int input = 10;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
else
{
input = Integer.parseInt(check);
}
Let me explain what this code is doing. You were originally using nextInt() to get your number for input, correct? The problem is, nextInt() only responds if the user actually inputs something, not if they press enter. In order to check for enter, we used a method that actually responds when the user presses enter and used that to ensure that our code does what we wanted to. One thing I recommend using is an API, Java has one.
Here's the link for the API HERE
And here's the link for the actual method I used HERE. You can find descriptions and instructions on many methods you'll run into on this API.
Now, back to my answer, that's the easy way to do it. Problem is, this code isn't necessarily safe. It'll throw exceptions if something goes wrong, or if someone is trying to hack into your system. For example, if you were to enter a letter instead of pressing enter or entering a number, it would throw an exception. What you've been seeing in the other answers is what we call exception handling, that's how we make sure exceptions don't happen. If you want an answer that'll catch most of these exceptions, you need to make sure your code catches them, or avoids them all together (I'm simplifying things immensely). The above answer is working code, but isn't safe code, you wouldn't ever use something like this all by itself in real life.
Here is something that might be considered safe code. And no exceptions to keep it simple! ;)
import java.util.Scanner;
public class SOQ15
{
public Scanner scanner;
public SOQ15()
{
scanner = new Scanner(System.in);
int input = 10;
boolean isAnInt = true;
String check;
check = scanner.nextLine/*Int*/();
if(check.equals(""))
{
//do nothing since input already equals 10
}
for(int i = 0; i < check.length(); i++)
{
if(check.charAt(i) >= '0' && check.charAt(i) <= '9' && check.length() < 9)
{
//This is if a number was entered and the user didn't just press enter
}
else
{
isAnInt = false;
}
}
if(isAnInt)
{
input = Integer.parseInt(check);
System.out.println("Here's the number - " + input);
}
}
public static void main(String[] args)
{
SOQ15 soq = new SOQ15();
}
}
I don't have time to go into all the details right now, but ask and I'll gladly respond when I get the time! :)
Well if you are using scanner, given the details provided, you can try:
Scanner in = new Scanner(System.in);
if in.hasNextInt(){ //Without this, the next line would throw an input mismatch exception if given a non-integer
int i = in.nextInt(); //Takes in the next integer
}
You said you wanted a default of 10 otherwise so:
else {
int i = 10;
}
This is my first time on this site. I am taking a course in Java right now and I am having some trouble with this code/program that I am supposed to make that allows the user to select whether they want to see "good monkeys", "bad monkeys" or "show monkeys". It is nowhere near done but I am having trouble returning to the command screen/area after a command is completed. I would like the commands to be used as many times as possible. Secondly, my program treats every input if someone put in "Good Monkey". So if you put in a word like "pineapple", it will still greet you with the output designated for the "Good Monkeys" input.
I've looked online and seen that maybe I should use a "do-while" loop and use "switch". Any input/ help would be greatly appreciated. Thank you so much!
Here is my code: public class and public static and Scanner import are in this code, but for some reason I cannot add them into this post without messing up the formatting of the code.
Scanner jScanner = new Scanner(System.in);
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
String userChoice = jScanner.nextLine();
for (int b= 1; b < 11000; b++)
{
if (userChoice.equalsIgnoreCase("Good Monkeys"));
{
System.out.println("You have selected Good Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner goodMonkeyScanner = new Scanner (System.in);
int userChoiceGood = goodMonkeyScanner.nextInt();
if (userChoiceGood >= 3 && userChoiceGood <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else if (userChoice.equalsIgnoreCase("Bad Monkeys"))
{
System.out.println("You have selected Bad Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner badMonkeyScanner = new Scanner (System.in);
int userChoiceBad = badMonkeyScanner.nextInt();
if (userChoiceBad >= 3 && userChoiceBad <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else
System.out.println("Sorry this doesn't work");
}
else if ((userChoice.equalsIgnoreCase("Show Monkeys")))
{
System.out.println("Monkeys");
System.out.println("0");
System.out.println("\\/");
System.out.println(" |");
System.out.println("/\\");
break;
}
else
{
System.out.println(" Wrong Answer. Try again");
}
break;
}
}
}
}
First, you need to define the loop. Second, you need to put the input instruction inside the loop.
I'll include a done variable to detect when the user wants to escape
So, let's code:
Scanner jScanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
System.out.println("(or enter 'done' to exit");
String userChoice = jScanner.nextLine();
swithc(userChoice.toLowerCase()) {
case "good monkeys":
/*
* The code for this option
*/
break;
case "bad monkeys":
/*
* The code for this option
*/
break;
case "show monkeys":
/*
* The code for this option
*/
break;
case "done":
done = true;
break;
default:
System.out.println("Your input isn't what I expected!\nTry again!");
break;
}
}
The code, explained:
That while(!done) stuff can be read as "while 'not done' do what follows"
userChoice.toLowerCase(): I convert the userChoice to lower-case, to simplify comparissons. That way, I only need to compare the string with other lower-case strings
switch(userChoice.toLowerCase()): ... hmmm... I think you can figure it out yourself ;)
That default block is what happens if no other case is valid
The "done" block will set the done variable to true, and thus it will terminate the loop
Important: ALWAYS end the case blocks with break
Further reading:
The Java Tutorials: Language basics
The while and do-while statements
The switch statement
Also, I recommend you study Flowcharts and, before start coding, try to draw in paper a flowchart of your program. That way, you will have a clear image of your program before you start writing the very first line of code.