Get some pointers/suggestions on first basic java program? - java

When I run the program and the user input field comes up, when I just hit enter without entering anything in the blank space another input field comes up. This happens over and over if I keep hitting enter. If there is a way to solve this please let me know. I couldn't find anything to fix it in the documentation.
import java.util.Scanner;
import java.util.Random;
class Game {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//generate a random number
//take user input
//check the input act appropriately
boolean running = true;
boolean guessed = true;
boolean realInt = true;
int number = 0;
int input = 0;
String firstName=" ";
System.out.print("want to play the game? Yes/No: ");
firstName = sc.next();
while (running) {
if (guessed && (("yes".equals(firstName)) | ("cheater".equals(firstName)))){
System.out.println("I have chosen a random value");
System.out.println("Have a go at guessing it");
Random rand = new Random();
number = rand.nextInt(10) + 1;
guessed = false;
}
if(("yes".equals(firstName)) | ("cheater".equals(firstName)))
{
if(sc.hasNextInt()) {
realInt=true;
input = sc.nextInt();
}
else{
System.out.println("That is not an integer.");
running = false;
}
}
else
running = false;
if((((input != number) && realInt)&&(input != -1))){
System.out.println("Plsease try again");
}
//below line sets up when to stop the program, when -1 is entered
if (input == -1){
running = false;
}
else{
guessed = input == number;
}
//below lines are cheat codes
if (input == -5){
System.out.println("Answer: " + number);
}
if ("cheater".equals(firstName) && (input != number)){
System.out.println("Answer: " + number);
}
}
}
}

This is due to the way how Scanner's next() method reads input.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
So even if you hit number of enters, there will not be any token and hence Scanner is just waiting from user to have one valid token so that in can read and continue reading the next token.
public String next()
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
Solution:
Use Scanner's hasNextLine() and nextLine() methods.It will allow you to capture empty or white-space lines. Refer to the API on java site for other methods.

Related

JAVA Do/while loop not returning the value

I'm new at stackoverflow and coding.
I'm trying to make a method for validating the user input. The user is only allowed to answer, add, show or exit. But I keep getting stuck in the first while loop.
I tried to change it to !userChoice.equals.. but it is not working.
What am I doing wrong.
public static String userFunction() {
Scanner sc = new Scanner(System.in);
String userChoice = "test";
do {
userChoice = sc.next().toLowerCase();
while (userChoice.equals("add") || userChoice.equals("exit") || userChoice.equals("show")) {
System.out.println("Please fill in add, show or exit");
userChoice = sc.next().toLowerCase();
}
while (!userChoice.equals("add") || !userChoice.equals("show") || !userChoice.equals("exit")) ;
return userChoice;
} while (userChoice == "test");
}
Your posted code has three loops – two "while" loops, and an outer "do" loop. It isn't necessary to use more than one loop.
Taking a step back, you are describing a method that should:
accept user input
check if the input is "allowed" or not – must be one of "add", "show", or "exit"
if input is one of those three, return it to the caller
if input is not one of those three, show a message to the user and prompt again
do this forever until the user enters valid input
Here's a method which does those things:
public static String getInput() {
Scanner scanner = new Scanner(System.in);
String input;
while (true) {
input = scanner.next().toLowerCase();
if (input.equals("add") || input.equals("show") || input.equals("exit")) {
return input;
} else {
System.out.println("Unsupported input: [" + input + "], enter: add, show, or exit");
}
}
}
And here's a sample run + output:
String input = getInput();
System.out.println("from getInput(): " + input);
adf
Unsupported input: [adf], enter: add, show, or exit
show
from getInput(): show

What is wrong with this java while loop?

New to Java and learning how to use While loops and random generator. This prints a multiplication question. Every time the user answers a question wrong, it should print the same question. Instead, it exits the program. What should I do?
while (true) {
Random multiply = new Random();
int num1 = multiply.nextInt(15);
int num2 = multiply.nextInt(15);
int output = num1 * num2;
System.out.println("What is the answer to " + num1 + " * " + num2);
Scanner input = new Scanner(System.in);
int answer = input.nextInt();
if (answer == output) {
if (answer != -1)
System.out.println("Very good!");
} else {
System.out.println("That is incorrect, please try again.");
}
}
If you want to repeat the same question when the user gets the answer wrong, you should use another while inside your main loop.
This inner loop continues to ask as long as you give a wrong answer.
I also replaced nextInt with nextLine, which reads in a whole line of text. This consumes the "Enter" key and is a safer approach at reading from the console. Since the result is now a String you need to use Integer.parseInt to convert it to an int. This throws an exception if you enter anything but a whole number so I wrapped it into a try-catch block.
If you want, you can add an additional check for validating user input. So in case the user wants to stop playing they only need to input "exit" and the whole outer loop will exit.
boolean running = true; // This flag tracks if the program should be running.
while (running) {
Random multiply = new Random();
int num1 = multiply.nextInt(15);
int num2 = multiply.nextInt(15);
int output = num1 * num2;
boolean isCorrect = false; // This flag tracks, if the answer is correct
while (!isCorrect) {
System.out.println("What is the answer to " + num1 + " * " + num2);
Scanner input = new Scanner(System.in);
try {
String userInput = input.nextLine(); // Better use nextLine to consume the "Enter" key.
// If the user wants to stop
if (userInput.equals("exit")) {
running = false; // Don't run program any more
break;
}
int answer = Integer.parseInt(userInput);
if (answer == output) {
if (answer != -1) {
System.out.println("Very good!");
isCorrect = true; // Set the flag to true, to break out of the inner loop
}
} else {
System.out.println("That is incorrect, please try again.");
}
}
catch(NumberFormatException e) {
System.out.println("Please enter only whole numbers");
}
}
}
Avoid while true. Declare a variable to true, pass the variable to the condición loop and set it to false when the answer is incorrect. You can use break too, but is easier to read the code when you use a exit condition in the while. Also read more about loops https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

How would i do input validation?

Tells the user if the number entered is even or even. I need help with the input validation. The validation i need do is that the user cannot entered anything but a number. Trying to do the validation without the try and catch method.
import java.util.Scanner;
public class oddoreven {
public static void main (String [] args) {
Scanner input = new Scanner (System.in);
//declaractions
int num;
//while loop
do{
System.out.println("PLease enter a number to see whether it is even or odd. To end tyype in -99.");
num = input.nextInt();
// input valid
}while(num != -99); // loop ends
// begins the method
public static void is_odd_or_even_number(int number){
int rem = number%2;
\
You can call Scanner.hasNextInt() to determine if the next input is an int (and consume anything else). Also, you might make an infinite loop and break when the input is -99 (or 99, your code tests for 99 but your prompt says -99). Finally, you should call your method. Something like,
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
do {
System.out.println("Please enter a number to see whether it is "
+ "even or odd. To end type in -99.");
if (input.hasNextInt()) {
num = input.nextInt();
if (num != -99) { // <-- directions say -99.
is_odd_or_even_number(num);
} else {
break;
}
} else {
System.out.printf("%s is not a valid int.%n", input.nextLine());
}
} while (true);
}
You can use Scanner.nextLine() to get a string input. Then loop through the characters to make sure they are all digits. (assuming non-negative integers only)
string rawInput = input.nextLine();
boolean validInput = true;
for (char c : rawInput) {
if (!Character.isDigit(c)) {
validInput = false;
break;
}
}
if (validInput) {
int num == Integer.parseInt(rawInput);
// proceed as normal
}
else {
// invalid input, print out error message
}
You can use regex to check whether all the characters of string entered by user are digits or not,
num.matches("[0-9]+") // return true if all characters are digits
or
num.matches("^[0-9]*$") // return true if all characters are digits
but before that change your num = input.nextint() to num = nextLine() and make num as String. if you dont do this there is no need of validating user input as you are requiring.

Java input keeps being empty?

This is a simple question selection, and then answer program:
import java.util.Scanner;
public class Mains {
static Scanner console = new Scanner(System.in);
static Tof tof = new Tof();
static int Ievel = 0;
static int Input = 0;
static boolean GAME = true;
static boolean AT_START = true;
static boolean IN_QUESTION = false;
public static void main (String[] args) {
while (GAME) {
String InputS = "";
if (AT_START) {
System.out.println("Welcome to the game! Please select a number from 1 to 10.");
AT_START = false;
}
if (!IN_QUESTION)
Input = console.nextInt();
if (Input == -1) {
GAME = false;
console.close();
} else {
String question = tof.getQuestion(Input);
String answer = tof.getAnswer(Input);
System.out.println(question);
IN_QUESTION = true;
while (IN_QUESTION) {
InputS = console.nextLine();
if (InputS != console.nextLine()) {
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
}
}
}
}
}
Problem:
When entering the IN_QUESTION loop, and writing a answer, it will always be incorrect.
That's because the InputS variable is ALWAYS empty, no matter what, while it has console.nextLine() set on it.
Why is it empty? How do I fix this?
In-case you need the other class Tof: http://pastebin.com/Fn5HEpL2
nextInt doesn't get the line terminator after the integer and you're reading from the console twice (the second time being in the if-statement).
So if you enter:
123
apple
The following happens:
Input gets assigned a value of 123
InputS gets assigned an empty string
InputS gets compared against apple and it is not equal (from InputS != console.nextLine() - I'm not sure why it's there)
You can fix it by:
Putting a console.nextLine(); after console.nextInt();
OR
Use Input = Integer.parseInt(console.nextLine()) instead of nextInt
Removing this - if (InputS != console.nextLine())
You're reading from the console twice. This should work:
while (IN_QUESTION) {
InputS = console.nextLine();
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
The problem is that the new line character was not read by the nextInt() method so it remain in the scanner buffer and when the next time you called nextLine() that character was printed first.
This is how to fix the issue:
//empty the newline character from the scanner
console.nextLine();
while (IN_QUESTION) {
InputS= console.nextLine();
if (InputS.equals(answer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect. " + InputS + " " + answer);
}
}
You call console.nextLine twice. This means that you read a line that you'll check, and another you won't. This is probably not what you are after. Also note that your initial call of nextInt will not consume the newline you pressed after entering the number. You need a nextLine right after that, but before the main loop.
Some general remarks:
uppercase names are only for constants, so your variables should be lowercase;
you should really be using local variables instead of static ones. Right now this isn't hurting you, but it soon could.

Splitting a String and Parsing it into an Integer

I have some logic (java.lang.ArrayIndexOutOfBoundsException) error in this part of my code for some reason. I want the user to input anything and have it be split and parsed into an integer. If the user fails to do so ask them again. And if they enter something like "g5 3 76h 23" have the program accept it as 5 3. Or if i can have the program deny this until the user only enters two numbers between 0 and 9 separated by a space, that would be fine aswell. The user also has the option of enetering a "q" to quit.
However, everytime i run it, it appears as if nothing was split into a new array. and I get the error.
/**
* Prompts the user for input
*/
public void promptUser() {
// a Scanner object that uses System.in for input.
Scanner scan = new Scanner(System.in);
// a prompt for the user, asking them for input.
System.out.print("Pick a coordinate [row col] or press [q] to quit: ");
// Get input from the user, checking for errors. If the input is
// correct (e.g., two numbers that in bounds and have not
// already been clicked), then call the click method for desired
// coordinates. If the user wants to quit the game then make sure
// to update the boolean state variable and print out a message.
String input = scan.next();
String del = "[\\s,;\\n\\t]+"; // these are my delimiters
String[] token = input.split(del); // here i will save tokens
int val0 = 11, val1 = 11;
boolean tf = true;
while(tf)
{
if(token[0] == "q")
{
isRunning = false;
System.out.println("Thank you for playing");
}
else
{
try
{
val0 = Integer.parseInt(token[0], 10);
}
catch (NumberFormatException nfe)
{
// invalid data - set to impossible
val0 = 11;
}
try
{
val1 = Integer.parseInt(token[1], 10);
}
catch (NumberFormatException nfe)
{
// invalid data - set to impossible
val1 = 11;
}
}
if( !(((val0 >= 0) && (val0 < rows)) && ((val1 >= 0) && (val1 < cols))) )
{
System.out.println("Input Invalid, pick a coordinate [row col] or press [q] to quit: ");
input = scan.next();
for(int i=0;i<2;i++)
{
token = input.split(del);
}
}
else if(false) //atm
{
}
else
{
tf = false;
}
click(val0, val1);
} //while loop
} // promptUser
You need to validate the length of your returned token[] array, as it is possible that no "tokens" are returned. I.E., you shouldn't try to access token[0] and token[1] without first ensuring that they exist.
An example check:
if(token.length > 1)
From the Scanner documentation:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You could change it to:
scan.useDelimiter(del); // If you want to split on more than just whitespace
while(scan.hasNext()) {
String input = scan.next();
if("q".equals(input)) {
System.out.println("Thank you for playing");
return;
}
// etc. Put in a list or array for use later.
}
Remember that Strings are objects so == only returns true if both strings are the same object, not if they have the same value. Use .equals for value comparison.

Categories

Resources