How to add 2 For-Each Loops to the below code? - java

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);
}
}

Related

Return several arrays from an method

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.

How to check for a certain value and then exchange to money values in Java?

I was playing around with arrays and I wanted to create a program in which you enter the value of money and then check how many coins or bank notes you need to fill that value.
In case you enter 650 you should get one for: 500 one for 100 and one for 50.
That's the program I got so far, but somehow it only prints out all of the values stored in bankovci array.
public static void main(String[] args) {
int[]bills = {500,200,100,50,20,10,5,2,1};
int amount=Integer.parseInt(JOptionPane.showInputDialog("Vnesi znesek: "));
int sum=0;
System.out.print("We will need bills for: ");
while(sum<=amount)
{
for(int i=0; i < bills.length; i++)
{
if(amount-bills[i]>=0)
{
sum+=bills[i];
}
else if(amount-sum>bills[i])
{
i+=1;
}System.out.print(bills[i]+", ");
}
}}}
Edit
In case I enter 650 or any other number I get the following output:
We will need bills for: 500, 200, 100, 50, 20, 10, 5, 2, 1,
There are cleaner ways of solving this problem (without using the break keyword), as I am sure other people will post. But to help you understand where you had trouble, here is a modified version of the code that you supplied. Notice that I changed the if statement, and removed the else block. I also had to add a break to exit the for loop early, which is what I think you were trying to use the i+1 for.
public static void main(String[] args) {
int[]bills = {500,200,100,50,20,10,5,2,1};
int amount=250;
int sum=0;
System.out.print("We will need bills for: ");
while(sum<amount)
{
for(int i=0; i < bills.length; i++)
{
if(sum+bills[i] <= amount)
{
sum+=bills[i];
System.out.print(bills[i]+", ");
break;
}
}
}}
Try this algorithm:
int[] numbers = new int[bills.length];
int total = amount;
for (int i = 0; i < bills.length; i++) {
numbers[i] = total / bills[i]; // Will perform integer division
total = total % bills[i]; // equivalent to total -= numbers[i]*bills[i];
}
It will work as long as bills is a decreasing array (starting with the highest avalable note).
numbers will contain the number of notes of the i-th bank note value.
Use this
public static void main(String[] args) {
List<Integer> availNote = new ArrayList<Integer>();
availNote.addAll(Arrays.asList(500,200,100,50,20,10,5,2,1));
System.out.println(availNote);
Scanner in = new Scanner(System.in);
int znesek=Integer.parseInt(in.next());
System.out.print("Potrebovali bi bankovce za: " );
List<Integer> splitedAmount = new ArrayList<Integer>();
while(znesek != 0){
for(int i=0; i < availNote.size(); i++)
{
if(znesek >= availNote.get(i) ){
splitedAmount.add(availNote.get(i));
znesek = znesek - availNote.get(i);
}
}
}
System.out.println(splitedAmount);
}
There is a logical mistake i will show you:
amount - bill[0] >=0? -> 650 - 500 >= 0? : yes , sum = 500 print: "500, "
amount - bill[1] >=0? -> 650 - 200 >= 0? : yes , sum = 700 print: "200, "
etc...
you should change your for loop to:
for(int i = 0; i < bills.length;) {
if(amount >= bills[i]) {
system.out.print(bills[i] +", ");
amount -= bills[i];
}
else {
i++;
}
}
i think this should do it :D
Edit:
You should remove the
while(sum<=amount)
when you try my suggestion

Summing two arrays by element, issue with carrying the 1

So I've gotten these two arrays to add properly when there is no need to carry anything. so a[0,1,1] + b[0,1,1] will give me c[0,0,2,2], but if I similarly do a[0,9,9] + b[0,9,9] I only get c[0, 0, 8, 8]. The loop in method addBigInts doesn't seem to work the way I thought it would. Any thoughts are appreciated.
import java.util.*;
public class AddBigInts {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
//init firstNum array
int[] firstNum = new int[getDigit()];
System.out.println("First number:");
//gets input to pop array
firstNum = getInt(firstNum);
//second array is same length
int[] secondNum = new int[firstNum.length];
System.out.println("Second number:");
//pop second array
secondNum = getInt(secondNum);
System.out.println(Arrays.toString(firstNum));
System.out.println(Arrays.toString(secondNum));
addBigInts(firstNum, secondNum);
}
//creates array that is one place bigger than entered #
public static int getDigit (){
Scanner console = new Scanner(System.in);
System.out.print("How many digits? ");
int arraySize = console.nextInt();
return arraySize + 1;
}
//populates array
public static int[] getInt (int[] num){
Scanner console = new Scanner(System.in);
for (int i=num.length-1; i>0; i--){
System.out.print("Digit " + i + ": ");
num[i] = console.nextInt();
}
return num;
}
//adds both arrays by index into the sum array
public static int[] addBigInts (int[]numArray1, int[] numArray2){
int count = Math.max(numArray1.length, numArray2.length);
int[] sum = new int[count+1];
//starting at numArray1 & 2 index, sums ints
for (int i=count-1; i>=0; i--){
//sum has to be +1 for numArray1 & 2 indexes
sum[i+1] = numArray1[i] + numArray2[i];
if (sum[i+1]>9){
//this line below doesn't seem to execute
sum[i]++;
sum[i+1] = sum[i+1] - 10;
}
else;
}
System.out.println(Arrays.toString(sum));
return sum;
}
}
You have:
sum[i+1] = numArray1[i] + numArray2[i];
You need:
sum[i+1] += numArray1[i] + numArray2[i];
By assigning instead of adding you are overwriting the carried 1 from the previous digit.
In your add bigints function, try change store the addition into a temp variable and use that in the if statement
int temp = numArray1[i] + numArray2[i]
if( temp > 9)

java array assignment - use of numeric literal

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

Better minimum and maximum algorithm using an array in Java

I was trying to write a simple max and min method, as I wrote it I just cant help feeling it shouldn’t be this complicated….maybe Im wrong?
My maximum code works like this, excuse my poor pseudo code:
Fill an array with 10 random numbers.
Create a max variable initialised to 0, because 0 is the lowest max.
Compare each element against the max
If the element is greater then max, replace the value of max with the element in question
I don’t like the fact I have to initialise max to 0, I feel there might be a better way then this?
My min code works similar except I:
Compare my min is lower then the array element.
If the element is lower replace min.
What I really don’t like about this is I have to initialise my min to the maximum random number, in this case 50.
My questions are:
Is there a better way to do this?
Is there a more efficient way to write this code?
import java.util.Random;
public class Main {
public static void main(String[] args) {
//Declare min and max
int max=0;
int min;
//Array of 10 spaces
int[] ar=new int[10];
//fill an array with random numbers between 0 and 50
for(int i=0;i<10;i++)
{
ar[i]=new Random().nextInt(50);
}
//Test max algorithm
//loop trough elements in array
for(int i=0;i<10;i++)
{
//max is set to 0, there should always be a maximum of 0
//If there isnt 0 will be the maximum
//If element is greater then max
//replace max with that element
if(ar[i]>max)
{
max=ar[i];
}
}
System.out.println("The max is "+ max);
//Test min
//Initialising min to maximum Random number possible?
min=50;
for(int i=0;i<10;i++)
{
if(ar[i]<min){
min=ar[i];
}
}
System.out.println("The min is "+min);
}
}
You can always grab the first element of the array (i.e. numbers[0]) as the initial value and start the loop from the second element.
int[] numbers = new int[10];
int max, min;
...
min = max = numbers[0];
for(int i = 1; i < numbers.length; ++i) {
min = Math.min(min, numbers[i]);
max = Math.max(max, numbers[i]);
}
Ok, while others were already posting answers, I have taken the time to edit your code into something I think would be more usable.
Make static methods. Those can be reused.
Use an ellipsis (...) because you then can either call the methods on array arguments like in your code, but also with a variable number of arguments as min(5,3,8,4,1).
Initialize with the smallest/biggest possible number the data type provides
To check that your code works, you have to print out the items in the array first, since when you don't know what's in it, there's no way to tell the result is correct.
Base your code on the existing methods in the standard library because these are known to be thoroughly tested and work efficiently (I know, min/max looks like a too trivial example).
I wouldn't bother too much about performance unless you really can show there is a performance problem in your code. Priority should be more like 1st correctness, 2nd readability/maintainability, 3rd performance.
Most of this has been already mentioned by others, but anyway, here's the code:
import java.util.Random;
public class MinMax {
public static int min(int... args) {
int m = Integer.MAX_VALUE;
for (int a : args) {
m = Math.min(m, a);
}
return m;
}
public static int max(int... args) {
int m = Integer.MIN_VALUE;
for (int a : args) {
m = Math.max(m, a);
}
return m;
}
public static void main(String[] args) {
// fill an array with random numbers between 0 and 50
int[] ar = new int[10];
for (int i = 0; i < 10; i++)
{
ar[i] = new Random().nextInt(50);
System.out.println(ar[i]);
}
int maxValue = max(ar);
int minValue = min(ar);
System.out.println("The max is " + maxValue);
System.out.println("The min is " + minValue);
}
}
Few tips:
Initialize min with first element and start from the second:
int min = ar[0];
for(int i=1;i<10;i++)
...or start from:
int min = Integer.MAX_VALUE;
this approach is better if you expect your array can be empty.
Use Math.min to avoid explicit condition (some may say it's slower though):
for(int i=0;i<10;i++)
{
min = Math.min(min, ar[i]);
}
Initialize max to 0 & min to 50 won't work when the numbers change. A more appropriate way is:
1. initialize them to the first element of the array.
2. Use length instead of a constant.
max = ar[0];
for(i=0;i<ar.length; i++)
{
if(ar[i]>max)
{
max=ar[i];
}
}
Same for min:
min = ar[0];
for(i=0;i<ar.length; i++)
{
if(ar[i]<min)
{
min=ar[i];
}
}
public static void main(String[] args) {
int[] myArray = {9, 7,9, -40, -10, 40};
//int[] myArray = {};
//int[] myArray = {4};
System.out.println("Difference between max and min = "
+ findDifference(myArray));
}
// Find difference between Max and Min values for a given array
public static int findDifference(int[] arr) {
if (arr.length == 0) {
// Log
System.out.println("Input Array is empty");
return Integer.MIN_VALUE;
}
int min = arr[0];
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min)
min = arr[i];
else if (arr[i] > max)
max = arr[i];
// Just to check if logic works fine
System.out.println("Min=" + min + " Max=" + max);
}
return max - min;
}
import java.io.*;
public class MultiDimensionalArrayIO {
public static void main(String[] args)throws IOException {
BufferedReader c= new BufferedReader (new InputStreamReader (System.in) );
System.out.print ( "Enter Number Column : " );
int column = Integer.parseInt(c.readLine());
System.out.print ( "Enter Number Row : " );
int row = Integer.parseInt(c.readLine());
int array [][] = new int [column][row];
int max = array [0][0];
int min = array [0][0];
int sum= 0;
for ( int i=0 ; i < array.length; i++){
for (int j=0 ; j<array[i].length; j++){
System.out.print("Enter Array Values ["+i+"]["+j+"]: " );
array[i][j]= Integer.parseInt (c.readLine());
min = Math.min(min , array[i][j]);
max = Math.max(max , array[i][j]);
sum += array[i][j];
}
}
System.out.println("The Min Number :"+ min);
System.out.println("The Max Number :"+ max+ " total is "+ sum);
}
}
Depending on whether you'd want the max and min-functions in the same method you also have to consider the return type.
So far most suggestions have kept the two separate, meaning it's fine to return an int. However, if you put the max and min-functions into a findLargestDifference-method you'd have to return a long seeing as the largest difference between any given numbers in the int array can be the size of 2 ints. You'd also getting rid of having to loop over the int array twice.
Furthermore I recommend writing unit tests for corner and edge cases instead of printing in a main-method. It helps test your logic early on when implementing it and thus often makes the code cleaner.
See example code below.
public class LargestDifference {
public static long find(int[] numbers) {
if (numbers == null || numbers.length == 0) {
throw new IllegalArgumentException("Input cannot be null or empty.");
}else {
long currentMax = numbers[0];
long currentMin = numbers[0];
for (int i=0; i < numbers.length; i++) {
if (currentMin > numbers[i]) {
currentMin = numbers[i];
}else if (currentMax < numbers[i]) {
currentMax = numbers[i];
}
}
return currentMax - currentMin;
}
}

Categories