Number Generator with User Input - java

Ok, I have wrote this RandomNumberGenerator.java class and I am getting an error. Logically it looks like it would work but it is not. I need to have a random number between the two input's that the user input's. Would someone take a look at my code and see where I am going wrong. Here is my code:
import java.util.*;
public class NumberGenerator
{
// Begin
public static void main(String[] args){
Scanner input;
int max, min, range;
Random gen;
public static int genRandom(int mod){
Random r = new Random();
}
input = new Scanner(System.in);
System.out.println("Please enter a max value: ");
max = input.nextInt();
// Ask user to input max value
System.out.println(" Please enter a minimum value: ");
min = input.nextInt();
// Ask user to input min value
range = Math.abs(r.nextInt()) % (max - min + 1) + min;
// Get random integer between min and max values using %
System.out.println(" Your generated number is: " + range );
}
}

Your code structure is incorrect. The getRandom(..) method is defined inside your main method. You also have scoping issues (you're defining the 'r' variable inside one method and attempting to use it in another).
Try starting small and concentrate on getting your indentation right, then these kinds of errors will become more apparent.

Following Code Will Work. Basically you have a non final method inside main method.
import java.util.Random;
import java.util.Scanner;
public class NumberGenerator {
// Begin
static Random r = new Random();
public static void main(String[] args) {
Scanner input;
int max, min, range;
Random gen;
input = new Scanner(System.in);
System.out.println("Please enter a max value: ");
max = input.nextInt(); // Ask user to input max value
System.out.println(" Please enter a minimum value: ");
min = input.nextInt(); // Ask user to input min value
range = Math.abs(r.nextInt()) % (max - min + 1) + min;
// Get random integer between min and max values using %
System.out.println(" Your generated number is: " + range);
}
}

Your method,
public static int genRandom(int mod){
Random r = new Random();
}
is inside of your main method. You can't declare one method inside of another just like that. You should declare it outside of your main method. Also, you've declared it to return an int, which means you actually have to make it return an int or it won't compile. So do it like this:
public static int genRandom(int mod){
Random r = new Random();
return r.nextInt(); // Add this line to return an int.
}
public static void main(String[] args) {
...
// Call getRandom() in here where appropriate
}
NOTE
The gist of this answer is to help you understand why your code isn't compiling. Even if you get your code to compile, it still probably won't behave correctly. The other answers give you good solutions to make it work correctly.

You declare an object:
Random gen;
Then you create a method called genRandom(int mod) which instantiates a new Random object 'r'. Which is INSIDE your main method. Which isn't correct.
Then when you go to call a method to get a random number you choose to use 'r' which is not in the scope of the statement.
Developers don't let developers code recklessly.
Now I'ma need to take your keyboard.

try this
public class RandomRange {
public static void main(String[] args) {
int min = 50;
int max = 100;
for (int i = 0; i < 10; i++) {
int rnd = (int) ((Math.random() * (max + 1 - min))) + min;
System.out.println(rnd);
}
}
}

Related

so ive been working on this code and i think it might need nested methods but idk [duplicate]

I'm creating a program that generates 100 random integers between 0 and 9 and displays the count for each number. I'm using an array of ten integers, counts, to store the number of 0s, 1s, ..., 9s.)
When I compile the program I get the error:
RandomNumbers.java:9: error: method generateNumbers in class RandomNumbers cannot be applied to given types;
generateNumbers();
required: int[]
found:generateNumbers();
reason: actual and formal argument lists differ in length
I get this error for the lines of code that I call the methods generateNumbers() and displayCounts() in the main method.
public class RandomNumbers {
public static void main(String[] args) {
//declares array for random numbers
int[] numbers = new int [99];
//calls the generateNumbers method
generateNumbers();
//calls the displayCounts method
displayCounts();
}
//*****************************************************************
private static int generateNumbers(int[] numbers){
for(int i = 0; i < 100; i++){
int randomNumber;
randomNumber = (int)(Math.random() *10);
numbers[i] = randomNumber;
return randomNumber;
}
}
//*****************************************************************
private static void displayCounts(int[] numbers){
int[] frequency = new int[10];
for(int i = 0, size = numbers.length; i < size; i++ ){
System.out.println((i) + " counts = " + frequency[i]);
}
}//end of displayCounts
}//end of class
generateNumbers() expects a parameter and you aren't passing one in!
generateNumbers() also returns after it has set the first random number - seems to be some confusion about what it is trying to do.
call generateNumbers(numbers);, your generateNumbers(); expects int[] as an argument ans you were passing none, thus the error
The generateNumbers(int[] numbers) function definition has arguments (int[] numbers)that expects an array of integers. However, in the main, generateNumbers(); doesn't have any arguments.
To resolve it, simply add an array of numbers to the arguments while calling thegenerateNumbers() function in the main.
I think you want something like this. The formatting is off, but it should give the essential information you want.
import java.util.Scanner;
public class BookstoreCredit
{
public static void computeDiscount(String name, double gpa)
{
double credits;
credits = gpa * 10;
System.out.println(name + " your GPA is " +
gpa + " so your credit is $" + credits);
}
public static void main (String args[])
{
String studentName;
double gradeAverage;
Scanner inputDevice = new Scanner(System.in);
System.out.println("Enter Student name: ");
studentName = inputDevice.nextLine();
System.out.println("Enter student GPA: ");
gradeAverage = inputDevice.nextDouble();
computeDiscount(studentName, gradeAverage);
}
}
pass the array as a parameter when call the function, like
(generateNumbers(parameter),displayCounts(parameter))
If you get this error with Dagger Android dependency injection, first just try and clean and rebuild project. If that doesn't work, maybe delete the project .gradle cache. Sometimes Dagger just fails to generate the needed factory classes on changes.
public class RandomNumbers {
public static void main(String[] args) {
//declares array for random numbers
int[] numbers = new int [100];
//calls the generateNumbers method
generateNumbers(numbers); //passing the empty array
//calls the displayCounts method
displayCounts(numbers); //passing the array filled with random numbers
}
//*****************************************************************
private static void generateNumbers(int[] numbers){
for(int i = 0; i < 100; i++){
int randomNumber;
randomNumber = (int)(Math.random() *10);
numbers[i] = randomNumber;
} // here the function doesn't need to return.Since array is non primitive data type the changes done in the function automatically gets save in original array.
}
//*****************************************************************
private static void displayCounts(int[] numbers){
int count;
for(int i = 0, size = 10; i < size; i++ ){
count=0;
for(int j = 0; j < numbers.length ; j++ ){
if(i == numbers[j])
count++; //counts each occurence of digits ranging from 0 to 9
}
System.out.println((i) + " counts = " + count);
}
}//end of displayCounts
}//end of class

Take Average of an Array using Recursion

I'm trying to create a program that will take a user input, input that data into an dynamic array, and then recursively finds the average. The first part of my code works. This allows the newly created array to be passed to the method.
public static void main(String args[])
{
int i = 0;
int sum = 0;
double runningTotal = 0;
int classSize;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the class size: ");
classSize = keyboard.nextInt();
int newClassSize[] = new int[classSize];
for (i=0; i < newClassSize.length; i++)
{
System.out.println("Please enter the grade of the user at: " + (i + 1));
newClassSize[i] = keyboard.nextInt();
}
findAverage();
for (i=0; i < newClassSize.length; i++){
sum = sum + newClassSize[i];
}
System.out.println(Arrays.toString(newClassSize));
keyboard.close();
}
}
This is where I'm getting confused and confusing myself however. How would I pass the newly created array to the findAverage() method? I would then need to also have that be saved to an accumulator and then devided. Is there a better way to do this? This is my current findAverage() method but I'm confusing myself on my implementation.
public double findAverage(int classAverage, int baseCase, double runningAverage)
{
runningAverage = 0;
int sum = 0;
if (newClassSize.length - 1 > baseCase)
runningAverage = newClassSize.length;
return findAverage();
System.out.println("The class average is " + classAverage);
}
Hopefully I understood your question correctly but heres how to do it below.
The basic idea is that when the index reaches the length of the array in the
recursive function that's the base case. So all you have to do is add to the sum at each index point in the array, and just keep passing in the updated index and sum into the recursive function.
class Main {
public static void main(String[] args) {
int newClassSize[] = {1,2,3}; // User Input let say
double average = findAverage(newClassSize);
System.out.println(average);
}
public static double findAverage(int[] arr){
// Avoid division by zero error
if (arr.length==0){
return 0;
}
return findAverageHelper(arr,0,0);
}
public static double findAverageHelper(int[] arr, int index,int sum){
if (index==arr.length){ // Base Case
return (double) sum/arr.length;
}
// Increase index and add current value at index to sum
return findAverageHelper(arr,index+1,sum+=arr[index]);
}
}

Find Average using Array of Objects/Object Array

this is such a simple problem but for some reason, I cant wrap my head around Array of Objects or Object Arrays. All I have to do is take in 5 user inputs, and create a class called Height, create object array and store user inputs into obj array and print the average. I'm kinda stuck.
class Height{
int total=0;
int count=0;
public Height(int y) {
total=total+y;
count++;
}
public void print() {
System.out.print("The average is: "+total/count);
}
}
public class ObjectArray {
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter 5 heights in inches: ");
int[] x=new int[5];
int total=0;
for(int i=0;i<x.length;i++) {
x[i]=s.nextInt();
}
Height[] h=new Height[x.length];
for(int y=0;y<x.length;y++) {
h[y]=new Height(x[y]);
}
h.print();
}
}
Maybe I'm over complicating it. The problem right now is that I cannot invoke h.print();. I've tried different iterations, ex: taking out the print method and doing all the printing after every iteration.
Your approach is wrong. Your Height class appears to be responsible for the evaluation of the mean value. Hence, you should put all values inside a single Height instance, instead of generating a new instance for each user value.
However, h is an array of Heights object, while print() method is defined on a single Height instance. In order to call such method, you have to access one of the objects contained in h, that is h[0].print().
I'm assuming that your goal is simply to print the average of all the heights recieved via user input.
Your code in your main method is a tad confusing, so correct me if I'm wrong in any of the examples I give here. You should, instead of creating the x[] array, simply add the user input for the five values to Height.total in a for loop, and increase the Height.count variable by one each loop through. This should look something like this:
for (int i = 1; i <= 5; i++) {
// System.out.println("Please enter the next height: ");
Height.total += s.nextDouble();
Height.count++;
}
Then, you can run Height.print();.
I would also recommend adding a System.out.print(""); command to let the user know that they should enter the next value. That's the comment I left in the example code I gave above.
You have to design your Height in a way that match your requirement :
you need different Height with for each one a value
you need to know how many instances there is
For that, you need a private value, and a static counter :
class Height {
private int value = 0;
private static int count = 0; // static => nb of instances
public Height(int y) {
value = y;
count++;
}
public static int averageOf(Height... heights) {
return Arrays.stream(heights).mapToInt(h -> h.value).sum() / count;
}
}
To get the average, because it doesn't depend on a particular instance, you can have a static method, that sums all the value of the Height given and divide by the nb of instance
And use like :
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int nb = 5;
System.out.println("Enter " + nb + " heights in inches: ");
Height[] heights = new Height[nb];
for (int i = 0; i < heights.length; i++) {
heights[i] = new Height(Integer.parseInt(s.nextLine()));
}
System.out.println("Average is " + Height.averageOf(heights));
}

I am getting a Cannot find symbol error that I can't resolve

I am getting this error that to me looks like I am not calling the method correctly. I have reviewed the past answers here but none have specifically addressed my problem as far as I can see. This is for a class project. I realize my math in the method is most likely not correct yet but I need to get the rest working then deal with an incorrect out put. Thanks a lot!
Here is my code:
import java.util.*;
public class PrintOutNumbersInReverse {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Gather Number
System.out.print("Enter a number between 2 and 10 digits long ");
int num = console.nextInt();
System.out.println("your number is: " + num);
// call method
System.out.println("Your number in reverse is: " + reverse);
}
public static int reverse(int num, int rNum) {
rNum = 0;
while (num != 0) {
rNum = rNum + num % 10;
num = num / 10;
}
}
}
And My error Message:
PrintOutNumbersInReverse.java:28: error: cannot find symbol
System.out.println ("Your number in reverse is: " +reverse);
^ symbol: variable reverse location: class PrintOutNumbersInReverse 1 error
Change method implementation to:
public static int reverse (int num)
{
int rNum = 0;
...
return rNum;
}
and place, that is calling this method to:
System.out.println ("Your number in reverse is: " +reverse(num));
Then should be fine
When copy pasting this into eclipse, i noticed 2 things:
1.) your reverse() method doesn't return an int, but it should because the signature of the method says so: public static int reverse(int num, int rNum). Maybe return rNum, or whatever the logic behind it might be?
2.) second, you have not declared any reverse variable in the main method. Maybe you wanted a parameterized call of reverse()?
Also it looks like, you want in the reverse() method rNum to be an output parameter. In java you can't pass primitives by reference, so whatever you do with rNum inside the method, the changes will only be present in the scope of the method. So you might want to calculate something and actually return the results of your calculations.
You need to use reverse as a method, and not a variable. Also, you are passing in a variable that is not used: rNum. You see in reverse(int num, int rNum); right after you start, it sets your rNum to 0. So why pass a number in that will get set to zero?
I did this from my phone, but this should be working code:
import java.util.*;
public class PrintOutNumbersInReverse {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Gather Number
System.out.print("Enter a number between 2 and 10 digits long ");
int num = console.nextInt();
System.out.println("your number is: " + num);
// call method
System.out.println("Your number in reverse is: " + reverse(num)); //<-- notice how this is a method cause it has "()"
}
public static int reverse(int num) { //<-- this has "int num" in the "()". This is a parameter.
int rNum = 0;
while (num != 0) {
rNum = rNum + num % 10;
num = num / 10;
}
}
}

Having errors with Java assignment

I'm getting some errors in code I wrote for an assignment, and I can't quite understand them.
I:\Java Programming\FibonacciJDialog.java:19: error: variable sum might not have been initialized
return sum;
^
I:\Java Programming\FibonacciJDialog.java:20: error: unreachable statement
JOptionPane.showMessageDialog(null,"That Fibonacci Number is" ); // Display results in dialog box.
^
I:\Java Programming\FibonacciJDialog.java:25: error: missing return statement
}
^
3 errors
Tool completed with exit code 1
Here is the code:
import javax.swing.JOptionPane;
public class FibonacciJDialog {
public static long main(String[] args) {
String num;
int n;
int sum;
num = JOptionPane.showInputDialog("Enter n: "); // getting user number input.
n = Integer.parseInt(num);
Fibonacci box = new Fibonacci(); // Creating new Fibonacci object.
JOptionPane.showMessageDialog(null, "That Fibonacci Number is"); // Display results in dialog box.
return sum;
System.exit(0); // Terminate
}
}
This is the Fibonacci class I made.
public class Fibonacci {
int Fib(int n) {
int in1 = 1, in2 = 1;
int sum = 0;//initial value
int index = 1;
while (index < n) {
// sum=the sum of 2 values;
// in1 gets in2
// in2 gets sum
// increment index
}
return sum;
}
}
You never assign a value to sum.
sum = box.fib(n);
In your main function, you also return the value instead of outputting it to the console.
JOptionPane.showMessageDialog(null,"That Fibonacci Number is" + sum);
A few errors I've noticed:
You don't assign sum a value. It's only declared, but not initialized. That's what the stack trace tells you - you have to initialize the value to something.
I'm willing to bet that the "unreachable code" is a red herring - after you initialize your variable I don't see any code path that won't take you to newing your Fibonacci class.
For some reason, you've decided to return long from main(). I'm not sure how that's working - you may have some other main method somewhere else that calls this class - but you can either return a long, or set the signature of the method to void.

Categories

Resources