Else-If / While Loop stuck - loops

I'm trying to make a program that takes input of a minimum and a maximum number and then generates a random number in that range. Then the user guesses a number and if it's too high, it outputs a messege.. If it's too low, it outputs a message. The part that i'm stuck at is when you guess the number correctly, the user inputs "Y" or "N" to run the program again.
My code is as follows:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame_V2
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print('\u000C');
int min;
int max;
int userGuess;
int numberGuesses = 1;
System.out.println("Enter the minimum number: ");
min = in.nextInt();
System.out.println("Enter the maximum number: ");
max = in.nextInt();
Random r = new Random();
int randomNumber = r.nextInt(max - min + 1) + min;
System.out.println("Enter your guess: ");
userGuess = in.nextInt();
String guessAgain = ("Y");
while(!guessAgain.equalsIgnoreCase("N"))
{
if( userGuess > randomNumber ){
System.out.println("Your guess was to high! Guess again!");
System.out.println("Input your new guess: ");
userGuess = in.nextInt();
numberGuesses++;
}
else if (userGuess < randomNumber ){
System.out.println("Your guess was to low! Guess again!");
System.out.println("Input your new guess: ");
userGuess = in.nextInt();
numberGuesses++;
}
else
{
System.out.println("Congratulations, you guessed the number!");
System.out.println("It took " + numberGuesses + " tries");
System.out.println("Guess another number? (Y/N)");
guessAgain = in.next();
}
}
System.out.println("Thank's for playing!");
}
}
The problem comes when the user hits "Y" to restart the program. It doesn't restart and just displays the final message again. (print statement, number of guesses, and Y/N). I need the program to restart when the user types "Y"
I'm new to posting on the site.. so forgive me if I messed up putting in the code -
Thanks in advance for the help -
*Changes - 11/13/13 10:58 Changed the code to take more than one input and to
keep taking input until the user gets it right.

You need nested loops because you are doing two repetitive actions--first is repeating the game and second is prompting for guesses within one game.
So use nested loops. One loop prompts the user if he or she wants to play and prompts the user again with the same question at the end. The nested loop should be as you have it.
Your code should be along the lines of
while (stillPlaying) {
while (stillGuessing) {
}
}
Hope that helps.

Related

Guessing Game in C programming

I built a guessing game in C programming using while loop, and I am having a problem with it during execution. So, when I print a number less than the guess number or greater than the guess number, I get the correct answer. But when the user enters the right answer, the screen shows the statement for the greater number "The number you entered is greater than the Secret Number." and then it shows the right statement below this "This is the secret Number." I think the problem could be because else statement does not define the condition for greater number but I am not sure how to solve this. Can somebody help me?
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Guessing game
const int SecretNum = 4;
int guess;
while (guess != SecretNum){
printf("Enter a number: ");
scanf("%d", &guess);
if (guess < SecretNum){
printf("The number you entered is less than the Secret Number. \n");
} else printf("The number you entered is greater than the Secret Number.\n");
}
printf("This is the secret number.\n");
return 0;
}
You think the problem could be because else statement does not define the condition for greater number, so you should add that.
Also you have to initialize guess before using its value.
Formatting your code using indent properly is another important portion.
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Guessing game
const int SecretNum = 4;
int guess = !SecretNum; /* initialize guess : guess will be different value from SecretNum using this */
while (guess != SecretNum){
printf("Enter a number: ");
scanf("%d", &guess);
if (guess < SecretNum){
printf("The number you entered is less than the Secret Number. \n");
} else if (guess > SecretNum) /* add condition */
printf("The number you entered is greater than the Secret Number.\n");
}
printf("This is the secret number.\n");
return 0;
}

Number guessing game in C

I had a problem at doing my number guessing game in C. While running the program it shows up return function when I put the char element in there. Can someone help me with this? Also how can I improve my code in order to make it workable? I'M really stuck with this issue.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int main()
{
char s, n, q;
int b;
bool (1=true), (0=false);
int secret;
secret = rand();
int guess;
int seed;
srand(seed);
printf("Welcome to the guessing game!\n");
do{
printf("Menu: (s) to start a new game, (n) to set a new range, or (q) to quit:\n");
scanf("%s, %s, %s", s, n, q);
if((s==1))
{
printf("The secret number is Between 0 AND rand(). Guess\n");
scanf("%s", b);
}
else if((n ==1))
{
printf("Enter a new MAXIMUM\n");
scanf("%s", rand());
if(( s ==1))
{
printf("The secret number is Between 0 AND rand(). Guess\n");
scanf("%s", b);
printf("The secret number is between 0 and rand() Guess:");
scanf("%s", b);
if(guess = rand()){
printf("Congratulations you won, You took %d guesses!", b);
break;
}
else if(guess > rand())
{
printf("Too High, Guess again:");
}
else if(guess < rand()){
printf("Too Low, Guess Again:");
}
else{
printf("This number out of the number set!");
}
}
}
else{
printf("Unrecognized command");
}
}while(q == 1);
printf("You quited the game");
return 0;
}
This code has myriad issues to resolve. I'd suggest approaching your code writing process in small steps. It appears as though you wrote the entire program in one burst, ran it, and found it didn't work instead of incrementally adding small features and running each one to verify it works before moving on to the next step. Not doing this results in a difficult to debug program and a lack of understanding about how the program operates.
To be specific, try writing a three or four line program that collects and prints user input. Is the output working as you expect? Did you test its robustness on a variety of input? Can you write it to use a variety of data types? If something isn't working, did you research the problem and resolve it before steaming ahead?
Some areas of your program to investigate:
bool (1=true), (0=false); doesn't compile and isn't necessary for the program. If you #include <stdbool.h> you don't need to do this (you can simply write if (something == true)).
srand() is not properly called or seeded. Seed it once per program using the time() call from the header you included and call rand() once per game. Use the % operator to set the function output between 0 and max.
On each turn, compare guess against the value you previously stored rand() in rather than calling rand() during each comparison, which makes the game logic arbitrary.
%s input isn't appropriate; read chars %c and ints %d, passing appropriate variable references to scanf. scanf("%s, %s, %s", s, n, q); collects 3 whitespace separated strings for input instead of 1 char as the prompt suggests.
There is no game loop. Add an inner loop to run a game when the user chooses s and move your guess/response logic there.
Use more verbose variable names and correct brackets and indentation to improve readability.
Putting it all together, here's one possible working version. It could make better use of functions and implement secure user input (exercises for the reader):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char menu_choice;
int guess;
int guesses;
int secret;
int max = 100;
srand(time(NULL));
printf("Welcome to the guessing game!\n");
for (;;) {
printf("\nMenu: (s) to start a new game, (n) to set a new range, or (q) to quit: ");
scanf(" %c", &menu_choice);
if (menu_choice == 's') {
guesses = 0;
secret = rand() % max;
for (;;) {
printf("\nThe secret number is between 0 and %d. Enter a guess: ", max);
scanf("%d", &guess);
guesses++;
if (guess == secret) {
printf("\nCongratulations, you won! You guessed %d in %d guesses!\n", secret, guesses);
break;
}
else if (guess > secret) {
printf("Too high! Guess again.");
}
else if (guess < secret) {
printf("Too low! Guess again.");
}
else if (guess >= max) {
puts("Out of range");
}
}
}
else if (menu_choice == 'n') {
printf("\nEnter a new maximum: ");
scanf("%d", &max);
}
else if (menu_choice == 'q') {
puts("\nGoodbye!");
break;
}
else {
puts("\nUnrecognized command.");
}
}
return 0;
}
Sample run:
Welcome to the guessing game!
Menu: (s) to start a new game, (n) to set a new range, or (q) to quit: n
Enter a new maximum: 50
Menu: (s) to start a new game, (n) to set a new range, or (q) to quit: s
The secret number is between 0 and 50. Enter a guess: 25
Too low! Guess again.
The secret number is between 0 and 50. Enter a guess: 37
Too low! Guess again.
The secret number is between 0 and 50. Enter a guess: 43
Too low! Guess again.
The secret number is between 0 and 50. Enter a guess: 47
Congratulations, you won! You guessed 47 in 4 guesses!
Menu: (s) to start a new game, (n) to set a new range, or (q) to quit: q
Goodbye!
printf("Menu: (s) to start a new game, (n) to set a new range, or (q) to quit:\n");
scanf("%s, %s, %s", s, n, q);
you dont need to use three variables s,n,q. you should ask the user to enter a single choice. either to start a new game or to quit or aything else.
secondly, rand() returns a random number every time. you are supposed to store random number somewhere. like this
rand_num=rand()
also
if(guess = rand())
is a wrong way of comparison. this should be
if(guess==rand_num)
finally binary search is the solution for your problem. please refer it on internet

Another way to terminate loop?

I'm studying loops in class and for one of the labs, I have to figure out a way for the user to enter an unspecified number of integers to calculate the average. I know I can have the user enter the number of integers to be averaged in order for the loop to be terminated like below:
int count = 0, value = 0, sum = 0, numberofintegers = 0;
double avg = 0;
printf("enter the number of integers you wish to average\n");
scanf("%d",&numberofintegers);
//loop
while (count < numberofintegers)
{
printf("enter a positive integers\n");
scanf("%d",&value);
sum = sum + value;
count = count + 1;
}
avg = (double) sum/count;
So basically I could have a user input the number of integers to be averaged in order for the loop to terminate, but there has to be another way to make the loop terminate without having the user input it?
Normally you'd use a predetermined "illegal" number like (say -1)
input = read_a_value();
while(input != -1)
{
// do something with input
input = read_a_value();
}
scanf returns the number of successful entries.
This may solve your issue.
#include<stdio.h>
int main(void)
{
int number, total = 0, count = 0;
char c;
printf("Enter a number to continue, a character to exit\n");
while (scanf("%d", &number) == 1)
{
total+= number;
count++;
}
/* You need to handle the case where no valid input is entered */
(count > 0) ? printf("Average : %.2f\n", (float)total / count) : printf("No valid numbers entered\n");
/* I have casted the average to float to keep the precision*/
while (getchar() != '\n')
;;
printf("Press any key to continue..");
getchar();
return 0;
}
A downfall is that the scanf will continue to prompt for input if a user presses the Enter Key repeatedly. In fact you might wish to replace the scanf with fgets. Have a look here.
If you are sure that the user doesn't enter too many numbers, use a string.
Length of string, you can choose according to you and split it using spaces to get the numbers

(Beginner) Using 2 loops to determine if number is prime...doesn't work for some numbers

I'm just gonna post the functional part of my program here (not the methods for the hello and goodbye graphics...they're fine!). Basically the program has the user input a whole number, determines if it's prime or not, and asks them if they want to do it again. It continues to run the loop until they say no.
Here's what I have so far.
Main:
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
int n = 0, even = 2;
int answer = 0;
String reply;
char doAgain = 'Y';
Welcome();
do
{
System.out.print("Enter a whole number: ");
n = scan.nextInt();
PrimeTest(n);
System.out.print("Try another number? (Y/N): ");
reply = scan.next().toUpperCase();
doAgain = reply.charAt(0);
System.out.println();
}while(doAgain != 'N');
Goodbye();
}
And here's the part that isn't working, apparently--it does nothing for 3, and says 21 IS a prime number:
public static void PrimeTest(int n)
{
int two = 2;
while(two <= n / 2)
{
if(n % two == 0)
{
System.out.println(n + " is not a prime number.");
System.out.println();
}
else
{
System.out.println(n + " is a prime number.");
System.out.println();
}
break;
}
}
Any help is appreciated! Whether it's efficiency, or just pointing out where I messed up. Please let me know what other details you need to help me.
That test is as faulty as it can be... it simply checks if a number is even (but you've substituted words for saying it is/isn't a prime).
You also never change two, so technically that while loop should never end.
it does nothing for 3
two <= n / 2 will always evaluate to false when n is equal to three - so nothing will get printed because the while loop won't get entered.
and says 21 IS a prime number
What your modulus calculation is doing is showing that 21 is odd, but because you've changed the wording it shows as prime.

reached end of file while parsing,

what is wrong with this , i am getting an error that states: reached end of file while parsing. what do i do to fix this?
i have tried several thing with no result
public class FindMin
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int smallest = 9999999;
String userInput;
boolean quit = false;
System.out.println("This program finds the smallest number"
+ " in a series of numbers");
System.out.println("When you want to exit, type Q");
while(quit != true)
{
System.out.print("Enter a number: ");
userInput = keyboard.next();
if(userInput.equals("Q")) userInput.equals("q");
{
if(quit == true) {
}
else
{
int userNumber = Integer.parseInt(userInput);
if(UserNumber < smallest)
smallest = userNumber;
}
}
System.out.println("The smallest number is " + smallest);
System.exit(0);
}
Check your braces: they don't match up, which is why the compiler complains:
FindMin.java:35: reached end of file while parsing
Besides there's a typo and some other issues with that program. See other answers for reference :)
It was just too messy, try this
import java.util.Scanner;
public class FindMin{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int smallest = 9999999;
String userInput;
boolean quit = false;
System.out.println("This program finds the smallest number"
+ " in a series of numbers");
System.out.println("When you want to exit, type Q");
while(true)
{
System.out.print("Enter a number: ");
userInput = keyboard.next();
if(userInput.equalsIgnoreCase("q"))
break;
else{
int userNumber = Integer.parseInt(userInput);
if(userNumber < smallest)
smallest = userNumber;
}
}
System.out.println("The smallest number is " + smallest);
}
}

Resources