Need to update a variable inside a while loop - java

I am trying to define a main method that asks the user for an input (x). If the value is >= 0, it asks for another input (y). But if the value was < 0 the player has three chances to enter a correct value, otherwise he exits the game. This is what I have until now:
Scanner keyboard = new Scanner(System.in);
final int NUMBER_OF_TRIES = 3;
boolean correctNumber = false;
int attemptNumber = 0;
int x = keyboard.nextInt();
keyboard.nextLine();;
while (x < 0)
{
System.out.println("Must not be negative.");
System.out.print("Initial x: ");
int x = keyboard.nextInt(); keyboard.nextLine();
if (x >= 0)
{
correctNumber = true;
}
else
{
System.out.println("Incorrect answer");
attemptNumber++;
}
if(x < 0 && attemptNumber == NUMBER_OF_TRIES)
{
System.out.println("Too many errors. Exiting.");
break;
}
But as I already defined 'x', I cannot do it again inside the loop. I think my problem is really simple but I cannot figure out a way to fix that. Does anyone know how?

It looks like this might work if you just remove "int " from line 12. You don't need to declare the variable there since you have already declared it.

If the condition to exit the loop is to enter a negative value 3 times, then use that as the actual condition. Code should be easier to read as well.
incorrectAttempts = 0;
while (incorrectAttempts < 3)
{
get new value
value invalid?
yes: incorrectAttempts = incorrectAttempts + 1;
no: do anything else;
}

Related

A loop doesn't work properly

import java.util.*;
public class GuessNumber{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
int x = 0;
String num = "65854"; // This is the secret code
String s;
System.out.println("This program asks you to guess the code of 5 digits. ");
System.out.println("You have 5 attempts. ");
for(int i=0; i<5; i++){
do{
s = in.nextLine();
for(int c=0; c<s.length(); c++){
if(s.charAt(c)==num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x
x++;
}
System.out.println("Number of correct digits in right position: " + x); // here the execution goes out of bounds
}
while(!s.equals(num));
System.out.println("Congrats! You guessed the secret code. ");
System.exit(0);
}
}
}
I tried to create a simple java program which should allow user to guess a prefixed code of five digits (with only five attempts). The do-while loop shows correct values only for the first two attempts, then it goes out of bounds (shows values>5, which are impossible for a code of only 5 digits). Can somebody explain why?
Remove your do-while loop. It will run till user guesses right code.
Insert following code to check length of string
if(s.length()!=5){
System.out.println("code should be of length 5");
continue;
}
You can add more restrictions for no characters in input string.
Also reset x at start of outer loop every time.
Also check if input string is correct in every outer loop
if(s.equals(num)){
System.out.println("Congrats! You guessed the secret code. ");
System.exit(0);
}
this code is gonna run for EVER since you enter the true code , because you have do-while that its condition say !s.equals(num) , so you must remove the do-while at first , it is not neccessary , when your predicted code is equal to the num then the variable x must equal to 5 , so you terminate your program using a return statement after the printing success. be aware of the value of x , it must be equal to zero at each iteration , i mean x=0!
for(int i=0; i<5; i++){
s = in.nextLine();
if(s.length!=5){
System.out.println("code should be of length 5");
continue;
}
x = 0;
for(int c=0; c<5; c++){
if(s.charAt(c)==num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x
x++;
}
System.out.println("Number of correct digits in right position: " + x); // here the execution goes out of bounds
if(x==5){
System.out.println("Congrats! You guessed the secret code. ");
return;
}
}
System.out.println("Sryy !! :((");
Current Code -
for (int i = 0; i < 5; i++) {
do {
s = in.nextLine();
for (int c = 0; c < s.length(); c++) { // the length of s can exceed 5 as of **num = "65854"**
if (s.charAt(c) == num.charAt(c)) //if digit in 's' equals the digit in the same position in 'num', increment variable x
x++;
System.out.println("Number of correct digits in right position: " + x);
}
}
while (!s.equals(num)); // this ensures currently N number of attempts NOT JUST 5 as stated otherwise.
System.out.println("Congrats! You guessed the secret code. ");
System.exit(0); // with this line the for loop would execute just once
}
Suggested Code -
String s;
int count = 0;
int x;
do {
x = 0;
if (count >= 5) { break; } // 5 attempts
s = in.nextLine();
String formattedNumber = String.format("%05d",
Integer.parseInt(s)); // make sure the input is of 5 digit integer (padding here with 0's)
for (int c = 0; c < formattedNumber.length(); c++) {
if (formattedNumber.charAt(c) == num.charAt(c)) {
x++;
}
if (x == 5) { // correct guess if all chars are equal
System.out.println("Congrats! You guessed the secret code.");
break; // break if guessed correct
} else {
System.out.println("Number of correct digits in right position: " + x);
}
}
count++; //next attempt
} while (!s.equals(num)); //input not equals the desired, next attempt

Adding values to array without overwriting

Using a simple Java array called int score[], I wish to store in the array
the int 1 or 0.
The ints are supplied from a simple math question and an if statement, that allows a 1 to be added to the array if a correct answer is given, or a 0 if the answer is incorrect.
There are only 5 math questions to try, with 1 point/ 0 point (or int 1/0) for each correct answer, so its a fixed array of size[4].
I am using a for loop, but the durn thing keeps filling the array with 1's if i use <= score.Length() method.
I just wish to add an int 1 or 0 to score[4] without overwriting the previous element, each time the user answers a question.
if( playerTotal < computerTotal || playerTotal > computerTotal) {
System.out.printf("\n" + "Sorry, thats incorrect...try again__");
for(int i = 0; i <= score.length ;++i ) {
score[i] = 0 ;
System.out.print( " | ");
System.out.print( score[i]);
}
} else {
System.out.print( playerTotal + " is correct, very well done!");
// in.close();
for(int i = 0; i <= score.length ; i++ ) {
score[i] = 1 ;
System.out.print( " | ");
System.out.print( score[i]);
}
}
I hope to use the stored ints to move the math game (yayy!) onto the next level after 5 correct points are achieved.
You dont need a for loop if you want to set one element.
remove to for loop and write
if( playerTotal < computerTotal || playerTotal > computerTotal ) {
score[4]=0;}
else{score[4]=1;}
score[4] = ( (playerTotal < computerTotal) || (playerTotal > computerTotal)) ? 0 : 1;
As mentioned in the comments a few times, the error in your code is the loop overwriting the other values.
I do not know how you interact with the user, but I've provided an example on how you may solve this task. The do-while will ask for an answer until it is correct.
Scanner scanner = new Scanner(System.in);
String[] questions = {"What is 2-1?", "What is 2+1?", "What is 10-5?"};
int[] correctAnswer = {1,3,5};
//keep track of correct/incorrect answer with a boolean value
boolean[] score = new boolean[correctAnswer.length];
for(int i = 0; i < questions.length; i++) {
System.out.println(questions[i]);
do {
int input = scanner.nextInt();
score[i] = input == correctAnswer[i];
if(score[i])
System.out.println("Correct!");
else
System.out.println("Wrong, please try again..");
} while(!score[i]);
}
//do something with the score data
int sum = 0;
for(boolean b : score)
if(b) sum++;
System.out.println("You got " + sum + " points!");

User input and finding multiples

I'm new to java and I have an assignment asking to prompt user for a number between 2 and 10 and it is supposed to print out multiples of that number. It is also supposed to use a for loop.
I think I have the general idea with the for loop I'm just trying to figure out how to do the multiples. Any help is greatly appreciated! This is where I am so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please Enter a number between 2 and 10:");
for(int i = 2; i<= 100; i++){
System.out.println(+ i);
}
I suggest thinking about how you would go about doing the task mentally. When you're counting integers, you will add one each time (i++). When you're counting by, say threes, you will add three each time. You need to store your scanner's read value to a variable (don't try to read the scanner each time!) and adjust i++ in your loop to add the number you read from the scanner instead.
Begin with:
int step = in.nextInt();
if(step >= 2 && step <=10){
for(int i = 0; i <=100; ???){
System.out.println(+ i);
}
} else {
System.out.println("The step value was not between 2 and 10.");
}
I will leave you at this point as learning it for yourself is far more valuable than any Stack Overflow answer could ever be. If you are still stumped, I can guide you farther in the right direction.
You should ensure that the user can only enter numbers between 2 and 10, and you will need to store the input for use in your for loop. For example:
int num = 0;
Scanner in = new Scanner(System.in);
do
{
System.out.print("Please enter a number between 2 and 10:")
num = in.nextInt();
System.out.println();
} while((num < 2) || (num > 10));
Followed by your for loop.
A multiple of a number is that number times something.
So one multiple of i would be i * 13 (for example).
of course you need to get number from the Scanner "in" object
for (int i=2; i < 13; i++) {
System.out.println(" Multiple (" + i + ") = " + i*number;
}

Do while statement not accepting variable

I am trying to make a program that takes positive integers from the user and finds the maximum until the user enters a negative number. I have to use a do while loop. It won't accept the variable in the while part of the statement. I don't understand why this is, because I checked and I should have the correct amount of brackets.
Scanner in = new Scanner(System.in);
System.out.println("Enter a number: ");
do {
int currentnumber = 1;
int number = in.nextInt();
if(currentnumber < number) {
currentnumber = number;
}
if(number > currentnumber) {
currentnumber = number;
System.out.println("Max number is: " + currentnumber);
}
} while(number > 0);
Edit: Once I fixed the number issue. The program will print "Enter a number: " but when a number is entered it doesn't do anything
Scanner in = new Scanner(System.in);
System.out.println("Enter a number: ");
int number;
do{
int currentnumber = 1;
number = in.nextInt();
if(currentnumber < number){
currentnumber = number;}
if(number > currentnumber){
currentnumber = number;
System.out.println("Max number is: " + currentnumber);
}
}while(number > 0);
}
}
declare number outside of do block so that while() can access it
No, because in Java, local scopes are defined by {}(block). If you declare number inside the do block, it won't be accessible outside.
Notice that the condition (number > 0) is outside of the do block.
What can you do? You can declare number before the do-while:
int number = ...;
do {
...
} while (number > 0);
To use a variable in the conditional part of a do-while loop, the variable must have scope outside the loop--it must be defined outside the loop.
int number;
do{
int currentnumber = 1;
number = in.nextInt();
if(currentnumber < number) {
currentnumber = number;
} if(number > currentnumber) {
currentnumber = number;
System.out.println("Max number is: " + currentnumber);
}
} while(number > 0);
This is no different from any other loop.
while (number > 0) {
int number;
// do stuff
}
That loop will have obvious problems. But if we rewrite it to:
int number = 1;
while (number > 0) {
// do stuff
}
The problems are gone.
The same logic applies to your do-while loop.
You declared number inside the loop and it therefore only exists within the loop. In order to use it outside of the body of the loop (which includes the loop's conditional statement), it must be declared outside the loop.
One thing I noticed is that you are setting currentnumber in both less than and greater than cases. If you are attempting to determine the max input value then you only need to assign that value if it is greater than the current max value.
One other reason it "doesn't do anything" is likely because the number you have entered is less than the currentnumber. In that case your program doesn't output anything but goes back to accepting input.
Also consider moving the output asking the user for input within the loop. Then each iteration will re-prompt the user for input.
Scanner in = new Scanner(System.in);
int currentMax = 0;
int number = 0;
do {
System.out.println("Enter a number: ");
number = in.nextInt();
if(number > currentMax) {
currentMax = number;
System.out.println("Max number is: " + currentMax);
}
} while(number > 0);

not a statement error, illegal start of type

import java.util.*;
public class ulang {
public static void main(final String[] args) {
int a;
int b;
int sum;
Scanner scan = new Scanner(System.in);
System.out.println("Enter num 1: ");
a = in.nextLine();
System.out.println("Enter num 2: ");
b = in.nextLine();
{
sum = a + b;
}
for (i = 0; i < 5; i++) {
(sum >= 10)
System.out.println("Congratulations");
else
System.out.println("Sum of the number is Less than 10");
}
}
}
I'm weak on looping especially in Java. So I need some corrections on my coding, but I have no idea how to fix it.
The coding should run like this: User need to insert 2 numbers and the program will calculate the sum of both number. After that, the program will determine if the total of sum is >=10 or <10. If the sum >=10, "Congratulations" will appear but if it is <10, then "The sum of number less than 10" will appear. How to fix it?
This is the immediate problem:
(sum>=10)
I believe you meant that to be an if statement:
if (sum>=10)
Additionally:
You're trying to use an in variable, but the Scanner variable is called scan
Scanner.nextLine() returns a String - I suspect you wanted Scanner.nextInt()
Your for loop uses a variable that hasn't been declared. You probably meant:
for (int i = 0; i < 5; i++)
A few other suggestions though:
The sum isn't going to change between the loop iterations... why are you looping at all?
You've got a new block in which you're calculating the sum, but for no obvious reason. Why?
It's generally a good idea to declare variables at the point of initialization, e.g.
Scanner scan = new Scanner(System.in);
System.out.println("Enter num 1: ");
int a = scan.nextInt();
System.out.println("Enter num 2: ");
int b = scan.nextInt();
int sum = a + b;
Given that you want to take the same basic action (writing a message to the screen) whether or not the user was successful, you might consider using the conditional operator like this:
String message = sum >= 10 ? "Congratulations"
: "Sum of the number is Less than 10";
System.out.println(message);
That would then allow you to refactor the loop to only evaluate the condition once:
String message = sum >= 10 ? "Congratulations"
: "Sum of the number is Less than 10";
for (int i = 0; i < 5; i++)
{
System.out.println(message);
}
(sum>=10)
This line needs an if at the beginning, or it won't be read as a branch.
if (sum >= 10)
You also should name your main-class Ulang, because java class identifiers should start with an upper case letter, for readability.
The loop should look like the following:
for (int i = 0; i < 5; i++) {
The first part defines the counter and assigns zero to it. The second is your condition and the last counts for you.
for (int i = 0; i < 5; i++) {
if (sum >= 10)
System.out.println("Congratulations");
else
System.out.println("Sum of the number is Less than 10");
}

Categories

Resources