Create an application containing an array that stores 20 double values,
such as 2.34, 7.89, 1.34, and so on. The application should:
* Display the sum of all the array elements
* Display the average of all the array elements
* Display the largest value of all the array elements
This is a java class assignment. I got a bad grade on this one because my professor said I used a numeric literal. I lost 28 points out of 40. Did I design the solution so bad? His exact comments:
"The program you submitted uses numeric literals in place of the array’s length.
This cause several runtime errors when I change the size of your array and tested the code."
AND my solution:
import java.util.Random;
import java.util.Arrays;
public class MyArray{
public static double[] doubles;
public static void main(String args[]) {
MyArray.createDoublesArray();
MyArray.displayDoublesArray();
MyArray.displaySum();
MyArray.displayAverage();
MyArray.displayTheLargestValue();
}
/*Fill up the double Array class member*/
public static void createDoublesArray(){
doubles = new double[20];
//Create Random object
Random r=new Random();
double rangeMin = 1, rangeMax = 9;
//Generate random double number - 20 times within the range of 2 to 9
for(int i=0;i<20;i++) {
//Generate random double numbers and round them to the two decimal places
double randomdouble = Math.round((rangeMin + (rangeMax - rangeMin) * r.nextDouble())*100.0)/100.0;
doubles[i] = randomdouble;
}
}
/*Display the double Array*/
public static void displayDoublesArray(){
String delimiter;
Arrays.sort(doubles);
System.out.println("The double array: ");
// iterate through all the array elements
System.out.print("{");
for(int i=0;i<20;i++) {
if(i < 19){
delimiter = ", ";
}
else{
delimiter = "}";
}
System.out.print(doubles[i]+ delimiter);
}
System.out.println("\n");
}
/*Displays the sum of the double array.*/
public static void displaySum() {
//initialize the sum with 0
double sum = 0.0;
// iterate through all the array elements
for (int i = 0; i < doubles.length; i++) {
// add up each element to the sum variable
sum += doubles[i];
}
// display the sum
System.out.println("The sum is: " + Math.round(sum*100.0)/100.0 + "\n");
}
/*Displays the average of the double array.*/
public static void displayAverage() {
// initialize the sum with 0
double sum = 0.0;
// iterate through all the array elements
for (int i = 0; i < doubles.length; i++) {
sum += doubles[i];
}
// display the average by dividing the sum to the length of the array
System.out.println("The average is: " + Math.round((sum / doubles.length)*100.0)/100.0 + "\n");
}
/*Displays the largest value from the double array */
public static void displayTheLargestValue() {
//initialize the largest value with the first element
double largestValue = doubles[0];
//iterate through the remaining elements (ignore the first)
for (int i = 1; i < doubles.length; i++) {
// check if "i" element is greater then the current largest value
if (doubles[i] > largestValue) {
largestValue = doubles[i];
}
}
// display the largest value
System.out.println("The largest value is: " + largestValue);
}
}
I'm guessing that instead of things like the following
for(int i=0;i<20;i++)
he wanted you to use the length property
for(int i=0;i<doubles.length;i++)
additionally, here
//initialize the largest value with the first element
double largestValue = doubles[0];
you're assuming that doubles is not empty, and when it is empty, that will thrown an exception
To allow us to maintain this code easily I would 1st of all create:
private final static int SIZE = 20;
createDoublesArray:
public static void createDoublesArray(){
doubles = new double[SIZE];
//Create Random object
Random r=new Random();
double rangeMin = 1, rangeMax = 9;
//Generate random double number - 20 times within the range of 2 to 9
double randomdouble = 0.0; // <- we don't want to initiate double in 'for' loop
for(int i=0;i<SIZE;i++) {
//Generate random double numbers and round them to the two decimal places
randomdouble = Math.round((rangeMin + (rangeMax - rangeMin) * r.nextDouble())*100.0)/100.0;
doubles[i] = randomdouble;
}
}
displayDoublesArray:
/*Display the double Array*/
public static void displayDoublesArray(){
String delimiter;
Arrays.sort(doubles);
System.out.println("The double array: ");
// iterate through all the array elements
StringBuilder buff = new StringBuilder(); // use buffer
buff.append("{");
for(int i=0;i<SIZE;i++) {
if(i < SIZE-1){
delimiter = ", ";
}
else{
delimiter = "}";
}
buff.append(doubles[i]+ delimiter);
}
buff.append("\n");
System.out.println(buff.toString());
}
Our code seems a bit more generic and i can change SIZE (if needed) without actually change my code.
I agree with Maxim Shoustin...
Just one comment to add
1) It is not required to always use double. for eg.
double rangeMin = 1, rangeMax = 9; //can be replaced by int.
ref: Primitive Data Types
Related
I am a beginner at java, but I'm trying to learn.
This is my program i am working on, the user will enter some values, where the program sort all the even values of the index to be the variable radie and all the odd values of the index to be height no matter what the element is. Same goes for nominator och denominator in the next method. But now i am stuck and dont know how to return the arrayList. I want to return my new arrays so i can use them in my other methods. Like i said im very new at java but find it fun to work with but now i need your help. As you can see i have been using swedish words for the outprint, sorry for that.
import java.util.Scanner;
import java.util.ArrayList;
public class program
{
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("-------------------------------");
System.out.println("# Test av area- och volymmetod.");
System.out.println("-------------------------------");
double result1 = area1(radie);
double result2 = area2(radie, height);
double result3 = volumeCone(radie, height);
System.out.println("Radie = " + radie + "\tHeight = " + height);
System.out.printf("Basytans area:%11.2f", result1);
System.out.println();
System.out.printf("Mantelytans area:%8.2f", result2);
System.out.println();
System.out.printf("Volym:%19.2f", result3);
System.out.println();
}
public static ArrayList<Integer> readFirstInputs(int numberOfInputs)
{
System.out.println("Please enter values, Q to quit:");
int[] inputs = new int[numberOfInputs];
ArrayList<Integer> radie = new ArrayList<Integer>();
ArrayList<Integer> height = new ArrayList<Integer>();
for(int i = 0; i < inputs.length; i++)
{
inputs[i] = keyboard.nextInt();
if (i % 2 == 0)
{
radie.add(inputs[i]);
}
else if (i % 2 != 0)
{
height.add(inputs[i]);
}
}
return ????? // return radie and height array, how?
}
public static ArrayList<Integer> readSecondInputs(int numberOfInputs)
{
System.out.println("Please enter values, Q to quit:");
int[] inputs = new int[numberOfInputs];
ArrayList<Integer> nominator = new ArrayList<Integer>();
ArrayList<Integer> denominator = new ArrayList<Integer>();
for(int i = 0; i < inputs.length; i++)
{
inputs[i] = keyboard.nextInt();
if (i % 2 == 0)
{
nominator.add(inputs[i]);
}
else if (i % 2 != 0)
{
denominator.add(inputs[i]);
}
}
return ????; // return nominator and denominator array, how?
}
/* Use my different arrays in the methods below. */
public static double area1(int radie)
{
double areaBas = Math.PI * Math.pow(radie, 2);
return areaBas;
}
public static double area2(int radie, int height)
{
double areaMantel = Math.PI * radie * Math.sqrt((Math.pow(radie, 2) + Math.pow(height, 2)));
return areaMantel;
}
public static double volumeCone(int radie, int height)
{
double volume = Math.PI * Math.pow(radie, 2) * height / 3;
return volume;
}
public static int fractionToInteger(int nominator, int denominator)
{
int amount = nominator / denominator;
return amount;
}
public static int fractionToFraction(int nominator, int denominator)
{
int remainingAmount = nominator % denominator;
return remainingAmount;
}
}
Are you allowed to use a list instead? it's way more efficient since once created, you can't change the size of an array, but if you instead create two empty lists you can just use the .add method that lists have, looking similar to this:
public static List<Integer> readFirstInputs(int numberOfInputs)
{
System.out.println("Please enter values, Q to quit:");
int[] inputs = new int[numberOfInputs];
List<Integer> evens = new List<Integer>();
List<Integer> odds = new List<Integer>();
for(int i = 0; i < inputs.length; i++)
{
inputs[i] = keyboard.nextInt();
if (i % 2 == 0)
{
evens.add(inputs[i]);
}
else if (i % 2 != 0)
{
odds.add(inputs[i]);
}
}
}
of course I am a bit confused on exactly what you want to do so you are definitely gonna have to change this up a bit, I just want to use this as a basic example of how to use a list instead.
If I understand you correctly, you would like to return from the function an array of odd numbers and an array of even numbers from user input.
but you are returning only one array which is just an array of the users inputs (with no logical meaning for the conditions in the loop).
from what I know - it is not possible to return 2 arrays, but there are solutions of course. you can return a class or a dictionary, for example.
if you choose a dictionary it will be something like Dictionary<string,object>, and will have 2 items, the string will be "odd" \ "even", and the object will be the matching array of the numbers (int[] or List<int>). odd numbers array a value of "odd" key, and even numbers array a value of "even" key in the dictionary.
two problems that appear to me here other than that:
1.) you are trying to use 2 variables that are not defined or even mentioned in the function (even and odd).
2.) in each condition you wrote return. this will exit the loop and function on the first iteration.
hope this was helpfull.
I need to write a program that takes 10 floating-point numbers as inputs.
The program should display the average of the numbers followed by all of the numbers that are greater than the average.
Part of my requirements include writing a method that takes an array of doubles as a parameter and returns the average of the data in the array, and I am required to use at least 2 for-each loops in this program, and am not sure where to place them. The program works perfectly now, it just needs to have two for each loops added.
Here is what I have so far.
public class Floats {
public Floats() {
}
public static void main(String[] args) {
int count = 0, ct = 0, inc = 0, avc = 0, ac = 0, incre = 0, greaterCount = 0;
double sum = 0, average = 0, number = 0;
Scanner reader = new Scanner(System.in);
double[] array = new double[10];
double[] averageArray = new double[1];
double[] greaterArray = new double[10];
//inputs and appends to an array
while (count < array.length) {
System.out.print("Enter a number: ");
number = reader.nextInt();
array[count] = number;
sum = sum + number;
count++;
}
average = sum / count;
//counts
while (inc < array.length) {
if (array[inc] > average) {
greaterArray[inc] = array[inc];
incre++;
}
inc++;
}
//prints all numbers
System.out.println("All of the numbers entered: ");
while (avc < array.length) {
System.out.print(array[avc] + "," + " ");
avc++;
}
//average displayed
averageArray[0] = average;
System.out.println("");
System.out.println("The average of all numbers entered: ");
System.out.println(averageArray[0]);
//larger than average
System.out.println("Numbers greater than the average: ");
while (ac < inc) {
if (greaterArray[ac] != 0) {
System.out.println(greaterArray[ac]);
}
ac++;
}
}
}
Thanks for the help in advance! Let me know if you have any questions!!
I don't want to do your homework for you, but I will try to give a helpful recommendation. The Arrays.asList(array) method returns a list that can easily be used as the source of a for-each loop.
Since it was pointed out that a for-each loop can be used on an array and a collection that implements Iterable, my answer above isn't necessary. With that in mind, I'll provide some example code:
String[] array = new String[] {"Test", "String", "Array"};
for (String string : array) {
}
Print all the numbers in double[] array.
for (double d : array) {
System.out.print(d + ", ");
}
Print all the numbers in array greater than average
for (double d : array) {
if (d > average) {
System.out.println(d);
}
}
Write a method to generate and return a set of random values in an int array of a user specified size. The values should all be between +/- N, where N is a constant such as 100.
Thank you.
Here's Mine;
import java.util.*;
public class Test
{
public static void main(String[] args)
{
int limit, numbers;
Random random = new Random();
Scanner scan = new Scanner(System.in);
System.out.print ("Enter your limit value for your array: "); //Needs to be positive.
limit = scan.nextInt();
int[] list = new int[limit];
for (int i = 0; i < list.length; i++)
{
System.out.print(list[i] + ", ");
}
numbers = random.nextInt(limit - (0 - limit)) + (0 - limit);
System.out.println (numbers);
System.out.println (list[numbers]);
}
}
public List<Integer> random(int range, int count){
List<Integer> result = new ArrayList<Integer>();
for(int i=0;i<count;i++){
if(Math.random() > 0.5){
//adding positive value with probability of 0.5
result.add((int)(Math.random() * (double)range));
}else{
//adding negative value with probability of 0.5
result.add(-1 * (int)(Math.random() * (double)range));
}
}
return result;
}
If you want to create your own random number generator, the easiest one to implement will be Linear Congruential Generator. Read from wiki and try yourself. Ask here if you need help.
I wrote the code, but there is no conversion from double to int.
public class Array {
public static void main(String[] args) {
int i;
int[] ar1 = new int[100];
for(int i = 0; i < ar1.length; i++) {
ar1[i] = int(Math.random() * 100);
System.out.print(ar1[i] + " ");
}
}
}
How can it be corrected?
ar1[i] = (int)(Math.random() * 100);
Conversion in Java looks like cast in C.
It should be like
ar1[i] = (int)(Math.random() * 100);
When you cast, cast type should be in brackets e.g. (cast type)value
Try this:
package studing;
public class Array {
public static void main(String[] args) {
Random r = new Random();
int[] ar1 = new int[100];
for(int i = 0; i < ar1.length; i++) {
ar1[i] = r.nextInt(100);
System.out.print(ar1[i] + " ");
}
}
}
Why?
Using Math.random() can return 1, this means Math.random()*100 can return 100, but OP asked for maximum 99! Using nextInt(100) is exclusive 100, it can only return values from 0 to 99.
Math.random() can not return -0.000001 that would be round to 0 and 1.0000001 can not be returned that should round to 1. So you have less chance to get 0 or 99 than all the numbers between. This way it is not realy random, to guess "its not 0 or 99" is more true than "its not 1 or 98".
Also it do not make a detour via casting and mathematic operations you don't realy need, hey you dont need to strictfp on amd-cpus or old intel-cpus.
This is not actually using the java.lang.Math class, but in Java 8 a random array can also be created in this fashion:
int[] random = new Random().ints(100, 0, 100).toArray();
My solution uses Random class instead of Math.random. Here it is.
private static int[] generateArray(int min, int max) { // generate a random size array with random numbers
Random rd = new Random(); // random class will be used
int randomSize = min + rd.nextInt(max); // first decide the array size (randomly, of course)
System.out.println("Random array size: " + randomSize);
int[] array = new int[randomSize]; // create an array of that size
for (int i = 0; i < randomSize; i++) { // iterate over the created array
array[i] = min + rd.nextInt(max); // fill the cells randomly
}
return array;
}
My professor asked us to generate random variables between 0 and 0.5. I wrote this code:
public class Random_Number_Generator {
double randomGenerator() {
Random generator = new Random();
double num = generator.nextDouble() * (0.5 - 0);
return num;
}
}
But my professor is saying this code is generating random numbers not random variables. What could this mean?
Apparently I misread the post; the following should be read with that in mind.
In that code, num and generators are local variables. A random number (a value) is assigned to the variable called num using the Random object named by the generator variable. Finally, the value stored in the variable num is returned from the method.
In any case, generator.nextDouble() returns a value between [0,1) so to get a value between [0,0.5), just scale it by half: divide it by two or, as done, multiply it by a half.
The - 0 in the above code is silly, but "okay" because (0.5 - 0) == 0.5.
(Also, it is good to get into the practice of to creating one Random instance and re-using it .. although this issue is more obvious in .NET.)
Now, actual random variable is, as far as I know, a function that maps values to their probability. I don't think you're supposed to return a function, so I've scratched this: the closest thing to what I guess you're supposed to do:
import java.util.*;
import java.lang.*;
class RandomVar
{
TreeMap<Double, Integer> variables;
public RandomVar()
{
variables = new TreeMap<Double, Integer>();
int count = Main.RandGen.nextInt(15);
double probabilityLeft = 1.0;
for (int i = 0 ; i < count - 1; i++)
{
int toPut = Main.RandGen.nextInt(100);
while (variables.containsValue(toPut)) toPut = Main.RandGen.nextInt(100);
double prob = probabilityLeft * Main.RandGen.nextDouble();
variables.put(prob, toPut);
}
int toPut = Main.RandGen.nextInt(100);
while (variables.containsValue(toPut)) toPut = Main.RandGen.nextInt(100);
double prob = probabilityLeft;
variables.put(prob, toPut);
}
public int getValue()
{
double rand = Main.RandGen.nextDouble();
double sum = 0;
for (double prob : variables.keySet()) //keySet() is sorted ascending
{
if (prob >= rand)
return variables.get(prob);
}
return variables.get(variables.lastKey());
}
//Shows probabilities of values
public void test()
{
for (double key : variables.keySet())
System.out.println(key + " :: " + variables.get(key));
}
}
class Main
{
public static Random RandGen = new Random();
public static void main (String[] args)
{
RandomVar rv = new RandomVar();
rv.test();
System.out.println("------------------------------");
for (int i = 0; i < 40 ; i++)
System.out.print(rv.getValue() + ", ");
}
}
This is very lousy solution, basically a class which allows you to return values with a set (random) probability. I still don't know if this is what you professor wants though...
Try this code:
public static void main(String[] arg) {
System.out.print(Random());
}
public static double Random() {
double START = 0;
double END = 0.5;
Random random = new Random();
double token = RandomNumber(START, END, random);
return token;
}
public static double RandomNumber(double aStart, double aEnd, Random aRandom) {
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
// get the range, casting to long to avoid overflow problems
double range = aEnd - aStart;
// compute a fraction of the range, 0 <= frac < range
double fraction = (range * aRandom.nextDouble());
double randomNumber = (fraction + aStart);
return randomNumber;
}