unable to get loop to work properly - java

import java.util.Random;
import java.util.Scanner;
public class addinggamedowhile
{
public static void main (String[]args)
{
Random r = new Random ();
Scanner s = new Scanner(System.in);
int x = r.nextInt(20)+1;
int y = r.nextInt(20)+1;
int sum = x + y;
int guess;
System.out.println("===========");
System.out.println("Adding Game");
System.out.println("===========");
System.out.println();
int tries = 0;
for (int games = 0; games < 10; games++)
{
do
{
System.out.print (x + " + " + y + " = ");
guess = s.nextInt();
if (guess != sum && tries < 2)
{
System.out.println("Not quite. Try again!");
System.out.println();
tries++;
}
else
System.out.println("Not quite. The answer is " +sum+ ".");
System.out.println();
}
while (guess != sum);
System.out.println("Congratulations. You got it!");
System.out.println();
}
}}
I'm having trouble with this loop. I cannot get the loop to terminate when I want it to. It's supposed to last for only ten "guesses". In addition, when the user gets the question right, my else statement is also executed. The other thing is that once the user gets the question correct, or does not get the question correct in the three times it is allowed, a new set of numbers are supposed to appear. I have not been able to get that to execute properly either. I've tried different things that worked well, but the requirement for the project is to use a do while loop.

How about something like this?
do {
//your code here
} while (guess != sum && tries <= 10);
The loop will keep going until the sum is correct or the number of tries is exhausted. Increment tries by one every time the loop iterates.
Then, after completion (i.e. outside the loop), do a check to see if the guess is the correct sum or if the tries were exhausted and print out the response accordingly.

Alternatively you can use the break keyword when the guess is correct or no more tries. Also, you should probably reset your tries variable inside the outer for loop (so that it get's reset at the beginning f each game).

Related

I want to add the a feature where the program to ask the user if they want to continue

I want to add a feature to my while loop if they want to try again but I don't know where to put the code. If the user enters N, the code shall stop and if he enters Y, it shall re-ask for the start, end and step.
import java.util.Scanner;
public class Sum3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int start, end, step;
char option;
System.out.print("Enter START value: ");
start = input.nextInt();
System.out.print("Enter END value: ");
end = input.nextInt();
System.out.print("Enter STEP value: ");
step = input.nextInt();
while (start > end)
System.out.println("Start is larger than End");
while (step == 0)
System.out.println("Step is larger than the zero");
while (true)
for (int i = start; i < end; i += step)
System.out.println(i);
/*System.out.println("Would you still want to continue? (Y/ N)");
option = input.next().charAt(0);*/
}
}
I can see a few significant problems in your code.
Like all of your while loops are infinite. You can just use "if-else" instead.
Next, I'm not sure why you put that for loop inside that endless while loop.
What you can do instead is, do your printing inside for loop and then ask if they want to retry. Here's an example :
for (int i = start; i < end; i = i + step)
{
System.out.println(i);
System.out.println("Retry (Y/N) : ");
option = input.nextChar();
if (option == 'N')
{
break;
}
}
You can add a do-while loop and put all your logic within it. So basically it should begin before your first sysout and should end after your commented code at the end.
But there are some other problems in your code. For example,
while(step == 0) should be if(step == 0) or better if(step <=0), because you want to show the message if step is 0 or negative, otherwise you want to print the numbers, correct?
You don't need the while(true) around the for loop. For loop itself should be enough.
Take this as a suggestion and build around your code.

while loop incrementing an extra time

The below while loop runs an extra time. I am trying to perform a user input that accepts 10 valid numbers from the user and prints their sum. However, the while loop executes an extra time and asks for the 11th input.
import java.util.Scanner;
class userInput{
public static void main(String[] args) {
int i = 1, sum = 0;
Scanner sc = new Scanner(System.in);
while(i <= 10){
i++;
System.out.println("Enter number " + "#" +i);
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum += userChoiceNumber;
}else{
System.out.println("Invalid Input");
}
}
System.out.println("The sum of your entered numbers are = " + sum);
}
}
In addition to those great comments, you should probably only increment "i" if you get a VALID input:
while(i <= 10) {
System.out.print("Enter number " + "#" +i + ": ");
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum += userChoiceNumber;
i++;
}else{
System.out.println("Invalid Input");
sc.next();
}
}
Note that when you have a bad input you need to get rid of it with "sc.next()".
First - make sure you're formatted correctly.
(I've indented your loops, moved your output into the main class, fixed up some curly brackets/loop endings).
public static void main(String[] args) {
int i = 1, sum = 0;
Scanner sc = new Scanner(System.in);
while(i <= 10){
i++;
System.out.println("Enter number " + "#" +i);
boolean isValidNumber = sc.hasNextInt();
if(isValidNumber){
int userChoiceNumber = sc.nextInt();
sum += userChoiceNumber;
}
else{
System.out.println("Invalid Input");
}
}
System.out.println("The sum of your entered numbers are = " + sum);
}
Alright - so running the code, I've found there are the correct amount of times asked, but the input prompt is displaying the wrong number with the first input prompt starting on 2, the last one on 11.
The reason for this is the i++ runs before asking for an input, thus it counts up before outputting.
This can easily be fixed by moving said i++ to just underneath the else clause - as follows:
else{
System.out.println("Invalid Input");
}
i++
}
the main problem here is that you're increasing the variable at the start of your while loop. If that's what you're looking for then that's fine, but if you want to stop the loop when it hits 10 you'll need to have it like while(i < 10) if the i++ were at the end of the loop, then you could do while(i <= 10)
Ex:
i = 0;
while(i < 10){
i++;
//code here
}
this will make the code that uses i use the values between 1 and 10. using <= will use the values between 1 and 11.
another example:
i = 0;
while(i < 10){
//code here
i++;
}
this will make the code that uses i use the values between 0 and 9. using <= will use the values between 0 and 10.
another way people do an incremental loop is doing a for loop rather than a while loop
this would look like:
for(int i = 0; i < 10; i++){
//code here
}
this also allows you to create a variable that will only be inside the loop, so rather than making it at the beginning of the method or before the loop, you could make it inside the for loop. This is not good if the variable is used elsewhere though.

JAVA: if statement inside a for loop and exiting from a for loop

Good day guys, I am new in this. I am doing an assignment for my prog unit, so please bear with me.
So what I have to do is to write up a code that can input people's ages, from integers between 1 to 120 inclusive. The user then have to calculate the average age, and should be calculated as a real number. But the user has to input age values until the user enters 0, which is to stop the program then output the average. If the user enters an age that is invalid, then the program should continue to re-prompt the user until they enter a valid age.
So I did my part. I created a code and I come up with this:
public static void main(String[] args)
{
int ageValue = 0;
double getAge;
getAge = inputAge();
System.out.println("Average age is: " + getAge);
}
public static double inputAge()
{
int ageValue = 0;
double avgAge = 0;
Scanner sc = new Scanner(System.in);
for (int i = 1; i <= 120; i++)
{
System.out.println("Enter age");
ageValue += sc.nextInt();
avgAge = ageValue / (double) i;
if (ageValue == 0)
{
System.out.println("Average age is: " + avgAge);
System.exit(0);
}
while (ageValue < 0 || ageValue > 120)
{
System.out.println("Invalid input. Try again!");
ageValue = sc.nextInt();
}
}
return avgAge;
}
Now I laid down my code and I got my average formula somehow working. Now, the problem is that when I press 0, it doesn't prompt the "if" statement. However, when the first "Enter your age" prompt comes up and I pressed 0, the "if" statement worked. But for each iteration, the program won't let me execute the statement.
On the other hand, I am also struggling to figure out how to exit a loop without using break or System.exit() because that will give me zero marks. What I wanted is when I press 0, it should exit the loop and output the average, like what the task said.
I don't know if you guys can get it.. Is the code right? Am I on the right track? Am I missing something???
Cheers
You could consider a do while loop approach. This would allow your code to naturally run once, and exit once the user enters 0:
int ageValue = 0, numOfAges = 0, sumOfAges = 0;
do {
System.out.println("Enter age");
ageValue = sc.nextInt();
if (ageValue < 0 || ageValue > 120)
System.out.println("Bad value... try again");
else if (ageValue != 0) {
sumOfAges += ageValue;
numOfAges++;
}
} while (ageValue != 0);
return ((double)sumOfAges / numOfAges);
On the other hand, I am also struggling to figure out how to exit a loop without using break or System.exit() because that will give me zero marks.
You can have another condition in your for loop like this
boolean finished = false;
for (int i = 1; i <= 120 && finished == false; i++)
and replace
System.exit(0)
with
finished = true;
However, I would question why using "break" will score you zero marks. This is exactly the sort of scenario break was intended for.
you can try this approach.
i've corrected a bit the exit condition and the way averaging is done.
the "for" loop you show in your code is limiting the number of sample to 120, but the question don't say so, so i took the liberty to generalise you question to any number of sample to average.
first thing is you should look up "if-else" conditionnal structure, as that was the main point missing in your code.
https://en.wikipedia.org/wiki/Conditional_(computer_programming)
you can think the way the problem is expressed as :
calculate the average in a serie
the serie is keyboard inputted
when zero is inputted, exit the loop and return the current average
when any value out of bound [0,120] is inputted, give a message and continue the loop without changing anything to the serie
when any value inside the bound [1,119] is inputted add the value to the serie and recalculate the average
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println("Final Average age is: "+inputAge());
}
private static double inputAge()
{
int ageValue=0;
double avgAge=0;
boolean shouldExit=false;
Scanner sc=new Scanner(System.in);
List<Integer> samples=new ArrayList<Integer>();
// loop until flag is true
while(!shouldExit)
{
System.out.println("Enter age");
ageValue=sc.nextInt();
if(ageValue==0)
{
shouldExit=true;
}
else if(ageValue<0||ageValue>120)
{
System.out.println("Invalid input. Try again!");
}
else
{
// add current input in the samples and calculate average over all the samples
samples.add(ageValue);
avgAge=getAvg(samples);
System.out.println("Current Average age is: "+avgAge);
}
}
sc.close();
return avgAge;
}
private static double getAvg(List<Integer> samples)
{
double avgAge=0;
for(Integer tmp:samples)
{
avgAge+=tmp;
}
return avgAge/(double) samples.size();
}
}

How can I reset a variable in a loop in Java?

I am writing a number-guessing game for my Computer Science 1100 class, one part of which is to print the number of attempts the player takes at guessing the target number. I've defined a variable tries to track that; the program increments it by one every time the player makes a guess.
The game restarts after the player guesses the number correctly, and at that point I want to reset the tries counter. I can't figure out how to do that, however, because the program increments tries each time the number is guessed. How can I do it?
import java.util.Scanner;
import java.util.Random;
public class Q2 {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
Random r = new Random();
System.out.println("Welcome to the Number Guessing Game");
int x=0;//defining x for later
int tries = 1;//defining tries for later
while (x!=-1) {
int y = r.nextInt(101);//defining random number 0-100
System.out.print("Guess a number between 0 and 100 or enter -1 to quit: ");
x=kbd.nextInt();//redefining x
x=kbd.nextInt();//redefining x
for (int i=1;x!=-1&&x!=y;i=1) {//for loop
if (x<-1||x>100) {//illegal condition
System.out.print("Out of bounds. Try again: ");
}
else if (x>y) {//input greater than random condition
System.out.print("The number is lower. Try again: ");
}
else if (y>x) {//random greater than input condition
System.out.print("The number is higher. Try again: ");
}
x = kbd.nextInt();//redefining x
tries+=i;//defining pattern for tries
}
if (x==y) {//input=random condition
System.out.println("Congratulations! You guessed the number in " + tries + " tries");
}
}
if (x==-1) {//quit condition
System.out.print("Thank you for playing the game!!");
}
}
}
a) Change the scope of your variable
Variables are only available in the scope they are defined in. For example
while (something) { // all code inside the loop is in an inner scope
int variable = 42;
// variable is accessible here
}
// variable is not accessible here
This means, every time the while-loop performs one iteration, variable is newly created. It is a good practice to only define variables in the scope they actually have a meaning (in this case in the while-loop).
b) Assign the variable every time anew
Another way would be to reset the variable each time it is necessary. This would result in such a design:
int variable; // variable is defined outside the inner scope
while (something) {
variable = 42;
// some code that changes variable's value
}
One possible solution would be to encapsulate your guessing game into it's own method, which will re-initialize all variables when called, and create an if condition inside of your loop if the guess is correct.
private static void guessingGame() {
Scanner scanner = new Scanner(System.in);
double randomNum = Math.random();
double tries = 0, guess = 0;
do while (!(guess == randomNum) {
System.in("What is your guess? ");
guess = scanner.nextDouble();
tries++;
if (guess == randomNum) {
System.out.println("Guessed correctly in " + tries + " tries.");
tries = 0;
}
}
}
public static void main() {
guessingGame();
}

Creating a loop to check array (java)

Homework assignment Suggestions only please as I wish very much to learn this as second nature!
The goal is to create an array with a user specified question amount (array size) followed by an answer key (said array size now filled). Then to have the user input the "students" answers to check against key.
I wrote all that no worries. Works lovely. The issue I am having is in two areas:
Create a loop that asks to grade another quiz.
Have it only check/score/calculate every other answer. ie: even answers only.
I have used a do/while loop to continue checking but couldn't get a sentinel value to stick. Also depending on where I placed it, the answers kept coming up as the first check. So I am unsure as to where to place and how to write it. I even tried to use a for loop boxing in the array and student answer portion to no avail.
As regards to having it check every other one, I thought of modifying the count of "i" to something like ((i+1)*2) instead of i++ for the two for loops but I just get errors as that seems to not be proper at all.
Thank you in advance!
import java.util.Scanner;
import java.text.NumberFormat;
public class EvenQuizzes {
public static void main(String[] args) {
int quizQuest = 0, count = 0;
double percentTotal = 0.0;
Scanner scan = new Scanner(System.in);
System.out.print("How many questions are in the quiz? Or enter 0 to quit. ");
quizQuest = scan.nextInt();
int[] answers = new int[quizQuest]; // scan in question total and apply
// to array
System.out.println("Enter the answer key: ");
for (int i = 0; i < answers.length; i++) {
answers[i] = scan.nextInt();
}
for (int i = 0; i < answers.length; i++) {
System.out.println("Enter the answer to be graded : ");
int toGrade = scan.nextInt();
if (toGrade == answers[i]) {
count++;
}
}
percentTotal = ((double) count / quizQuest);
NumberFormat defaultFormat = NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(2);
System.out.println("The questions answered correctly total: " + count);
System.out.println("The percentage correct is: " + defaultFormat.format(percentTotal));
System.out.println("\nAnother quiz to be graded?");
}
}
// do ( quizQuest != 0){ //condition check to run new quiz against KEY
// for (int j = 0; (quizQuest = scan.nextInt()) != 0; j++); {
At the bottom is what I had considered for the loop portion I am having trouble with.
As you asked for hints (and not the code), here it is:
For more than one quizzes, use do-while, as follows:
do{
//do something
//scan the value of quiz quest
//do something
}while(quizquest != 0)
Now, if only answers at even positions are to be checked, do following:
for (int i =0; i <answers.length; i++)
{
System.out.println("Enter the answer to be graded : ");
int toGrade = scan.nextInt();
if(i % 2 == 0 && toGrade == answers[i]){
count++ ;
}
}
Create a loop that asks to grade another quiz: You could use a do-while loop with a boolean indicating if the user (teacher?) wants to grade another quiz:
do{
boolean continue = false;
// check if the user wants to continue
while(continue);
Have it only check/score/calculate every other answer. ie: even answers only: You can check for even answers with the modulo operator:
if(i % 2 == 0){
// even answer
}
Hope this helps!
You should have a variable, perhaps named continue, whose default value is 'Y'. At the very beginning, create a while loop that checks the condition continue==Y, and at the end when you ask "Another quiz to be graded?", read in the input to the variable continue.

Categories

Resources