Java program high-low game - java

I wrote this in jQuery however the loop isn't right and I can't see my error? It doesn't end when a user inputs -99? Nor calculate the highest and lowest figure?
import java.util.Scanner;
public class LargestandSmallest
{
public static void main (String [] args)
{
//Create a Scanner object for the keyboard input
Scanner keyboard = new Scanner(System.in);
//Declare local variable
double number;
//Explain what the program does
System.out.println ("This program will ask you to enter in a series of");
System.out.println ("numbers, and then will display the lowest and");
System.out.println ("highest numbers, out of what you enter, until you input");
System.out.println ("the value indicated to end the program.");
//Have the user input a series of numbers and continue processing
//until the user enters -99
System.out.println ("Please enter a number: (or -99 to end the program).");
number = keyboard.nextDouble();
//Display the table headings
System.out.println ("Lowest\tHighest");
System.out.println ("------------------");
//Call the method to caluclate the highest and lowest numbers
calculateLowHigh(number);
}
//Module called calculateTemp
public static void calculateLowHigh(double number)
{
//Declare local calculation variables
double highestNumber = 0;
double lowestNumber = 0;
//Set the parameters for running the loop
while (number != -99)
{
for(number = 0; number < 5; number++)
{
//Calculate the lowest and highest numbers entered
if (number > highestNumber) {
highestNumber = number;
}
if (number < lowestNumber) {
lowestNumber = number;
}
}
}
//Display the results
System.out.println (lowestNumber + "\t\t" + highestNumber);
}
}

Your problem is that in calculateLowHigh, you're using the number variable for two different things. It's the parameter in which the number that the user typed is passed into this method; but you've also used it as the loop index inside the for loop. Maybe you should use a different variable for one or the other purpose. Better still, dispense with the for loop altogether - it doesn't seem to do anything.
Also, the while loop should be done in main, not in calculateHighLow, otherwise the user will only ever have the opportunity to input a number once.

Related

For loop to get user input lets you enter two values for the first question, but only calculates one value

I created a small program that asks the user for 10 random numbers and it will print the sum of those numbers. I embedded it with a for loop and included a counter. Everything seems to be working fine except when I run the program, the first question allows me to enter two values, but it will still only calculate a total of 10 numbers.
Below is what I currently have and I need to understand what is going wrong when it prompts the user for the number the first time:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int counter = 0;
for (int i = 0; i < 10; i++) {
counter++;
System.out.println("Enter number #" + counter + " :");
int numberInput = scanner.nextInt();
boolean hasNextInt = scanner.hasNextInt();
if (hasNextInt) {
sum += numberInput;
} else {
System.out.println("Invalid Number");
}
}
scanner.nextLine(); // handle the next line character (enter key)
System.out.println("The sum is " + sum);
scanner.close();
}
}
In each loop, you're calling scanner.nextInt() and scanner.hasNextInt(). But you do not use the result of hasNextInt() in a meaningful way (you might have noticed that your "Invalid Number" output is not what happens if you enter something that's not a number).
The first call to nextInt() blocks until you enter a number. Then hasNextInt() will block again because the number has already been read, and you're asking whether there will be a new one. This next number is read from System.in, but you're not actually using it in this iteration (you merely asked whether it's there). Then in the next iterations, nextInt() will not block because the scanner already pulled a number from System.in and can return it immediately, so all the subsequent prompts you see actually wait for input on hasNextInt().
This amounts to 11 total input events: The firts nextInt() plus all 10 hasNextInt()s
Scanner scanner = new Scanner(System.in);
int sum = 0;
int counter = 0;
for (int i = 0; i < 10; i++) {
counter++;
System.out.println("Enter number #" + counter + " :");
int numberInput = scanner.nextInt();
// boolean hasNextInt = scanner.hasNextInt();
//if (hasNextInt) {
sum += numberInput;
// } else {
// System.out.println("Invalid Number");
//}
}
scanner.nextLine(); // handle the next line character (enter key)
System.out.println("The sum is " + sum);
scanner.close();
Don't call hasnextInt() it has no use here.
It has taken 11 inputs rather than 10.
If you remove this condition it will take 10 inputs and work fine.
Your condition have no impact on it.

How do I make my program repeat according to certain circumstances?

import java.util.Scanner;
public class MyFirstGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter A Number: ");
double s = scanner.nextDouble();
double randomNumber = Math.random();
double realNumber = randomNumber*10;
double realerNumber = Math.round(realNumber);
System.out.println(realerNumber);
if(s==realerNumber) {
System.out.println("You Win!");
} else {
System.out.println("Try Again...");
}
}
}
So what I am trying to do is make a "game" for my Java class. I have generate a random number between 1 and 10 and the user has to input a number and if the input and the random number are the same, they "win." If they lose, they try again...? First, I did all the necessary scanner stuff that I don't even fully understand. I just copied the professor. So the program says to enter a number and the program generates a number between 0.0 and 1.0. I multiply that number by 10 to make it between 1 and 10. Then I round the number to the nearest integer. If the input matches this number, the program says you win. If not, it'll say try again.
The problem is how do I make the program repeat itself without the user having to reboot the program with the cmd? I need to repeat the input, random number generator, and then the result. What do I need to do? Also, how is my program? My second big one...yeah right...big. But seriously, how can I make it less complex or anything to improve it. Thanks.
Use a while loop:
long realerNumber = Math.round(realNumber);
// first guess
long guess = scanner.nextLong();
while (guess != realerNumber) {
System.out.println("Try Again...");
// guess again
guess = scanner.nextInt();
}
System.out.println("You Win!");
There is already a class to generate random numbers, you could use it:
// TODO: move to constant
int MAX = 10;
// nextInt(int n) generates a number in the range [0, n)
int randomNumber = new Random().nextInt(MAX + 1)
just put your code inside the do-while loop
Scanner scanner = new Scanner(System.in);
do
{
System.out.println("Please Enter A Number: ");
double s = scanner.nextDouble();
double realerNumber = Math.round( Math.random() * 10 );
System.out.println(realerNumber);
if(s==realerNumber) {
System.out.println("You Win!");
} else {
System.out.println("Try Again...");
}
}
while(someCondition);
the someCondition can be for example a counter (if you want to play n times just set counter to n and decrease it every loop iteration then check if it is 0 in while) or some function checking if a key is pressed (like escape)
int n = 5;
do
{
n--;
...
}
while(n > 0);
This will run forever, but it's the idea mentioned in the first comment
...
Scanner scanner = new Scanner(System.in);
while(true){ // add this after Scanner ... declaration
...
} // end of existing else block
} // end of while loop, so add this single brace
...

Averaging User Input, looping input until negative number is entered

import java.util.*;
public class Average {
public static void main(String[] args) {
int count = 0;
int amtOfNums = 0;
int input = 0;
System.out.println("Enter a series of numbers. Enter a negative number to quit.");
Scanner scan = new Scanner(System.in);
int next = scan.nextInt();
while ((input = scan.nextInt()) > 0) {
count += input;
amtOfNums++;
}
System.out.println("You entered " + amtOfNums + " numbers averaging " + (count/amtOfNums) + ".");
}
}
This is supposed to be a Java program that takes integers from the user until a negative integer is entered, then prints the average of the numbers entered (not counting the negative number). This code is not counting the first number I enter. I'm not sure what I'm doing wrong.
Comment out your first input (outside the loop), you called it next.
// int next = scan.nextInt();
That takes one input, and does not add it to count or add one to amtOfNums. But you don't need it.

What is causing my dice game to show an unrealistic amount of perfect rolls

I am trying to create a die rolling program. The goal is to roll a die until the chosen value comes up a certain number of consecutive times (I used the programmer defined name "rollLength" for this). I am trying to display how many total rolls it took until the die value comes up consecutively. The problem is when I run the program it shows that the rollLength came up perfectly with no wasted rolls which I know is unrealistic. My question is if you can suggest what is wrong with my code. I am not sure if I am doing nested loops wrong.
Here is my code.
package lab03_schultz;
import java.util.Scanner;
import java.util.Random;
public class Lab03_Schultz {
public static void main(String[] args) {
// WRITE main's CODE HERE
Scanner keyboard = new Scanner(System.in);
Random randomNumber = new Random();
//declare variables
int value, nSides, rollLength, roll;
int turns=0, n=0, count=0, totalThrows=0;
//ask for input
System.out.println("Please enter the number of sides (2, 4, or 6): ");
nSides = keyboard.nextInt();
System.out.println("Enter the value sought. Must be in the range [1," + nSides + "]: ");
value = keyboard.nextInt();
System.out.println("Enter the length of the run.\n" + "Remember, the bigger it is the longer it will take to find it");
rollLength = keyboard.nextInt();
System.out.println("Enter number of times to run the experiment:");
turns = keyboard.nextInt();
while(n!=value) {
roll = randomNumber.nextInt(nSides)+1;
n++;
}
while(count!=rollLength){ //countinue till count = rollLength
if(n==value){
count++; //count how many times n == value, this is to represent consective rolls for the value
} else if (n!=value) { //if n is not the value counter starts over at zero
count=0;
}
if (n!=value) {//This will count how many times the die didn't come up with the value
totalThrows++;
}
}
System.out.println("totalThrows: " + totalThrows); //finding what totalThrows is
//adds rolls (without watched value) and (when it showed watch value) together
System.out.println("Your total throws are: " + (totalThrows+rollLength));
}
}
This can be done with just a single loop
int rollsInARow = 0; // store how many times we roll the value
int totalThrows = 0;
while(rollsInARow != rollLength) {
int roll = randomNumber.nextInt(nSides)+1;
if(roll == value) {
rollsInARow++; // Count consecutive rolls that are the wanted value
} else {
rollsInARow = 0; // Reset if we get a roll other than value
}
totalThrows++; // +1 after each roll
}
We loop until we have the wanted rollLength. Each loop generates a random number and compares it to value. If they are equal, increment the counter. If different, reset the counter. At the end of each loop, keep track of total rolls.
Also a tip. When using an if statement to check a true/false value (n == value), you can simply use an else statement to catch the n != value because there are only two cases.
if(n == value) {
count++;
} else { // The same functionality as else if(n != value)
count = 0;
}
Your first while loop will run until n is equal to the value. It will not move past that block of code until n is equal to value.

java program that finds average with average method

I have a program that will average your numbers from the command line. Everything is in the main method.
1. The program should run allowing you to enter one number at a time and when you press enter it asks you for another number or offers the ability to press Q to get your average.
2. The program has a limit set to 20 numbers added. When you hit 21 the program notifies you that you added to many numbers and shuts down.
3. If you enter multiple numbers on the same line and press enter, for every number you enter it System.out.println a message once for every number instead of just once.
I would like to understand how to change the program to do these things.
How to get the System.out.println to only appear one time per entry.
How to get the program to output the average of 20 before it ends when someone enters 21
how do i change it to create a method for averaging outside of main then call on the averaging method inside the main.
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double sum = 0;
int count = 0;
System.out.println ("Enter your numbers to be averaged:");
String inputs = scan.nextLine();
while (!inputs.contains("q")) {
Scanner scan2 = new Scanner(inputs); // create a new scanner out of our single line of input
while(scan2.hasNextDouble()) {
sum += scan2.nextDouble();
count += 1;
System.out.println("Please enter another number or press Q for your average");
}
if(count == 21)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
inputs = scan.nextLine();
}
System.out.println("Your average is: " + (sum/count));
}
1.
scan2.hasNextDouble()
is parsing the line which contains multiple entries so it must be removed in the while loop. You can parse yourself using string tokenize and print the message only once.
2 . Simply add this line:
System.out.println("Your average is: " + (sum/count));
before returning in if condition to print the average before quitting.
3 . that really depends on what kind of function would you like. May be you can create a function that takes an array of numbers and prints out their average or maybe you want something else.
one possible function:
public double findAverage(ArrayList<Integer> numbers){
int sum=0;
for (Integer i: numbers){
sum+=i;
}
return sum/(double)numbers.size();
}
You can try with the following:
public static void main(String[] args){
if(args.length==20)
{
int sum=0;
sum += Integer.parseInt(args[0]); //do this for 20 array elements using loop
// do required calculation
}
else //print error message
}

Categories