My program asks the user for a number and then validates if the number is either within the range of two randomly generated numbers or outside the range. The variable num is supposed to be the user's guess, but it keeps equating to 0. I'm uncertain if it has to do with the num = 0 in main, which is there because I get a "variable might not of been initialized" error if the = 0 is not there.
Code:
public static int getValidGuess(Scanner get)
{
int num;
System.out.print("Guess a number: --> ");
num = get.nextInt();
return num;
} // getValidGuess end
public static boolean displayGuessResults(int start, int end, int num)
{
boolean result;
Random gen = new Random();
int n1 = gen.nextInt(99) + 1;
int n2 = gen.nextInt(99) + 1;
if (n1 < n2){
start = n1;
end = n2;
} //if end
else
{
start = n2;
end = n1;
} //else end
System.out.println("\nThe 2 random numbers are " + start + " and " + end);
System.out.println("User Guess is " + num);
if(num >= start && num <= end){
result = true;
System.out.println("Good Guess!");
}
else if(num < start || num > end){
result = false;
System.out.println("Outside Range.");
}
else{
result = false;
}
return result;
} // displayGuessResults end
public static void main(String[] args) {
// start code here
int start = 0, end = 0, num = 0;
Scanner scan = new Scanner(System.in);
String doAgain = "Yes";
while (doAgain.equalsIgnoreCase("YES")) {
// call method
getValidGuess(scan);
displayGuessResults(start, end, num);
System.out.print("\nEnter YES to repeat --> ");
doAgain = scan.next();
} //end while loop
} //main end
Variables in different functions aren't magically the same just because they have the same name. If you want to be able to share variables without passing them as parameters or return values, then you need to declare them in the class instead.
Specifically, here's your two choices. Choice 1 (recommended): change getValidGuess(scan); to num = getValidGuess(scan);. Choice 2: put public static int num = 0; right in your class, outside all of your functions, and remove the declarations of num from all of your functions.
Related
i'm trying to create a program where the number that the user has input would decrease by a certain amount. something that would like this:
Update by (Increment/Decrement):decrement
Enter starting number:15
Enter update number:3
Enter end number:3
loop#1 value=15
loop#2 value=12
the end number is where the loop would stop and the update number is how much the starting number should decrement by. so far this is the code I have and I'm stuck on how to keep the loop going until the end number.
package jaba;
import java.util.Scanner;
public class loop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String Decrement = scan.nextLine();
System.out.print("Enter starting number:");
String number = scan.nextLine();
System.out.print("Enter update number:");
String upnumber = scan.nextLine();
System.out.print("Enter end number:");
String endnumber = scan.nextLine();
int i,j;
i = 15;
j = 1;
do {
System.out.println("loop#" +j+ "\tvalue="+i);
j++;
}while(i<15);
i = i-3;
System.out.println("loop#" +j+ "\tvalue="+i);
};
}
how about something like this:
public class loop {
public enum Operation {INCREMENT, DECREMENT, INVALID}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String operationString = scan.nextLine();
System.out.print("Enter starting number:");
String numberString = scan.nextLine();
System.out.print("Enter update number:");
String upnumberString = scan.nextLine();
System.out.print("Enter end number:");
String endnumberString = scan.nextLine();
// Determine and parse stuff
int startNumber = Integer.parseInt(numberString);
int updateNumber = Integer.parseInt(upnumberString);
int endNumber = Integer.parseInt(endnumberString);
// Parse operation, but assume invalid operation
Operation operation = Operation.INVALID;
if (operationString.equalsIgnoreCase("increment")) {
operation = Operation.INCREMENT;
} else if (operationString.equalsIgnoreCase("decrement")) {
operation = Operation.DECREMENT;
}
// now do the "meat" of the assignment
int loopNumber = 0; // we'll keep the loop number as a separate counter
switch (operation) {
case INCREMENT:
for (int i = startNumber; i < endNumber; i = i + updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i);
}
break;
case DECREMENT:
for (int i = startNumber; i > endNumber; i = i - updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i)
}
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
}
private static void performAssignmentPrinting(int loopNumber, int value) {
System.out.println("loop#" + loopNumber + "\tvalue=" + value);
}
}
or the do/while version:
// now do the "meat" of the assignment
int currentNumber = startNumber;
int loopNumber = 0; // we'll keep the loop number as a separate counter
do {
loopNumber++;
switch (operation) {
case INCREMENT:
currentNumber += updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case DECREMENT:
currentNumber -= updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
} while (currentNumber != endNumber);
you have i = i-3; out of loop.
Move decrementation of i into loop:
do {
System.out.println("loop#" + j + "\tvalue=" + i);
j++;
i = i - 3;
} while (i > endnumber);
For loop is the solution for your program. for(a ; b ; c) {...}
Google how a for loop works. And try to understand how the 3 parts a,b,c works.
Pseudo:
// if decrease mode
// for (i = upperbound ; i >= lowerbound ; i-= decrement)
// print i
// if increase mode
// for (i = lowerbound ; i <= upperbound ; i+= increment)
// print i
Update: This is sufficient to get you started and add more validation on your journey.
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rnd = (int)(Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for (int count = 1; count <= 7; count++) {
while (num != rnd) {
if (num < rnd) {
System.out.println("Your guess is too low.");
}
if (num > rnd) {
System.out.println("Your guess is too high.");
}
if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2)) {
System.out.println("But your guess is VERY close.");
}
num = scan.nextInt();
}
System.out.println("You got it right!");
}
System.out.println("You should guess it in 7 tries.");
}
}
So I used two loops and just nested them. Is that how it works for this? Right now the code is like starting with for loop and if that is true it goes to the while loop part where the guessing number takes place. Can this be fixed with just moving some codes and fixing minor areas around?
What you should do in a situation like this is do the code manually. Literally. Grab a piece of paper and pretend you're a computer. It's a good exercise, and it will help you figure out your problem.
The problem is your inner loop. It loops until they guess correctly regardless of the number of attempts. Then you force them to do it 6 more times with the outer loop.
You really only need 1 loop. I would have a single loop like this:
int attempts = 0;
int num = 0;
do {
num = scan.nextInt();
... most of the if code from your inner loop but not another scan.nextInt
} while (++attempts < 7 && num != rnd);
// and here you look at num == rnd to see if success or failures
I think you should rebuild you code to make it more clear.
Split the title (with description of the task)
Split main loop where you read user input and check it with expected number
Split output of the final result, where you print the result.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int rnd = new Random().nextInt(101);
final int maxAttempts = 7;
System.out.println("The program is going to give a number that is between 0 and 100 (including them).");
System.out.println("You can guess it within maximum " + maxAttempts + " attempts by pressing Run.");
boolean success = false;
for (int attempt = 1; attempt <= maxAttempts && !success; attempt++) {
System.out.format("(%s of %s) Enter your number: ", attempt, maxAttempts);
int num = scan.nextInt();
if (num == rnd)
success = true;
else {
System.out.print("Your guess is too " + (num > rnd ? "high" : "low") + '.');
System.out.println(Math.abs(rnd - num) <= 2 ? " But it's VERY close." : "");
}
}
System.out.println(success ? "You got it right!" : "Bad luck this time. Buy.");
}
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int rnd = (int) (Math.random() * 101);
System.out.println("The program is going to give a number that is between 0 and 100 (including them). You can guess it by pressing Run.");
System.out.println("Enter your number:");
int num = scan.nextInt();
for(int count = 1; count <= 7; count++)
{
if (num < rnd)
{
System.out.println("Your guess is too low.");
}
else if (num > rnd)
{
System.out.println("Your guess is too high.");
}
else if ((Math.abs(rnd - num) == 1) || (Math.abs(rnd - num) == 2))
{
System.out.println("But your guess is VERY close.");
}
else
System.out.println("You got it right!");
System.out.println("Enter Next number: ");
num = scan.nextInt();
}
}
}
It should work Fine.Basically Your reasoning wass wrong because You are putting a while loop inside a for loop. What you want to do is you want only 7 iteration.In those 7 iterations you are checking the conditions based on user Input.
My program asks the user for a number and then decides if the number is between the range of two randomly generated numbers or outside of it. Everything works fine, except the program keeps giving the result that the guessed number is outside the range, even when it is inside the range. Not sure how to get the answer to show correctly. Boolean result = true is there since a "Cannot find symbol" error appears if it is not.
Code:
public static int getValidGuess(Scanner get)
{
int num;
System.out.print("Guess a number: --> ");
num = get.nextInt();
return num;
} // getValidGuess end
public static boolean displayGuessResults(int start, int end, int num)
{
int n1, n2;
boolean result = true;
Random gen = new Random();
n1 = gen.nextInt(99) + 1;
n2 = gen.nextInt(99) + 1;
if(n1 < n2)
{
start = n1;
end = n2;
} // if end
else
{
start = n2;
end = n1;
} //else end
if(num > start && num < end){
result = true;
System.out.println("\nThe 2 random numbers are " + start +
" and " + end);
System.out.println("Good Guess!");
} //if end
if(num < start || num > end){
result = false;
System.out.println("\nThe 2 random numbers are " + start +
" and " + end);
System.out.println("Outside range.");
} //if end
return result;
} // displayGuessResults end
public static void main(String[] args) {
// start code here
int start = 0, end = 0, num = 0, input;
Scanner scan = new Scanner(System.in);
String doAgain = "Yes";
while (doAgain.equalsIgnoreCase("YES")) {
// call method
input = getValidGuess(scan);
displayGuessResults(start, end, num);
System.out.print("\nEnter YES to repeat --> ");
doAgain = scan.next();
} //end while loop
} //main end
Your displayGuessResult should be improved:
public static boolean displayGuessResults(int num) {
boolean result = true;
Random gen = new Random();
int n1 = gen.nextInt(99) + 1;
int n2 = gen.nextInt(99) + 1;
int start = Math.min(n1, n2);
int end = Math.max(n1, n2);
System.out.println("\nThe 2 random numbers are " + start + " and " + end);
if(num >= start && num <= end){
result = true;
System.out.println("Good Guess!");
} else {
result = false;
System.out.println("Outside range.");
}
return result;
} // displayGuessResults end
and you have to call it using input read from the Scanner:
input = getValidGuess(scan);
displayGuessResults(input);
I know how to display an Error message if the user enters a number below 10 or higher than 999 but how can I code to make sure the program doesn't end after the users enter a number below 10 or higher than 999 and give them a second chance to enter their valid input over and over again until they give a correct input.
import java.util.Scanner;
public class Ex1{
public static void main(String args[]){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter an integer between 10 and 999: ");
int number = input.nextInt();
int lastDigit = number % 10;
int remainingNumber = number / 10;
int secondLastDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdLastDigit = remainingNumber % 10;
int sum = lastDigit + secondLastDigit + thirdLastDigit;
if(number<10 || number>999){
System.out.println("Error!: ");
}else{
System.out.println("The sum of all digits in " +number + " is " + sum);
}
}
}
You will need to use a loop, which basically, well, loops around your code until a certain condition is met.
A simple way to do this is with a do/while loop. For the example below, I will use what's called an "infinite loop." That is, it will continue to loop forever unless something breaks it up.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start a loop that will continue until the user enters a number between 1 and 10
while (true) {
System.out.println("Please enter a number between 1 - 10:");
num = scanner.nextInt();
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
} else {
// Exit the while loop, since we have a valid number
break;
}
}
System.out.println("Number entered is " + num);
}
}
Another method, as suggested by MadProgrammer, is to use a do/while loop. For this example, I've also added some validation to ensure the user enters a valid integer, thus avoiding some Exceptions:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start the loop
do {
System.out.println("Please enter a number between 1 - 10:");
try {
// Attempt to capture the integer entered by the user. If the entry was not numeric, show
// an appropriate error message.
num = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: Please enter only numeric characters!");
num = -1;
// Skip the rest of the loop and return to the beginning
continue;
}
// We have a valid integer input; let's make sure it's within the range we wanted.
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
}
// Keep repeating this code until the user enters a number between 1 and 10
} while (num < 1 || num > 10);
System.out.println("Number entered is " + num);
}
}
Try this, i just include the while loop in your code it will work fine.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = askInput(input);
while(number<10 || number>999) {
System.out.println("Sorry Try again !");
number = askInput(input);
}
int lastDigit = number % 10;
int remainingNumber = number / 10;
int secondLastDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdLastDigit = remainingNumber % 10;
int sum = lastDigit + secondLastDigit + thirdLastDigit;
if(number<10 || number>999){
System.out.println("Error!: ");
}else{
System.out.println("The sum of all digits in " +number + " is " + sum);
}
}
private static int askInput(Scanner input) {
int number = input.nextInt();
return number;
}
I'm trying to make code that asks the user to enter 10 numbers and subtracts them all. This is what i have so far. I think i have the general layout all set but i dont know what to do with the rest
import java.util.Scanner;
public class subnumbs
{
int dial;
int[] num = new int [10];
Scanner scan = new Scanner(System.in);
public void go()
{
int q=0;
dial = 10;
while (q != 0)
{
System.out.println("type numb: ");
int newinput = scan.nextInt();
q+=newInteger;
dial = cdial + 1;
}
return q;
}
}
System.out.printIn("Enter Integer: ");
int newInteger = scan.nextLine();
While (newInteger >= 0){
System.out.println("Re-enter Integer (must be negative): ");
newInteger = scan.nextLine();
}
n+=newInteger;
Counter = counter - 1;
return n;
this is one way to ensure inly negative numbers, only count down and add it if it was negative ...
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(newInteger < 0) {
n+=newInteger;
counter -= 1;
}
else {
System.out.println("must be negative integer, please try again: ")
{
}
In general, to ensure an input you have to evaluate it at the point where you are getting the input