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));
}
Related
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
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]);
}
}
My parseSentence method is supposed to take an input string and parse each individual word, giving one point for consonants and doubling the score for vowels. It needs to start at 1 point for each word and adds the scores of the individual words, not take the total overall score of all characters. It also shouldn't count spaces as characters. I am trying to make my parseSentence method process each word but it parses the first and calls it quits. It should be restarting its count at every word. Instead, it doesnt't. E.g. "as a" should be 5 points "as": 1*2(for a)+1(for s) =3 and 1*2(for the next a)=2, add them both and get 5. instead it continues from s and doubles the 3 and makes it 6.
import java.util.*;
public class WordGolf {
public static int points;
public static void main(String[] args){
System.out.println("Enter word: ");
Scanner sc = new Scanner(System.in);
String Input = sc.next();
System.out.println(parseSentence(Input));
}
public static int parseWord(String input, int start){
String charList = "aeiouyAEIOUY";
int tempPoints = 1;
points = 1;
for(int x = start; x < input.length();x++){
if(charList.indexOf(input.charAt(x)) != -1){
points *= 2;
}
else{
points++;
}
System.out.println("Test");
}
return points;
}
public static int parseSentence(String input){
int startPoint = 0;
String badList = " ";
for(int x = 0; x < input.length();x++){
if(badList.indexOf(input.charAt(x)) != -1){
startPoint = badList.indexOf(input.charAt(x)) + 1;
parseWord(input, startPoint);
}
}
return points;
}
}
You are mixing the points variable in WordSolf and the points variable in parseWord.
They should be different variables. I'd rename them to make it clear, for instance totalPoints and wordPoints.
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);
}
}
}
I am very new to java and have been trying to get my bearings with it. I've been trying to write an proof of concept employee database. It all works fine until I enter the last employee condition, then I get an ArrayIndexOutOfBoundsException. Here is the code for both of my files. Any help would be appreciated.
import java.util.Scanner;
public class EmployeeInterface
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Please enter the number of employees to register.");
int employeeCount = Input.nextInt();
Employee.setEmployeeNumber(employeeCount);
String employeeFullName;
String employeeAddress;
String employeeDateOfHire;
for(int x = 0; x <= employeeCount; x++)
{
System.out.println("Please enter the full name of employee number " + (x + 1));
Input.nextLine();
employeeFullName = Input.nextLine();
System.out.println("Please enter the address of employee number " + (x + 1));
employeeAddress = Input.nextLine();
System.out.println("Please enter the date of hire for employee " + (x + 1));
employeeDateOfHire = Input.nextLine();
Employee.employeeRegister(x, employeeFullName, employeeAddress, employeeDateOfHire);
}
}
}
Here is the second file:
public class Employee
{
private static int employeeCount;
private static String employees[][] = new String[employeeCount][4];
public static void setEmployeeNumber(int x)
{
employeeCount = x;
}
public static void employeeRegister(int employeeNumber, String employeeFullName, String address, String employeeHireDate)
{
employees[employeeNumber][0] = employeeFullName;
employees[employeeNumber][1] = employeeFullName;
employees[employeeNumber][2] = employeeFullName;
employees[employeeNumber][3] = employeeFullName;
}
}
This is the problem:
for(int x = 0; x <= employeeCount; x++)
You're using <= rather than <. So if employeeCount is 3, you'll actually ask for the details of 4 employees, and use indexes 0, 1, 2 and 3 - but 3 is an invalid index for an array of size 3.
Your setEmployeeCount method is also broken - it changes the value of employeeCount, but doesn't reinitialize the array, so you'll always end up with an array of size 0. Given that you've said the code works until the final entry, I suspect this isn't a problem in your real code, as otherwise you'd get an exception on the very first entry.
That said, I would strongly recommend that you create a rather more useful Employee type, with private instance fields for number, name etc... then create a List<Employee>. (There's probably no point in it being stored via a static field in Employee either - what if you want two employee lists?)
Additionally, an employeeHireDate should be in some appropriately chronological type - not a string. (I'd suggest using LocalDate from Joda Time as the built-in Java types for date/time types are awful.)
In addition to other answers:
private static String employees[][] = new String[employeeCount][4];
employeeCount is immediately intialized as 0 and so is the array afterwards.
You need to reintialize your array after setting employeeCount.
your loop is iterating 1 extra time. if employeeCount is 5 then loop iterates 6 times.
Try this instead
for(int x = 0; x < employeeCount; x++)
ArrayIndexOutOfBounds Exception
because you are trying to access the 1 index more which doesn't exist by using <= instead of < only
use for(int x = 0; x < employeeCount; x++)
instead of
for(int x = 0; x <= employeeCount; x++)`
Additionally to other answers:
In the method setEmployeeNumber(int x), you only change the variable employeeCount. What's missing here is to resize the array wherein you store the employees:
employees[][] = new String[employeeCount][4];