Generating Randoms but a few minor errors - java

I did look at the threads pertaining to randoms and implemented them into this assignment but I have 2 questions.
1) I need my program to generate random numbers (and print them) and count the iterations. I have counting the iterations down but I don't know why the random numbers don't print out. Does it have something to do with my guess = 0? Here's an example if I'm not clear.
Example:
Enter a number: 13
85
89
73
94
13
This took 5 tries
2) I have no clue why my program always ends up stuck at one number for the answer. The program immediately ends after entering the number 86.
import java.util.*;
public class FeelingLucky {
public static void main (String [] args) {
Scanner sc = new Scanner (System.in);
int tries = 0;
int guess = 0;
Random random = new Random(1);
int num = random.nextInt(100) + 1;
System.out.print("Pick a number between 1 and 100:");
while (guess != num) {
guess = sc.nextInt();
tries++;
}
System.out.println("It took " + tries + " tries to match");
sc.close();
}
}

Random(1) uses seed in constructor which is always the same. Use just Random() - no parameter constructor.
import java.util.*;
public class FeelingLucky {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tries = 0;
int guess = 0;
Random random = new Random(); // No seed
int num = random.nextInt(100) + 1;
System.out.print("Pick a number between 1 and 100:");
while (guess != num) {
guess = sc.nextInt();
tries++;
}
System.out.println("It took " + tries + " tries to match");
sc.close();
}
}
See Java random always returns the same number when I set the seed?

You've called nextInt() on the Random object only once, so you've only generated the one random number. Inside your loop you call nextInt() on the scanner, which is reading from System.in, so your program is halting and waiting for the user to input a number again each time around the loop.
If you want the user to enter a single number once, and then Random to keep generating numbers until they match, you'd need to swap which one is called inside the loop. To print the random numbers being generated, you'd need to add a print statement inside the loop that prints that current number.

while (guess != num) {
num = random.nextInt(100) + 1;
guess = sc.nextInt();
System.out.printf("you guessed: %d the number was %d%n",guess, num);
tries++;
}
This one will print out each time, and guess a new random number each time.

Related

I have a problem with splitting up my Java program into separate methods within the same class, could I have some advice on how to go about it?

I was given the task of splitting my program which which allows the user to enter an array of numbers and after an odd number between 1 and 10 to check whether the odd number is a factor of each of the 5 numbers in the array. I keep on trying out different ways but none seem to work. Could someone help me out or send a sample of how I should sort it? This is the program:
import java.util.Scanner;
public class CheckboxExample{
public static void main(String args[]) {
CheckBox c = new CheckBox();
new CheckboxExample(); // links to checkbox class
Scanner s = new Scanner(System.in);
int array[] = new int[10];
System.out.println ("Please enter 10 random numbers"); // prompts the user to enter 10 numbers
int num; // declares variable num
try{
for (int i = 0; i < 10; i++) {
array[i] = s.nextInt(); // array declaration
}
}catch (Exception e){
System.out.println ("You have an error");
}
System.out.println ("Please enter an odd number between 1 and 10");
try{
num = s.nextInt ();
if (num % 2 == 0){
do{
System.out.println ("\nYour number is even, enter an odd one");
num = s.nextInt ();
}while (num % 2 == 0);
}
if (num < 0 | num > 10){
do{
System.out.println ("Your number is outside of the range, try again");
num = s.nextInt ();
}while (num < 0 | num > 10);
}
for (int i = 0; i < 5 ; i++){
if (array[i] % num == 0) {
System.out.println("Your number is a factor of " + array[i] );
}
}
}catch (Exception e){
System.out.println ("error");
}
}
}
A method should ideally be responsible for one task. In your case you should think about the different things your code try to do and organize them in a sense that each of the methods you call does one thing of the list of things you try to do.
As an example: As far as I understand your code does the following things:
Read an array of 10 values
Read an odd number
Verify the number is odd
Verify the number is in range
Calculate if the number is a factor of one of the 10 numbers in the array
Now one possible approach would be to separate your code in 5 methods that do exactly these things.
At first you call the method that reads the 10 numbers.
Then you call the method to read the odd number.
3. and 4. are actually part of reading the number, since you need to retry on an invalid input, so you could write your method for inputting the odd number in a way that it uses the methods for verifying the input.
Finally when you have all the valid input, you call the method which produces your result (ie. if the number is a factor of the numbers in the list).
A general outlier for your code could look like:
public class CheckboxExample {
public static void main(String args[]) {
CheckBox c = new CheckBox();
new CheckboxExample(); // links to checkbox class
Scanner s = new Scanner(System.in);
int array[] = readInputArray();
int number = readOddValue();
calculateFactors(array, number);
}
private int[] readInputArray() {...}
private int readOddValue() {...}
private void calculateFactors(int[] array, int number) {...}
//additional methods used by readOddValue which verify if the value is actually odd
}
Please note that this is just one way to split your code into methods and there are several ways to design and implement each of these methods.

range between the min and max value

Create a NumberInTheRange application that prompts the user for two numbers.
The first number is a min value and the second is a max value. Prompter then prompts the user for a number between the min and max numbers entered. The user should be continually prompted until a number within the range is entered. Be sure to include the min and max numbers in the prompt.
I wrote a code allowing the users to write the two min and max values. However, I am wondering what code should I write in order to fulfill the conditions above. I am thinking about using loops and it would be very helpful if you guys correct me and give some instructions on how to process these.
import java.util.Scanner;
public class NumberinTheRange {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Type two numbers:");
int n1=scan.nextInt();
int n2=scan.nextInt();
}
}
Use a do...while loop.
int num;
do {
System.out.println("Enter a number between " + n1 + " and " + n2 + ":");
num = scan.nextInt();
} while(num < n1 || num > n2);
Now, you need to put a condition to loop-back if the input is not in the range. You can use a do-while loop for the same. You can do it with any other loop but using a do-while loop guarantees that its body will be executed at least once.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Type two numbers: ");
int min = scan.nextInt();
int max = scan.nextInt();
int n;
do {
System.out.print("Enter a number in the range of " + min + "-" + max + ": ");
n = scan.nextInt();
} while (n < min || n > max);
System.out.println("Your number is: " + n);
}
}
A sample run:
Type two numbers: 10 20
Enter a number in the range of 10-20: 34
Enter a number in the range of 10-20: 5
Enter a number in the range of 10-20: 15
Your number is: 15

How can I generate different random numbers using a seed with a loop?

I'm making a simple gradebook that's supposed to generate random numbers for each assignment for each student. It generates random numbers, but the numbers are the same each loop.
Here's the code I have so far:
import java.util.Random;
import java.util.Scanner;
public class Testing {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice == "y") {
System.out.println("Please enter a number for the random number generator seed:");
//User input for seed
int seed = sc.nextInt();
//Initializing Seed
Random randomSeed = new Random(seed);
//Prompting for number of students
System.out.println("Please enter the no of students for whom you have grade information: ");
//User input for number of students
int numberOfStudents = sc.nextInt();
String homework = "HW";
System.out.printf("%16s", homework);
System.out.println("\n");
//Finding random value for Homework.
int randomHomework = randomSeed.nextInt(((600-300) + 1) + 300);
//Creates an array that has 7 rows for points
//Will eventually add more values into array
int points [][] = new int[6][3];
//for loop that starts at 1 and prints number of students user entered
for (int i = 0; i < numberOfStudents; i++) {
System.out.print("Student #" + (i + 1) + " ");
points[0][2] += randomHomework;
System.out.print(randomHomework + " ");
System.out.println("\n");
}//End of for loop
choice = sc.nextLine().toUpperCase();
}//End of while loop
}
}
I get 540 points for each student, but I should be getting a random value between 300 and 600 for each student each time it loops.
Thanks for anything!
Place your instance of Random outside the loop. What you're doing is creating a new instance of random each iteration, with the same seed. The seed determines which values are going to get generated, and with the same seed, you'll get the same numbers each time.

How to add multiple values with while statement?

I'm trying to ask user to type how many numbers will be inputted and enter the values then add all the values.
import java.util.Scanner;
public class sum {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
int counter = 1;
int values = 0;
int times;
System.out.println("How many numbers will you input?: ");
times = sc.nextInt();
while(counter == times){
System.out.println("Enter your number: ");
values = values + sc.nextInt();
counter ++;
}
System.out.println("Your sum is " + values);
}
}
Your logic for the while loop is incorrect.
while(counter == times)
will only be true if counter and times have the same value. So if you would want to input two numbers, your while loop wouldn't even get executed. What you want is for the while loop to run until counter == times. So, your logic should be
while(counter != times)
Furthermore, you should start your counter at zero, instead of one. This is because it now means that you already inputted one number, which you didn't.
Alternatively, you could use the following snippet
while (sc.hasNextInt()) {
values += sc.nextInt()
}
This simple loop will go through all the integers inputted in the command line one by one, until there is no next integer (you type for example a letter).
In that case, you don't need to ask the user how many numbers he/she will input, as you will check it yourself.

How to input a lot of data until you type in an invalid number in java

User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}

Categories

Resources