How to make a do statement restart? - java

I really do not know to how explain this but here we go.
I am testing something for a bigger program I have to make. In the program I have to validate input from the user to see if it is being to be accepted as a valid answer.
I have the code to where it will say if the input is invalid but if I attempted to enter another letter the code crashes with this error:
Enter a letter:
f
Your answer is not valid.
A
Enter a letter:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at example.main(example.java:18)
Here is the code:
import java.util.Scanner;
public class example
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean UserInput;
do
{
char user_answer = 0;
System.out.println("Enter a letter:");
user_answer=input.nextLine().charAt(0);
if ( user_answer == 'A')
{
UserInput = true;
}
else if (user_answer == 'B')
{
UserInput = true;
}
else if (user_answer == 'C')
{
UserInput = true;
}
else if (user_answer == 'D')
{
UserInput = true;
}
else
{
System.out.println("Your answer is not valid.");
UserInput = false;
input.next();
}
}
while (!UserInput);
}
}

either remove input.next() or change it to input.nextLine()
What's happening is that input.next() will catch the A you input. Then you go back to the beginning of the do and start over, and do input.nextLine() but you had already pressed enter to input A and the A was consumed by input.next().

Remove the input.next(); and it will work fine. The reason is because when you use input.next(), it reads the next character the user types, without exiting the line. Then when the input.nextLine() executes, it reads that same line, but immediately after the number. Since nothing is after the number, it reads in nothing "" and the charAt(0); becomes out of bounds.

import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean UserInput;
do
{
char user_answer = 0;
System.out.println("Enter a letter:");
// user_answer=input.nextLine().charAt(0);
user_answer=input.next().charAt(0);
if ( user_answer == 'A')
{
UserInput = true;
}
else if (user_answer == 'B')
{
UserInput = true;
}
else if (user_answer == 'C')
{
UserInput = true;
}
else if (user_answer == 'D')
{
UserInput = true;
}
else
{
System.out.println("Your answer is not valid.");
UserInput = false;
// input.next();
}
}
while(!UserInput);
}
}

Related

y/n input validation including no input Enter key

I am trying to catch no input (enter key) and invalid input everything but y/n in one method. I tried it two different ways (pasted) but I cannot make work both “enter key” and “mistype y/n” together. Thank you for your help.
1st attempt:
public static String askToContinue(Scanner sc) {
String choice = "";
boolean isValid = false;
while (!isValid){System.out.print("Continue? (y/n): ");
if (sc.hasNext()){
choice = sc.next();
isValid = true;
} else {System.out.println("Error! "
+ "This entry is required. Try again");
}
if (isValid && !choice.equals("y") || !choice.equals("n")) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
isValid = false;
}
}
//sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}
2nd attempt
public static String askToContinue(Scanner sc) {
System.out.print("Continue? (y/n): ");
String choice;
while (true) {choice = sc.next();
//?????????????????????????????????????????????????????
if (choice.length() == 0){ System.out.println("Error! "
+ "This entry is required. Try again");
continue;
}
if (!(choice.equals("y") || choice.equals("n"))) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
continue;
}
break;
}
sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}
I tried with 1st attempt of your code. I explained with comment line which is included in below code like ;
public static String askToContinue(Scanner sc) {
String choice = "";
boolean isValid = false;
while (!isValid) {
System.out.print("Continue? (y/n): ");
choice = sc.nextLine(); //to reads all line , because this cannot read with empty enter input
isValid = true;
if (choice.isEmpty()) { //this isEmpty for empty enter
System.out.println("Error! "
+ "This entry is required. Try again");
}
System.out.println(choice);
//this logic if not y or n , it will return error
if (!choice.equals("y") && !choice.equals("n")) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
isValid = false;
}
}
//sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}
Your if statement in first case is wrong. You are checking if choice is not equal to 'y' or not equal to 'n' which will always be true .
Change
if (isValid && !choice.equals("y") || !choice.equals("n"))
To
if (isValid && !choice.equals("y") && !choice.equals("n"))

How do I break out of a loop while reading in a string?

For example:
Scanner keyboard = new Scanner(System.in);
int counter=1;
while (!(keyboard.equals('0')))
{
for (int i=1;i<=counter;i++)
{
prodNum[i]=keyboard.nextInt();
quantity[i]= keyboard.nextInt();
}
counter++;
}
How do I break out of a loop when I enter in a zero? I can't seem to figure it out. It keeps taking input, even when I enter a zero? I need for it keep taking input until the user enters a zero.
Any ideas what I'm doing wrong?
keyboard.equals('0') will compile, but it is never going to evaluate to true, because Scanner object cannot possibly be equal to a Character object.
If you would like to wait for the scanner to return zero to you, you should call next() or nextLine() on it, and compare the resultant String object to "0".
while (true) {
while (keyboard.hasNext() && !keyboard.hasNextInt()) {
System.out.println("Please enter an integer value.");
keyboard.nextLine();
}
if (!keyboard.hasNextInt())
break;
prodNum[i]=keyboard.nextInt();
if (prodNum[i] == 0)
break;
while (keyboard.hasNext() && !keyboard.hasNextInt()) {
System.out.println("Please enter an integer value.");
keyboard.nextLine();
}
if (!keyboard.hasNextInt())
break;
quantity[i]=keyboard.nextInt();
if (quantity[i] == 0)
break;
i++;
}
Demo.
int counter=1;
int flag = 1;
while (flag != 0)
{
for (int i=1;i<=counter;i++)
{
if(flag == 0)
{
break;
}
prodNum[i]=keyboard.nextInt();
quantity[i]= keyboard.nextInt();
flag = quantity[i];
}
counter++;
}

Java SecretWord Code

I am making basic java program to hold a secret word (mouse) and allow a user to guess letters. The program will end either when the user guesses all the letters in the word, or when they guess 7 wrong letters. Whenever I type any letter into the program, it will run through it without giving the user an option to enter another letter. What should I add so that it will only run the program once per letter entered? Also if it wasnt quite obvious I am new to coding.
import java.util.Scanner;
public class GuessWord
{
String Secretword="mouse";
String letter;
int index;
private int number;
private int counter;
private String guesses;
Scanner scan = new Scanner(System.in);
public GuessWord()
{
String Secretword="";
String letter = "";
String guesses = "";
int number = 0;
int counter = 0;
int index = 0;
}
public String getLetter(){
System.out.println("Please enter a letter");
letter = scan.next();
return letter;
}
public void calc(){
guesses=letter;
while(number <= 7 && counter<5)
{
if(Secretword.indexOf(letter) != -1)
{
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
}
else
{
System.out.println("You entered an incorrect letter");
number++;
}
guesses=guesses+" " +letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if(number == 7){
System.out.println("You lose");
}else
{
System.out.println("You win");
}
}
}//class
public class GuessWordR
{
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
g1.getLetter();
g1.calc();
}//class
}//main
You should use a while loop.
So while some condition is not met keep asking the user to enter a new key.
Perhaps add a new method to the GuessWord Class
public void startGuessing() {
while(hasGuesses /* some boolean flag */) {
getLetter()
getCalc()
}
}
And then call that method in your main method instead of getLetter() and getCalc().
You will need to add a boolean variable to your class to indicate when to exit this while loop and the logic to keep count of the number of failed guesses etc.
Use a boolean flag and run it in a loop. but for that you need to restructure your code as well. First fix the calc() method
public boolean calc() {
guesses = letter;
if (number <= 7 && counter < 5) {
if (Secretword.indexOf(letter) != -1) {
index = Secretword.indexOf(letter);
System.out.println("You entered a letter in the word");
counter++;
} else {
System.out.println("You entered an incorrect letter");
number++;
}
guesses = guesses + " " + letter;
System.out.println("The letters you have guessed are:" + guesses);
}
String str;
if (number == 7) {
System.out.println("You lose");
return true;
} else if (counter == 5) {
System.out.println("You win");
return true;
} else {
return false;
}
}
Your main method should be update like this
public static void main(String[] args) {
GuessWord g1 = new GuessWord();
boolean completed = false;
while (!completed) {
g1.letter = g1.getLetter();
completed = g1.calc();
}
}
you ask user for input unless condition get satisfied instead of asking and calculating once. And read char by char input instead of reading whole string.
something like:
public static void main(String[]args)
{
GuessWord g1 = new GuessWord();
while(number <= 7 && counter<5){
g1.getLetter();
g1.calc();
}
}//class

Boolean bug (FibonacciNumbers)

First of all I am not asking anyone to do anything just need a little help to fix this bug with boolean. I put false but the program stops. I got two parts to the program.
First part where i did the calculations:
class FibonacciNumbers {
FibonacciNumbers() {} //default constructor
public int fOf(int n) {
if (n == 0) //the base case
{
return 0;
} else if (n == 1) {
return 1;
} else {
return fOf(n - 1) + fOf(n - 2);
}
}
}
Second where the main method is:
import java.util.*;
public class FibonacciNumbersTesters {
public static void main(String[] args) {
FibonacciNumbers fNumbers = new FibonacciNumbers(); //creates new object
Scanner in = new Scanner(System.in);
String again;
String test;
boolean IsRepeat = true;
boolean isQuit;
try {
isQuit = false;
while (!isQuit) {
System.out.print("Enter the number you want to convert to Fibanocci('q' to quit): ");
int n = in.nextInt();
System.out.print("The Fibanocci number for " + n + " is: ");
n = fNumbers.fOf(n);
System.out.println(n);
System.out.print("Do you want to run again? (Y or N): ");
again = in.next();
if (again.equalsIgnoreCase("N")) {
System.out.println("Thank you! Please terminate the program by entering 'Q' or 'q' OR you can cotinue by entering anything else: ");
String toQuit = in.next();
if ((toQuit.charAt(0) == 'q') || (toQuit.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
}
} else {
IsRepeat = true;
}
}
} catch (InputMismatchException ex) {
test = in.nextLine();
if ((test.charAt(0) == 'q') || (test.charAt(0) == 'Q')) {
System.out.println("Good-bye!");
isQuit = true;
} else {
System.out.println("Invalid input!");
System.out.println("Try again! ");
isQuit = false;
}
}
}
}
This part where i put isQuit = false; at the end it just stops. I want it to continue.
Try putting your try catch statement inside of your while loop.

Throwing Exception

I am trying unsuccessfully to throw an exception TooLongEx if a user input fails. Been stuck on this forever :(
import java.util.Scanner;
public class MessageTooLong extends Exception {
public static void main(String args[])
throws TooLongEx {
Scanner keyboard = new Scanner(System.in);
String line;
char preference;
int length;
boolean go = true;
while (go) {
System.out.println("Enter a line of text.");
System.out.println("Use no more than 20 characters.");
line = keyboard.next();
length = line.length();
if (length <= 20) {
System.out.println("You entered " + length + " characters, which is an acceptable length.");
System.out.println("Would you like to enter another line?");
System.out.println("Enter 'y' to continue or 'n' to quit.");
preference = keyboard.next().charAt(0);
if ((preference == 'y') || (preference == 'Y')) {
go = true;
} else {
go = false;
}
} else {
throw new TooLongEx();
}
}
}
}
Seems to work fine for me.
For
class TooLongEx extends Exception {}
I get (for an input length > 20)
Exception in thread "main" TooLongEx
at
MessageTooLong.main(MessageTooLong.java:26)

Categories