Java Scanner ignores answer - java

Hi it's my first post here and I have a problem:
I have a program in which, at some point, asks the user if he wants to share the stars, and if he supposedly does, the program goes back to collecting them and after some time comes back to the question if he wants to share them again.
The problem is that, when the user comes back to that point, the program ignores whatever answer u give to it and goes to the "else answer block".
It looks like this:
"Do you want to share your stars?
yes
Please answer with yes or no"
Code:
import java.util.Random;
import java.util.Scanner;
public class App {
static Scanner skan = new Scanner(System.in);
static int starCount = 0;
static Random random = new Random();
public static void main(String[] args) {
starReaching();
}
static void starReaching() {
boolean starCollected = false;
int i = 0;
int j = random.nextInt(101);
while (i < j) {
i++;
System.out.println("Stars are out of reach");
}
if (i > j || i == j) {
starCollected = true;
}
if (starCollected == true) {
starCollector();
}
}
static void starCollector() {
System.out.println("You caught a star !");
starCount++;
if (starCount == 10) {
System.out.println("You have 10 stars ! :)");
System.out.println("Do you want to share your stars?");
String line = skan.nextLine();
if (line.equals("yes")) {
skan.reset();
starGiver();
} else if (line.equals("no")) {
wishMaker();
} else {
System.out.println("Please answer with yes or no");
System.exit(0);
}
} else {
starReaching();
}
}
static void starGiver() {
System.out.println("How many do you want to share?");
int starsToShare = skan.nextInt();
if (starsToShare < 10 || starsToShare == 10 && starsToShare > 0) {
starCount = starCount - starsToShare;
System.out.println("Stars shared !");
System.out.println("You now have " + starCount + " stars");
System.out.println("Go collect them again!");
starReaching();
} else if (starsToShare > 10) {
System.out.println("You don't have enough stars to share that much!");
starGiver();
} else {
System.out.println("That's not a valid option");
starGiver();
}
}
static void wishMaker() {
}
}

Every time you call skan.nextLine() you read a new line and advance the scanner's pointer, and this is the reason your code is failing: you're calling this too often.
Instead of
if (skan.nextLine().equals("yes")) {
skan.reset();
starGiver();
} else if (skan.nextLine().equals("no")) {
wishMaker();
} else {
do:
String line = scan.nextLine(); // read from Scanner **once** only
if (line.equals("yes")) {
skan.reset();
starGiver();
} else if (line.equals("no")) {
wishMaker();
} else {

Okay i've found the little bugger, i was using skan.nextInt without using skan.nextLine after that, thank you for the quick help, much love

Related

How to fix this algorithmic problem with Java arrays?

I have minor problem with part of the algorithm in this code. Here is a description of the task:
User types in a choice between the numbers 0,1,5 or 2.
0 ends the program,
1 prompts the user to add a name and email to the 2d array,
5 prints out all of the names and email pairs the user typed in. And
2 allows the user to search for an exact match by typing in the name and in return the program prints out the email of the name the user is looking for.
Problem is with the choice == 2 algorithm. It seems that there is a problem and it does not work properly. No matter what the user types it will always print out "Match is found!" and return the wrong email.
Any suggestions?
Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[][] rolodex = new String[257][2];
System.out.println("Welcome!");
int choice;
int p = 0;
String matchValue;
boolean isFound = false;
do {
System.out.println("Please select an option: ");
choice = in.nextInt();
in.nextLine();
if (choice == 1 && p < rolodex.length) {
System.out.println("What's the name?");
rolodex[p][0] = in.nextLine();
System.out.println("What's the email?");
rolodex[p][1] = in.nextLine();
p++;
} else if (choice == 5) {
for (int i = 0; i < p; i++) {
System.out.println("email: " + rolodex[i][1]);
System.out.println("name: " + rolodex[i][0]);
System.out.println("--------------------");
}
} else if (choice == 2) {
System.out.println("Type in the name of the email you want: ");
matchValue = in.nextLine();
for (int i = 0; i < p; i++) {
if (matchValue.equals(rolodex[i][0]) && !isFound) {
isFound = true;
}
if (isFound) {
System.out.println("Match Found!");
System.out.println(rolodex[i][1]);
} else {
System.out.println("Match not found!");
}
}
}
} while (choice != 0);
System.out.println("Thank you! Have a nice day!");
}
}
The initializing of the boolean variable and not re-initializing in the following repetitions was causing the problem in your code. Hence, in the block of code I am suggesting below, I have removed the boolean variable altogether. Furthermore, you could try by breaking off from the loop once the correct email match has been identified by the program.
for (int i = 0; i < p; i++) {
if (matchValue.equals(rolodex[i][0])) {
System.out.println("Match Found!");
System.out.println(rolodex[i][1]);
break;
} else if (i == (p - 1)) {
System.out.println("Match not found!");
}
}
You need to reset the value of isFound after it has been set to true. You have not done so, hence the wrong output.
if (isFound) {
System.out.println("Match Found!");
System.out.println(rolodex[i][1]);
//Add this to your code
isFound = false;
}
There is another problem with your search. You have to stop the loop once the match has been found. You have not done so.
I do suggest you try to do it on your own. You should also check #Ayyan Tahzib answer as it contains a hint on correcting this problem of your searching procedure.
If you face any problems, do comment. I will be happy to help you.

how to print number of stars depending on user choose

I've been trying practiceIt problems and expand them a little - and I'm stuck.
The code will give results in as many stars as it's necessary, but I do not know how to make user decide the value for n.
I've tried adding to both methods (main/starString) those code lines:
"Scanner input = new.Scanner(System.in);
int n = input.next();" [also input.nextInt]
but the code will note allow any input from console. Not to mention I've got no idea where shoud I add second println command to actually print result from this code...
help me please
import java.util.*;
public class printStars {
public static void main(String[]args) {
System.out.println("choose number and I wil show you 2^number stars");
}
public static String starString(int n) {
if (n < 0) {
throw new IllegalArgumentException();
} else if (n == 0) {
return "*";
} else {
return starString(n - 1) + starString(n - 1);
}
}
}
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Choose number and I wil show you 2^number stars: ");
System.out.println(starString(in.nextInt()));
}
public static String starString(int n) {
if (n < 0) {
throw new IllegalArgumentException();
} else if (n == 0) {
return "*";
} else {
return starString(n - 1) + starString(n - 1);
}
}
}
A sample run:
Choose number and I wil show you 2^number stars: 5
********************************
You should also be checking the input before you enter the method. Here is one approach that allows for improper input and reprompts the user to enter the correct value. This way, no exceptions need be caught.
Scanner in = new Scanner(System.in);
String prompt = "Choose number (or a char to end) \nand I will show you 2^number stars: ";
System.out.print(prompt);
while (in.hasNextInt()) {
int n = in.nextInt();
if (n > 0) {
System.out.println(starString(n));
} else {
System.out.print("Input must be greater than 0, try again: ");
continue;
}
System.out.print(prompt);
}
System.out.println("Bye!");
public static String starString(int n) {
if (n == 0) {
return "*";
} else {
return starString(n - 1) + starString(n - 1);
}
}

AIrline Reservation

I am trying to do a basic Java Airline Reservation App. Here is my code, It seems that after I press '1' it is terminating and not running the rest of the code. I am not sure if it is something wrong with my loop or why it is terminating. Please if anyone has any ideas or answers I would love to hear them! thanks
import java.util.Scanner;
public class Reservation {
boolean[] seat = new boolean[11];
Scanner input = new Scanner(System.in);
public void start() {
while (true) {
makeReservation();
}
}
public void makeReservation() {
System.out.println("Please type 1 for first class and type 2 for economy");
int section = input.nextInt();
if (section == 1) {
firstClassSeat();
} else {
economySeat();
}
}
public void firstClassSeat() {
for (int count = 1; count <= 5; count++) {
if (seat[count] = false) {
seat[count] = true;
System.out.printf("First Class. Seat# %d\n", count);
break;
} else if (seat[10] == true) {
if (seat[5] == true) {
} else {
System.out.println("First class is fully booked, would you like an econmy seat");
int choice = input.nextInt();
if (choice == 1) {
firstClassSeat();
start();
} else {
System.out.println("Next flight is in 3 hours");
System.exit(0);
}
}
}
}
}
public void economySeat() {
for (int count = 6; count <= 10; count++) {
if (seat[count] = false) {
seat[count] = true;
System.out.printf("First Class. Seat# %d\n", count);
break;
} else if (seat[10] == true) {
if (seat[5] == true) {
} else {
System.out.println("Economy is fully booked. Would you like First Class? 1 for Yes 2 for No");
int choice = input.nextInt();
if (choice == 1) {
firstClassSeat();
start();
} else {
System.out.println("Next flight is in 3 hours");
System.exit(0);
}
}
}
}
}
}
First off, there is no need to compare booleans inside an if. seats[i] == false is the same as !seats[i].
Nothing is happening because you have an assignment:if(seat[count]=false instead of comparison:if(seat[count]==false. That's the first error, after fixing that you will start assigning seats.
Next, you're calling firstClassSeat inside the same method, when I think you wanted to call economySeat (when first class is full). You need to fix the logic behind the checks and economy/first class suggestions.

printing a print statement after a certain amount of tries in a loop

I am new to coding. I created a guessing game, and it works well but, I would like to know how to make it so that after the user attempts guessing the number 3 times, they get a hint which I put on the last line, but it is currently unreachable, and I do not know how to make the statement reachable, and in the do while loop. I am currently stuck. Thank you
import java.util.Scanner;
public class guessing_game {
public static void main (String[] args) {
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc() {
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
public static int run(Scanner kb) {
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
int num = 44;
int tries = 0;
do {
if (guess < num) {
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
run(kb);
}
else if ((guess > 100) || (guess < 0)) {
System.out.println("That isn't between 1-100 is it?");
System.out.println();
run(kb);
}
else if (guess > num) {
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
run(kb);
}
else if(guess == num) {
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y")) {
run(kb);
}
else if (choice.equalsIgnoreCase("n")) {
System.exit(0);
}
}
tries++;
}while(tries < 3);
{
System.out.print("Here's a hint the lucky number is 4");
}
return guess;
}
}
There are a few flow issues with your program, but here is a simple way to fix it up.
First of all, you are not actually using the value of guess when you return it from your run() method, so that can be removed.
Also, in cases like this, you would not want to use a do/while loop, but just while. You want to keep repeating the prompt until the user guesses correctly. So add a boolean to allow you to check if they won:
boolean correct = false; - We set it false to begin because they haven't won yet.
Now, instead of calling run() again after every guess (which resets the tries count every time, just let the while loop do its job and repeat itself. Hence, we need to move the prompt input into the while loop.
Here is a complete code listing of the changes:
import java.util.Scanner;
public class guessing_game {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc() {
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
// Change the return type to void as you never use the value returned
public static void run(Scanner kb) {
int num = 44;
// Add a boolean to determine if the game is won
boolean correct = false;
int tries = 0;
while (!correct) {
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
if (guess < num) {
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
} else if ((guess > 100) || (guess < 0)) {
System.out.println("That isn't between 1-100 is it?");
System.out.println();
} else if (guess > num) {
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
} else if (guess == num) {
// Flag the guess as correct; this will exit the loop after this run
correct = true;
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y")) {
run(kb);
} else if (choice.equalsIgnoreCase("n")) {
System.exit(0);
}
}
tries++;
}
}
}
1.You are recursively calling run() method and every time you call this method, a new variable try will be created and initialised to zero.
2. Your recursive call is before the condition check and due to the same reason the logic may never reach the condition check.
To make this work with minimal changes, you can use the following code. But this is not the best as it does not resolve the above shortcomings
import java.util.Scanner;
public class guessing_game {
static int tries = 0;
public static void main (String[] args)
{
Scanner kb = new Scanner(System.in);
desc();
run(kb);
//int nun = 0;
//for (int i = 0; i < nun; nun ++)
}
public static void desc()
{
System.out.println("This is a guessing game.");
System.out.println();
System.out.println("Let's see how many tries it takes you to guess the right number!");
System.out.println();
System.out.println();
System.out.println();
}
public static int run(Scanner kb)
{
System.out.println("Please enter a number between 1-100");
int guess = kb.nextInt();
int num = 44;
do{
tries++;
if(tries>=3) break;
if (guess < num)
{
System.out.println("Oooh. Your guess is too low. Try again.");
System.out.println();
run(kb);
}
else if ((guess > 100) || (guess < 0))
{
System.out.println("That isn't between 1-100 is it?");
System.out.println();
run(kb);
}
else if (guess > num)
{
System.out.println("Aaah. Your guess is too high. Try again.");
System.out.println();
run(kb);
}
else if(guess == num)
{
System.out.println("Bingo!!! Nice guess bud.");
System.out.println("Tell a friend to play! Wanna try again? (y or n)");
String choice = kb.next();
if (choice.equalsIgnoreCase("y"))
{
run(kb);
}
else if (choice.equalsIgnoreCase("n"))
{
System.exit(0);
}
}
}while( tries < 3);
{
System.out.print("Here's a hint the lucky number is 4");
}
return guess;
}
}

newbie to nested if statements

I am learning to use Java and code on my own, I am network Tech and wanted to learn how to Code. I am learning from a site called programming by doing and I am stuck on one assignment:
https://programmingbydoing.com/a/twenty-questions.html
below is my code, it will compile but the issue is with the nested if statement not working properly please help!!!
import java.util.Scanner;
public class twentyQuestions
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String question1, question2, guess;
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I will try to guess it.");
System.out.println();
System.out.println("Question 1: Is it an animal, vegetable, or mineral?");
question1 = keyboard.next();
System.out.println();
System.out.println("Question 2: Is it bigger than a bread box?");
question2 = keyboard.next();
if (question1.equals("animal"))
{
if (question2.equals("no"))
{
guess = "squirrel";
}
else {
guess = "moose";
}
}
else if (question1.equals("vegetable"))
{
if (question2.equals("no"))
{
guess = "carrot";
}
else
{
guess = "watermelon";
}
}
else if (question1.equals("mineral"));
{
if (question2.equals("no"))
{
guess = "paper clip";
}
else
{
guess = "Camaro";
}
}
System.out.println("You're thinking of a " + guess);
}
}
}
First off all, you need to remove the semicolon after
else if (question1.equals("mineral"))
Then, you need to add a final else block at the end of the if statement to catch input that does not match any of the three inputs. Then it will be able to compile:
...
else if (question1.equals("mineral"))
{
if (question2.equals("no")) {
guess = "paper clip";
} else {
guess = "Camaro";
}
}else{
System.out.println("Invalid input");
return;
}
...
THANK YOU ALL here is my final code that works thanks to everyone...:
import java.util.Scanner;
public class twentyQuestions
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String question1, question2, guess = "";
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I will try to guess it.");
System.out.println();
System.out.println("Question 1: Is it an animal, vegetable, or mineral?");
question1 = keyboard.next();
System.out.println();
System.out.println("Question 2: Is it bigger than a bread box?");
question2 = keyboard.next();
if (question1.equals("animal"))
{
if (question2.equals("no"))
{
guess = "squirrel";
}
else {
guess = "moose";
}
}
else if (question1.equals("vegetable"))
{
if (question2.equals("no"))
{
guess = "carrot";
}
else
{
guess = "watermelon";
}
}
else if (question1.equals("mineral"))
{
if (question2.equals("no"))
{
guess = "paper clip";
}
else
{
guess = "Camaro";
}
}
else{
System.out.println("Invalid input");
return;
}
System.out.println("You're thinking of a " + guess);
}
}

Categories

Resources