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.
Related
I need to validate that user inputs two integers and as such, I need to continue asking him for input until he provides both inputs that are integers. Not sure how to implement it, but I came up with something like that but now struggling to implement the part that checks if coord1 and coord2 get correct types. If not, it of course gives me the NumberFormatException:
while (true) {
System.out.print("Enter the coordinates: ");
int coord1 = Integer.parseInt(scanner.next());
int coord2 = Integer.parseInt(scanner.next());
if (coord1 < 1 || coord1 > 3 || coord2 < 1 || coord2 > 3) {
System.out.println("Coordinates should be from 1 to 3!");
continue;
} else if (cellOccupied(field, coord1, coord2)) {
System.out.println("This cell is occupied! Choose another one!");
continue;
}
break;
}
Can I solve it without using try / catch, since I haven't learned that yet, or is this the only way?
Thank you in advance and sorry, since I'm still learning Java syntax and ways of validation.
Instead of manually checking if the input is the right type, you could rely on the Scanner's methods hasNextInt() and nextInt().
The first one will check whether your input is an actual int and then you can proceed reading it with nextInt(). For further details about placing a nextLine() after reading a numeric type read the following question asked here on stack overflow.
Here I've also included your code in a sample main. I know yours was just a snippet with much more code around (I didn't have the cellOccupied method, for example) but I've just pasted it like so for a minimal testing. Besides, I've also parameterized your use case. It was a bit odd and redundant to repeat the same code for reading the user input applying the same coordinate-logic.
public class Main {
public static void main(String[] args) {
int coord1 = 0, coord2 = 0;
do {
coord1 = readCoordinate("Enter first coordinate: ");
coord2 = readCoordinate("Enter second coordinate: ");
//Showing an error message if the coords refer to an occupied cell
if (cellOccupied(field, coord1, coord2)) {
System.out.println("This cell is occupied! Choose another one!");
}
} while (cellOccupied(field, coord1, coord2));
}
private static int readCoordinate(String message) {
int coord;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print(message);
if (scanner.hasNextInt()) {
coord = scanner.nextInt();
//getting rid of the new line character after reading the int
scanner.nextLine();
//Checking coordinate value
if (coord < 1 || coord > 3) {
System.out.println("Coordinates should be from 1 to 3!");
continue;
}
} else {
//assigning an undesired value (since your coords must be between 1 and 3
coord = 0;
//getting rid of the wrong user input
scanner.nextLine();
//Showing an error message
System.out.println("Please enter an int value");
//Skipping directly to the loop's condition
continue;
}
break;
}
return coord;
}
}
On a side note, avoid declaring fields in a loop.
You can find here several suggestions. For example, you can use regular expressions. Create an isNumeric function that will tell you whether a given string is an integer:
public boolean isNumeric(String strNum) {
Pattern pattern = Pattern.compile("\\d+");
if (strNum == null) {
return false;
}
return pattern.matcher(strNum).matches();
}
And before pushing the scanner.next() to the integer parser, check it with the function.
I'm fairly new to Java. I've done some C++ so I understand a lot of the concepts. I've been working on this code that allows me to ask for input on a tip calculator. I know some of the code is inconsistent but it's because I've been trying various methods to get it to display.
I can go through the program once asking for user input. However when I loop through it again, it just displays the same input I put in prior. I'm trying to get it to show then loop through, take new input and display that. I've been teaching myself this so it's a learning experience for me, however I'm stumped and not sure where to go from here. Any help is appreciated.
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TipApp {
public static void main(String[] args) {
calculateTips();
}
public static void calculateTips () {
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
String pattern = "$##,###,###.00;"; // Pattern string for the decimal format
DecimalFormat moneyFormat = new DecimalFormat(pattern); // Decimal Money format
NumberFormat defaultFormat = NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(1);
String choice;
double theBill;
int theTip;
int thePartySize;
boolean isBillValid = true;
boolean isTipValid = true;
boolean isPartySizeValid = true;
TipCalculator tipCalculator1 = new TipCalculator();
System.out.println("*** Tip Calculator ***");
do {
System.out.print("\nEnter the bill amount: ");
while (isBillValid) {
try {
if (input.hasNextDouble()) {
theBill = input.nextDouble();
isBillValid = false;
tipCalculator1.setBillAmount(theBill);
}
} catch (InputMismatchException e) {
System.out.println(input.next() + " is not a valid number");
}
input.nextLine();
}
System.out.print("Enter your desired tip percentage (20 equals 20%): ");
while (isTipValid) {
if (input.hasNextInt()) {
theTip = input.nextInt();
isTipValid = false;
tipCalculator1.setTipPercentage(theTip);
} else {
System.out.println("Please enter a valid tip percentage.");
isTipValid = true;
}
input.nextLine();
}
System.out.print("Enter the size of your party: ");
while (isPartySizeValid) {
if (input.hasNextInt()) {
thePartySize = input.nextInt();
isPartySizeValid = false;
tipCalculator1.setPartyAmount(thePartySize);
} else {
System.out.println("Please enter a valid party size.");
isPartySizeValid = true;
}
input.nextLine();
}
System.out.println("*** Your Bill ***");
System.out.print("\nBill Amount: ");
System.out.println(moneyFormat.format(tipCalculator1.getBillAmount()));
System.out.print("Tip Percentage: ");
System.out.println(defaultFormat.format(tipCalculator1.getTipPercentage()));
System.out.print("Party Size: ");
System.out.println(tipCalculator1.getPartyAmount());
System.out.print("\nTotal Bill (with Tip): ");
System.out.print(moneyFormat.format(tipCalculator1.getTotalAmount()));
System.out.print("\nShare for Each Individual: ");
System.out.print(moneyFormat.format(tipCalculator1.getIndividualShare()));
System.out.print("\nAnother Bill? (y/n): ");
choice = scan.nextLine();
} while (choice.equalsIgnoreCase("y")) ;
System.out.println("\nGoodbye!");
}
}
public class TipCalculator {
private double billAmount;
private int tipPercentage;
private int partyAmount;
// Constructor that holds 3 arguments
public TipCalculator() {
setBillAmount(billAmount);
setTipPercentage(tipPercentage);
setPartyAmount(partyAmount);
}
public double getBillAmount() {
return billAmount;
}
public void setBillAmount(double billAmount) {
this.billAmount = billAmount;
}
public double getTipPercentage() {
return tipPercentage / 100f;
}
public void setTipPercentage(int tipPercentage) {
this.tipPercentage = tipPercentage;
}
public int getPartyAmount() {
return partyAmount;
}
public void setPartyAmount(int partyAmount) {
this.partyAmount = partyAmount;
}
public double getIndividualShare() {
return (getTotalAmount() / partyAmount);
}
public double getTotalAmount() {
return (billAmount * getTipPercentage()) + billAmount;
}
}
[1]: https://i.stack.imgur.com/5tHIs.png
First off, use only one Scanner object, you don't need more than that. Perhaps name is userInput.
The problem you are having is because you are not resetting some key variables for the next bill to be calculated, in particular those that are used in conditions for your loops.
Take the following variables:
boolean isBillValid = true;
boolean isTipValid = true;
boolean isPartySizeValid = true;
double theBill;
int theTip;
int thePartySize;
and move them to the top of your do loop (the main outer loop) and initialize the String variable choice to hold a null string (""), for example:
do {
choice = "";
boolean isBillValid = false;
boolean isTipValid = false;
boolean isPartySizeValid = false;
double theBill = 0.0d;
int theTip = 0;
int thePartySize = 0;
System.out.print("\nEnter the bill amount: ");
while (isBillValid) {
try {
//..... The rest of your code ....
This way the conditions for your loops will not already be set from the previous bill should the User enter 'y' to process another Bill.
In my opinion, every prompt which requires User input of some kind should ensure valid input and this would include the Another Bill? (y/n): prompt, for example:
while (choice.isEmpty()) {
System.out.print("\nAnother Bill? (y/n): ");
choice = userInput.nextLine();
// Is only a 'y' or a 'n' supplied (regardless of letter case)
if (!choice.matches("(?i)[yn]")) {
// No...inform User and have him her try again.
System.out.println("Invalid input - 'y' or 'n' only! Try again...");
choice = ""; // Reset the 'choice' variable to null string.
}
}
The if statement condition in the above code utilizes the String#matches() method along with a small Regular Expression (RegEx). Within the regex string, the (?i) means 'ignore letter case' and the [yn] means: matches only the 'y' or 'n' characters. So, if the supplied choice does not match either y, Y, n, or N then the condition is true.
This sort of validation should apply to all your prompts to the User so as to ensure a trouble free experience for the User, after all, typo's do happen. Take the Tip Percentage entry for example, what is to happen if the User enters -10?. This would be okay if your were applying a discount coupon or something but not so much for a tip. I think it might be best for the User to enter a value within a specific range like 0 to 100 (or whatever you like):
while (!isTipValid) {
System.out.print("Enter your desired tip percentage (0 to 100): --> ");
try {
theTip = userInput.nextInt();
// Is the tip percentage inclusively between 0 and 100?
if (theTip < 0 || theTip > 100) {
// No...
throw new java.util.InputMismatchException();
}
isTipValid = true;
tipCalculator1.setTipPercentage(theTip);
}
catch (java.util.InputMismatchException ex) {
System.out.println("Invalid tip percentage supplied (" + theTip + ")! Try again...");
}
userInput.nextLine();
}
In the above example loop code you will most likely notice a few things done differently here.
To begin with, the condition for the while loop better represents the name of the boolean variable isTipValid. The variable name is in a sense more like a question: Is the Tip Valid?. By default you have this variable initialized to true which is basically like saying "Yes, the Tip is Valid!" when in reality that hasn't been established yet. For better clarity I think this variable (and others like it) should be initialize to boolean false and then changed to boolean true only after it is definitely determined that the value supplied is indeed valid.
Another change you may have noticed is the fact that the displayed prompt string to the Console Window is placed within the while loop rather than above it. This ensures that if an invalid situation occurs and the prompt requires further input then the User will definitely know what is requested. It's a good idea that all of your prompt mechanism be contained within the while loop that pertains to it. The prompt string has also be modified to indicate to the User that a value within the range of 0 to 100 is expected.
Another change you may have noticed is the fact that the if (input.hasNextInt()) { line has been replaced with a Try/Catch mechanism. This actually provides a more definite means to ensure proper data entry since the Scanner#hasNextInt() method (and other hasNext...() methods) is better suited for tokenized input whereas a delimited series of integer numbers may be in or combined within that input. It can of course be used in this use-case but requires additional handling to accommodate all possible invalid situations.
You will also see an additional if statement that is used to check whether or not the value supplied is within the described range of 0 to 100. If it isn't then an InputMismatchException is thrown which forces the code-flow to immediately fall into the catch clause which ultimately indicates the problem to the User ans re-prompts for another value.
Doing the above similarly to your other Prompts will produce a much better outcome and you will know that the values supplied will be valid with the exception of the Bil Amount prompt:
while (!isBillValid) {
System.out.print("Enter the bill amount: --> ");
try {
theBill = userInput.nextDouble();
if (theBill < 0) {
throw new java.util.InputMismatchException();
}
isBillValid = true;
tipCalculator1.setBillAmount(theBill);
} catch (java.util.InputMismatchException e) {
System.out.println("Invalid Bill amount supplied (" + theBill + ")! Try again...");
}
userInput.nextLine();
}
This will work well for pretty much all invalid possibilities except for this simple typo: 3e4 example. This is considered a valid double value by the Scanner#nextDouble() method. The e or E within the supplied value is considered a value in Scientific E Notation and in its drawn out state is the same as a double value of 30000.0. So, instead of the intended $34 bill the 3e4 ends up being a real healthy bill of $30,000.00. To cover this situation a slightly different approach will need to be used. In the code below you will see not just how the Bill Amount prompt code is done using this different approach but also all other prompts:
public void calculateTips() {
Scanner userInput = new Scanner(System.in);
String pattern = "$##,###,###.00;"; // Pattern string for the decimal format
java.text.DecimalFormat moneyFormat = new java.text.DecimalFormat(pattern); // Decimal Money format
java.text.NumberFormat defaultFormat = java.text.NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(1);
String choice;
TipCalculator tipCalculator1 = new TipCalculator();
System.out.println("*** Tip Calculator ***");
do {
choice = "";
boolean isBillValid = false;
boolean isTipValid = false;
boolean isPartySizeValid = false;
double theBill = 0.0d;
int theTip = 0;
int thePartySize = 0;
boolean breakAll = false;
while (!isBillValid) {
System.out.print("Enter the bill amount: --> ");
String theBillStrg = userInput.nextLine().trim();
// Is 'c' or 'C' for CANCEL entered?
if (theBillStrg.equalsIgnoreCase("c")) {
// Set breakAll to true break out of this loop.
breakAll = true;
break;
}
// If the value starts with a decimal point then
// prefix it with a 0.
if (theBillStrg.startsWith(".")) {
theBillStrg = "0" + theBillStrg;
}
// If the value ends with a decimal point then
// postfix it with a 0.
else if (theBillStrg.endsWith(".")) {
theBillStrg += "0";
}
// Is the supplied value a string representation of a
// Integer or double type value?
if (theBillStrg.matches("\\d+(\\.\\d+)?")) {
// Yes it is...
// Parse the string value to a double type
theBill = Double.parseDouble(theBillStrg);
isBillValid = true;
tipCalculator1.setBillAmount(theBill);
}
else {
System.out.println("Invalid Bill amount supplied (" + theBillStrg + ")! Try again...");
}
}
while (!isTipValid && !breakAll) {
System.out.print("Enter your desired tip percentage (0 to 100): --> ");
String theTipStrg = userInput.nextLine();
// Is 'c' or 'C' for CANCEL entered?
if (theTipStrg.equalsIgnoreCase("c")) {
// Set breakAll to true break out of this loop.
breakAll = true;
break;
}
// Is a string representation of a Integer value supplied?
if (theTipStrg.matches("\\d+")) {
// Yes...Convert the string value to Integer
theTip = Integer.parseInt(theTipStrg);
// Is the tip percentage inclusively between 0 and 100?
if (theTip < 0 || theTip > 100) {
// No...
System.out.println("Out of Range tip percentage supplied (" + theTip + ")! Try again...");
continue;
}
isTipValid = true;
tipCalculator1.setTipPercentage(theTip);
}
else {
System.out.println("Invalid tip percentage supplied (" + theTipStrg + ")! Try again...");
}
}
while (!isPartySizeValid && !breakAll) {
System.out.print("Enter the size of your party: ");
String partySizeStrg = userInput.nextLine();
// Is 'c' or 'C' for CANCEL entered?
if (partySizeStrg.equalsIgnoreCase("c")) {
// Set breakAll to true break out of this loop.
breakAll = true;
break;
}
else if (partySizeStrg.matches("\\d+")) {
thePartySize = Integer.parseInt(partySizeStrg);
isPartySizeValid = true;
tipCalculator1.setPartyAmount(thePartySize);
}
else {
System.out.println("Invalid party size supplied (" + partySizeStrg + ")! Try again...");
}
}
if (!breakAll) {
System.out.println();
System.out.println("======================================");
System.out.println("*** Your Bill ***");
System.out.println();
System.out.print("Bill Amount: ");
System.out.println(moneyFormat.format(tipCalculator1.getBillAmount()));
System.out.print("Tip Percentage: ");
System.out.println(defaultFormat.format(tipCalculator1.getTipPercentage()));
System.out.print("Party Size: ");
System.out.println(tipCalculator1.getPartyAmount());
System.out.print("\nTotal Bill (with Tip): ");
System.out.println(moneyFormat.format(tipCalculator1.getTotalAmount()));
System.out.print("\nShare for Each Individual: ");
System.out.println(moneyFormat.format(tipCalculator1.getIndividualShare()));
System.out.println("======================================");
}
while (choice.isEmpty()) {
System.out.print("\nAnother Bill? (y/n): ");
choice = userInput.nextLine();
if (!choice.matches("(?i)[yn]")) {
System.out.println("Invalid input - 'y' or 'n' only! Try again...");
choice = "";
}
}
System.out.println();
} while (choice.equalsIgnoreCase("y"));
System.out.println("\nGoodbye!");
}
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.
I need to user to enter an int between 1 and 301.
I have this simple loop here to check for user input.
I just want a single number from the user, and if the user enters anything other than an int between 1 and 301, I want to display the print line and prompt the users to try again until they enter a valid input.
while (!sc.hasNextInt()) {
System.out.print("Invalid Input. Please enter a valid number between 1 and 301: ");
sc.next();
}
int numToCheck = sc.nextInt();
// do stuff with numToCheck
This checks that the input is an int, but I can't seem to find a way to give the int input a bound. I tried to assign the user input to a variable and then check the conditions input < 1 or input > 301, but I get InputMismatchException if user enters a letter. How should I store the user input? (I want to store it as an int to check the conditions, but can't do that since I don't know what the user will enter).
Perhaps there is a better design to accomplish all this. Those are welcomed too.
Thanks in advance.
You're not saving the value of the of the input. So your program is waiting on the user to enter a number each time it see "sc.nextInt()" Assign the input to a variable, and then check the condition.
EDIT: okay, I'll go the extra mile for you. See if this works.
***Accounted for the case where the user might enter a character instead of a number.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int input;
while (true){
if (sc.hasNextInt()){
input = sc.nextInt(); // Assign the next integer to a variable
if (input <= 301 && input >= 1){ // Check if integer meets condition
break; // Condition met, break out of loop
}
}else{
sc.next();
}
System.out.println("Invalid Input. Please enter a valid number between 1 and 301: ");
}
}
}
I ran this code, to see if it would show a better performance than yours.
Scanner sc = new Scanner(System.in);
boolean valid = true;
do {
if (!valid) {
System.out.print("Invalid Input. ");
}
System.out.print("Please enter a valid number between 1 and 301: ");
String input = sc.next();
try {
int value = Integer.parseInt(input);
valid = (value >= 1 && value <= 301);
} catch (NumberFormatException nfex) {
valid = false;
}
} while (!valid);
When the conversion to integer fails, the JVM hangs a little. I believe your problem has more to do with the try / catch mecanism that Scanner performs under the hood, than with design.
Assuming you want only 1 input from the user, try following simple code, which takes input from the user until user enters a valid input.
Scanner in = new Scanner(System.in);
int flag = 0,x=0;
while(flag == 0){
x = in.nextInt();
if(x<1 || x>301){
flag = 0;
System.out.println("Invalid Input.");
}
else{
flag = 1;
}
}
And if you want user to input more than 1 inputs (i.e 3 here), than set a counter that increases with every valid input of the user, as following:
Scanner in = new Scanner(System.in);
int flag = 0,x=0,count = 1;
while(flag == 0){
x = in.nextInt();
if(x<1 || x>301){
flag = 0;
System.out.println("Invalid Input.");
}
else{
//executes when input is valid
if(count == 3){
flag = 1;
}
count++;
}
}
Edit:
If you also want to check whether the input is Integer or not, than you have to add one extra condition in above code. And as you said you want only one input from user rather than 3, you have to change exit condition. Change code as following:
Scanner in = new Scanner(System.in);
int flag = 0,count = 1,x=0,flag1 = 0;
String y;
while(flag == 0){
y = in.next();
flag1 = 0;
try{
x = Integer.parseInt(y);
}
catch(NumberFormatException e){
flag1 = 1;
System.out.println("Invalid Input.");
}
if((x<1 || x>301)&&flag1 == 0){
flag = 0;
System.out.println("Invalid Input.");
}
else if(flag1 == 0){
//executes when input is valid
if(count == 1){ // put count == 3 if you want 3 inputs from user.
flag = 1;
}
count++;
}
}
Here we are taking the input as a String and than converting the String into the Integer by using Integer.parseInt(). If the String is not Integer, than it will throw the exception and we will continue the loop till the valid input is entered by the user.
Use DO WHILE for result
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
OK ?
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.