Random number (1-100) picking loop program | Understanding methods - java

what I am looking to do is create a program that will randomly pick an integer between 1 and 100. Then, ask the user to guess it. Loop until they do, and after each incorrect guess tell them if they are too high or too low. I want to use two different methods to validate their input. One to test whether it is a valid int, the other to test the range (1-100). This second will require another parameter for the high range value.
The problems I am having:
1. I do not understand why I have to enter a number multiple times before my while (guess != a) { is triggered.
Example from console :
I am thinking of a number from 1 to 100 ... guess what it is ?6
I am thinking of a number from 1 to 100 ... guess what it is ?6
I am thinking of a number from 1 to 100 ... guess what it is ?6
6
higher!
2. how could I use my check methods and have them pertain to my while guess loop?
Example from console again:
`I am thinking of a number from 1 to 100 ... guess what it is? 10001
I am thinking of a number from 1 to 100 ... guess what it is? 10001
Error! Must be less than 100
I am thinking of a number from 1 to 100 ... guess what it is? 10001
100
lower!
10001
lower!`
{What I have full written currently}
package labbs;
import java.util.Scanner;
public class Lab12 {
public static double getDoubleGreaterThan(double low, Scanner input, String prompt) {
double num;
num = getDouble(input,prompt);
if(num <= low)
System.out.println("Error! Must be greater than 1");
num = getDouble(input,prompt);
if (num > 100)
System.out.println("Error! Must be less than 100");
num = getDouble(input,prompt);
return num;
}
public static double getDouble(Scanner input, String prompt) {
boolean OK;
double val=0;
do {
System.out.print(prompt);
OK = true;
try {
val = input.nextDouble();
}
catch(Exception e) {
OK = false;
System.out.println("Error! Invalid input. Must be a double value");
input.next();
}
}while(! OK);
return val;
}
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
double output, letscheck;
int count=0, guess=0;
int a=1 + (int) (Math.random() * 99);
letscheck = getDoubleGreaterThan(-0.9, keyboard,"I am thinking of a number from 1 to 100"
+ " ... guess what it is ?");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess > a) {
System.out.println("lower!");
} else if (guess < a) {
System.out.println("higher!");
}
}
System.out.println("Congratulations. You guessed the number with "
+ count + " tries!");
}
}

1. Query: You have just missed bracket in getDoubleGreaterThan()method as after if statement block always working not on the basis of input so change your code like below:
public static double getDoubleGreaterThan(double low, Scanner input, String prompt) {
double num;
num = getDouble(input,prompt);
if(num <= low){
System.out.println("Error! Must be greater than 1");
num = getDouble(input,prompt);
}
if (num > 100){
System.out.println("Error! Must be less than 100");
num = getDouble(input,prompt);
}
return num;
}

Related

Java project: number of students that passed or fail?? Logical error

So this code asks to input either a 1 for a pass or a 2 for a fail for ten students and it shows an error if the user inputs an invalid number. The logical error in this is for example all 10 students pass,the output is supposed to be "passed: 10 Failed:0".However, if I enter an error just once by mistake the error message will appear but the output will be"passed:9 failed:0 " even thought all 10 students passed.
import javax.swing.JOptionPane;
public class pass {
public static void main(String[] args) {
int passes = 0;
int failures = 0;
int result;
for (int studentCounter = 1; studentCounter <= 10; studentCounter++) {
String input = JOptionPane.showInputDialog("Enter (1=pass, 2= fail)");
result = Integer.parseInt(input);
if (result == 1) {
passes = passes + 1;
} else if (result == 2) {
failures = failures + 1;
} else if ((result != 1) && (result != 2)) {
JOptionPane.showMessageDialog(null, "Error input 1 or 2");
}
}
JOptionPane.showMessageDialog(null, "Passed:" + passes + "Failed:" + failures);
System.exit(0);
}
}
It is right, as 9 have passed and 0 have failed. The error does not count in none of the groups.
The problem is in your if else logic:
Your For loop increments the integer in the condition else if((result!=1)&&(result!=2)) which means that for example, if you make 10 times a input other than 1 or 2, you'll get a result like 0 passes and 0 failed... but your loop is over....
I suggest you additionally to use the Oracle Java Code Conventions... failures ++; passes++;
You can have try with below code. Decrements student counter on invalid input.
import javax.swing.JOptionPane;
public class pass{
public static void main(String [] args){
int passes=0;
int failures=0;
int result;
for(int studentCounter = 1; studentCounter<=10; studentCounter++){
String input = JOptionPane.showInputDialog("Enter (1=pass, 2= fail)");
result = Integer.parseInt(input);
if(result==1){
passes++;
}else if(result==2){
failures++;
} else if((result!=1)&&(result!=2)) {
studentCounter--;
JOptionPane.showMessageDialog(null,"Error input 1 or 2");
}
}
JOptionPane.showMessageDialog(null,"Passed:"+passes+" Failed:"+failures);
System.exit(0);
}
}
You can update your code like below to remove your logical error:
import javax.swing.JOptionPane;
public class pass{
public static void main(String [] args){
int passes=0;
int failures=0;
int result;
for(int studentCounter = 1; studentCounter<=10;){
String input = JOptionPane.showInputDialog("Enter (1=pass, 2= fail)");
result = Integer.parseInt(input);
if(result==1){
passes = passes + 1;
studentCounter++
}else if(result==2){
failures = failures +1;
studentCounter++
} else {
JOptionPane.showMessageDialog(null,"Error input 1 or 2");
}
}
JOptionPane.showMessageDialog(null,"Passed:"+passes+"Failed:"+failures);
System.exit(0);
}
}
The loop is executed exactly 10 times. But if an error occurs, your code neither increases passes nor failures, and therefore passes + failures always is the amount of inputs without failures and always <= 10.
If you want to have exactly 10 results you have to make sure that there are exactly 10 correct inputs.
You can achieve this by increasing a results counter on correct inputs until it reaches 10:
int studentCounter = 0;
while(studentCounter < 10 ){
String input = JOptionPane.showInputDialog("Enter (1=pass, 2= fail)");
result = Integer.parseInt(input);
if(result==1){
passes++;
studentCounter++;
}else if(result==2){
failures++;
studentCounter++;
} else {
JOptionPane.showMessageDialog(null,"Error input 1 or 2");
}
}

Making a program with a range that can change during the course of the program (Java)

I am working on a project where you make a code that has the computer guess a random number, and then the user says if that number is higher or lower. Then the computer is supposed to change its parameters based on what the user says. For example if it guesses 33 and you say too low and it says 74 and it says too high, then the next number generated will be between 33 and 74. My problem is, I can make the range get higher with using the rFinder variable and such when UserAnswer=2 in the RepeatedGuess method. But, though trying many things, I can't get a range that is dynamic or that changes throughout the code. Am I approaching this completely the wrong way? Any suggestions would be helpful.
import java.util.Scanner;
import java.util.Random;
public class Proj72 {
private static int UserAnswer;
private static int maximum = 100;
private static int minimum = 0;
private static int rFinder;
private static Random generator = new Random();
private static Scanner reader = new Scanner(System.in);
private static int guess = generator.nextInt(100);
public static void main(String[] args) {
FirstGuess();
RepeatedGuesses();
Correct();
}
private static void FirstGuess() {
System.out.print(guess + ": Is this your number? Enter 1 For Yes or enter 2 for Too Low or enter 3 for Too High:");
}
private static void RepeatedGuesses() {
while (1 != UserAnswer) {
UserAnswer = reader.nextInt();
if (2 == UserAnswer) {
rFinder = (int)(generator.nextInt(100 - guess));
guess = rFinder + guess;
System.out.print(guess + ": Is this your number? Enter Yes or enter Higher or enter Lower:");
} else if (3 == UserAnswer)
break;
}
}
private static void Correct() {
if (1 == UserAnswer) {
System.out.print("I got it!");
}
}
}
Keep track of the range of values that the guess could be. Call these min and max. Min is equal to 0 and max is equal to 100 at the beginning.
Guess a random int between the min and max
After each guess:
if the number is above the guess, set the min to the guess
if the number is below the guess, set the max to the guess
To progress further, instead of choosing a random guess each time, guess the value in the middle of the min and max values, e.g. 50 for the first guess.
This is then a binary search with O(log(N)) worst and average time!
private static void RepeatedGuesses() {
while (1 != UserAnswer) {
UserAnswer = reader.nextInt();
if (2 == UserAnswer) {
rFinder = (int) (generator.nextInt(100 - guess));
guess = rFinder + guess;
System.out.print(guess + ": Is this your number? Enter Yes or enter Higher or enter Lower:");
} else if (3 == UserAnswer){
break;
}
//change it
FirstGuess();
UserAnswer = reader.nextInt();
}
}

Is there anyway to see if my users input is in a certain range?

I'm taking some input from the user and I need to make sure there input is between the range 200-800. For all of my variable should I just make if statements or is there a shortcut?
System.out.print("SAT Math: ");
int satMath = kb.nextInt();
System.out.print("SAT Reading: ");
int satReading = kb.nextInt();
System.out.print("SAT Writing: ");
int satWriting = kb.nextInt();
//If score is out of range.
if (((satMath < 200 || satMath > 800) || (satReading < 200 || satReading > 800) || (satWriting < 200 || satWriting > 800)))
{
System.out.println("Did not enter a value in range!");
System.exit(-1);
}
You've got the logic correct, but your implementation is a bit odd. You basically want to do the same thing for every value, so why not check the value as soon as it's entered instead of at the end, like this:
class SAT
{
private static final Scanner sc = new Scanner(System.in);
private static int getInt(final String subject)
{
System.out.println("SAT " + subject + ": ");
final int value = sc.nextInt();
if(value < 200 || value > 800)
{
System.out.println("Did not enter a value in range! (200-800)");
System.exit(-1);
}
return value;
}
public static void main(String[] args)
{
int maths = getInt("Math");
int reading = getInt("Reading");
int writing = getInt("Writing");
}
}
Use separate if statements and if input is out of range, display which input was out of range so next time user can enter correct input. No shortcut sorry!
With repeated code like that, I usually refactor it, like this:
// reusable in-range method
private static boolean between(int value, int low, int high) {
return value >= low && value <= high;
}
// reusable version for this task, because they all share the same range
private static boolean isOK(int value) {
return between(value, 200, 800);
}
then
if (!isOK(satMath) || !isOK(satReading) || !isOK(satWriting)) {
System.out.println("Did not enter a value in range!");
System.exit(-1);
}

Numberguessing class and client

I am trying to code a number guessing class and client.
The issue/problems I am having with this class/client is that my number guess either ends up too high or too low and in top of that it loops the number twice when it should once.
Number generated from 0 to 100. Wanna take a guess(enter 0 to give up)
Let's take a guess:
50
40
Your guess is too low
What possible change can I make to improve the overall loop or change.
Here is my code for anyone that wants to look at it.
import java.util.Random;
public class NumberGuess
{
private Random generator;
private int Number;
int intGuess= (1 + (int)(Math.random()*100));
int numGuess=0;
boolean isGuessCorrect=false;
public NumberGuess(){
}
int numguess;
public int guess(int guessIn){
int numguess=guessIn;
if(numguess>intGuess){
return 1;
}else if(isGuessCorrect){
return 0;
}else{
return -1;
}
}
public int getNumberofGuesses(){
return numGuess;
}
public boolean gameIsComplete(){
if(isGuessCorrect){
return true;
}else{
return false;
}
}
public void reset(){
intGuess=(1 + (int)(Math.random()*100));
numGuess=0;
isGuessCorrect=false;
}
}
Client class
import java.util.Scanner;
public class NumberGuessclient{
public static void main(String[] args){
NumberGuess game1=new NumberGuess();
Scanner scan = new Scanner(System.in);
int quit=1;
while(quit != 0) {
System.out.println("Number generated from 0 to 100. Wanna take a guess(enter 0 to give up)");
System.out.println("Let's take a guess: ");
int guess1= scan.nextInt();
while((guess1 != 0)||(!game1.gameIsComplete())) {
guess1 = scan.nextInt();
if (game1.guess(guess1)==1){
System.out.println("Your guess is too high");
}
else if(game1.guess(guess1)==-1) {
System.out.println("Your guess is too low");
}
else { System.out.println("guessed in " + game1.getNumberofGuesses() + " tries");
}
}
System.out.println("Enter 1 for new game, 0 to quit: ");
quit = scan.nextInt();
if(quit==1){
game1.reset();
}
}
}
}
source code for more ELABORATION if not clarified above.
NumberGuess Class:
The NumberGuess class will facilitate a number guessing game. The constructor should generate a random number, saving the number in a private class field. The class should also define a method which accepts a "guess", compares the "guess" to the randomly generated number, and returns one of the following:
• -1 the guess was less than the secret number
• 0 the guess matched the secret number
• 1 the guess was higher than the secret number
Determine whether other methods, constructors or otherwise, would be useful for this class.
The Java API defines a Random class for generating random numbers. The class can be reviewed in the API or in your textbook beginning on page 250. Consider limiting the range of the random number. For instance, a number between 0 and 100.
Client Application:
The client application allows the end-user to play the number guessing game. Below is a sample run. Your application does not need to match.
I'm thinking of a number between 0 and 100. Can you guess it?
Take a guess: 50
Your guess is too high
Another guess? (Y or N): y
Take a guess: 25
Your guess is too high
Another guess? (Y or N): y
Take a guess: 10
Your guess is too low
Another guess? (Y or N): y
Take a guess: 15
Your guess is too low
Another guess? (Y or N): y
Take a guess: 18
Your guess is too low
Another guess? (Y or N): y
Take a guess: 20
Congratulations! You correctly guessed the secret number in 6 tries.
There are quite a bit of things that you can change, for instance:
There's no need to call game1.guess(guess1) more than once every loop.
The completion method is quite long...
You should call scan.nextInt() before entering the while loop...
I'm assumming the last output was manually generated, because you never increment numguess
The guess(int) method doesn't work...
I'm not usually one to do homework... but (I'm having a good day...!):
import java.util.Random;
import java.util.Scanner;
public class NumberGuessclient {
private static final String[] ANS = {
"Your guess is too low\n",
"guessed in %d tries\n",
"Your guess is too high\n"
};
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
NumberGuess game = new NumberGuess();
System.out.println("Number generated from 0 to 100. Wanna take a guess(enter 0 to give up)");
System.out.println("Let's take a guess: ");
while (!game.isGameComplete()) {
System.out.format(ANS[game.guess(scan.nextInt())+1], game.getNumberofGuesses());
}
System.out.println("Enter 1 for new game, 0 to quit: ");
if (scan.nextInt() != 1) {
System.out.println("Bye!");
System.exit(0);
}
}
}
}
class NumberGuess {
private static final Random RAND_GENERATOR = new Random(System.nanoTime());
int intGuess = RAND_GENERATOR.nextInt(101);
int numGuess = 0;
boolean isGuessCorrect = false;
public int guess(int guessIn) {
numGuess++;
if (guessIn > intGuess) {
return 1;
} else if (guessIn == intGuess) {
isGuessCorrect = true;
return 0;
} else {
return -1;
}
}
public int getNumberofGuesses() {
return numGuess;
}
public boolean isGameComplete() {
return isGuessCorrect;
}
}
Now one comment: as I recall the "fun" of this game was that you should always "guess" the number in at the very most 10 tries, you could implement that...

How to find Least Common Multiple (LCM) for two numbers

I have used Euclid's method to find the L.C.M for two numbers.
l.c.m=a*b/(gcd(a,b))
How can I do this without using this algorithm?
I have an idea of first getting all factors of these two numbers and storing them in array. Then take 1 element from array 1 and search for it in array2, if it present there then remove it from there and make the result multiply by that num.
Is this OK?
Almost. What's the LCM of 4 and 8? Obviously 8 (23), but in your method you'd find 2. You need to keep track not just of all factors, but also how often they appear.
I believe the algorithm you suggest is a method using a table, check to see if it works for you.
LCM(Least Common Multiple) is always greater than or equal to the larger of the two numbers. So we will first check that the larger number itself a LCM of two numbers by checking that the larger number is divisible by the smaller one , if yes we found the LCM & If no then we will increment the larger number by 1 and check again.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the first Number : ");
int number1 = scan.nextInt();
System.out.print("Enter the second number : ");
int number2 =scan.nextInt();
int multiple;
if(number1 >= number2) {
multiple = number1;
} else {
multiple = number2;
}
Boolean loopContinue = true;
while(loopContinue) {
if(multiple % number1 == 0 && multiple % number2 == 0) {
System.out.println("LCM of Two Numbers is " + multiple);
loopContinue = false;
}
multiple++;
}
}
}
You can get LCM of two number by getting GCD at first.
Here is the solution for the above.
package com.practice.competitive.maths;
import java.util.Scanner;
public class LCMandGCD {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int testCases = scanner.nextInt();
while (testCases-- > 0) {
long number1 = scanner.nextInt();
long number2 = scanner.nextInt();
long gcd = computeGCD(number1, number2);
long lcm = computeLCM(number1, number2, gcd);
System.out.println(lcm + " " + gcd);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static long computeGCD(long number1, long number2) {
while (number1 != number2) {
if (number1 > number2)
number1 -= number2;
else
number2 -= number1;
}
return number2;
}
private static long computeLCM(long number1, long number2, long gcd) {
return (number1*number2)/gcd;
}
}

Categories

Resources