java if statement in array for loop - java

Alright so I need to add some additional functions to this array, which gives 10 random integers. It needs to be able to store the numbers that are less than 40 and print them along with the numbers that are less than the average. How do I do this with an if statement in a for loop? (Ignore the stuff that's cometted out.
public static void main(String[] args) {
Random gen= new Random();
int[] ages = new int[10];
for(int i=0; i<ages.length; i++){ //adds stuff to arrays
ages[i] = gen.nextInt(100); //Determines the maximum used in random number generation
}
for(int x=0; x<10; x++){//prints the array with the below statement
System.out.println(ages[x]);
}
System.out.println("---------------");
System.out.println(ages[9]);
System.out.println(ages[8]);
System.out.println(ages[7]);
System.out.println(ages[6]);
System.out.println(ages[5]);
System.out.println(ages[4]);
System.out.println(ages[3]);
System.out.println(ages[2]);
System.out.println(ages[1]);
System.out.println(ages[0]);
int value = (ages[0] + ages[1] + ages[2] + ages[3] + ages[4] + ages[5] + ages[6] + ages[7] + ages[8] + ages[9]);
System.out.println("The combined value of the integers is " + value + ".");
int average = (value / 10);
System.out.println("The average value of the integers is " + average + ".");
}
}

Something like that? (Sorry guys for code but i don't have a time to make it better):
public static void main(String[] args) {
Random gen= new Random();
int[] ages = new int[10];
List<Integer> agesLesserThan40 = new ArrayList();
List<Integer> agesLesserThanAverage = new ArrayList();
float value = 0;
for(int i=0; i<10; i++) {
ages[i] = gen.nextInt(100);
value += ages[i];
}
for(int x=0; x<10; x++){
if(ages[x] < value/10) agesLesserThanAverage.add(ages[x]);
if(ages[x] < 40) agesLesserThan40.add(ages[x]);
}
System.out.println("ages:");
for(int z=0; z<10; z++){System.out.print(ages[z] + ", ");}
System.out.println();
System.out.println("Lesser than 40: ");
for(int y=0; y<agesLesserThan40.size()-1; y++){System.out.print(agesLesserThan40.get(y) + ", ");}
System.out.println();
System.out.println("Lesser than average: ");
for(int y=0; y<agesLesserThanAverage.size()-1; y++){System.out.print(agesLesserThanAverage.get(y) + ", ");}
System.out.println();
System.out.println("The average value of the integers is " + value / 10 + ".");
System.out.println("The combined value of the integers is " + value + ".");
}
}

I have no idea how if (value >= 100000) says anything is less than 40...
Here is probably how you could divide your array into above and under 40.
final int AGES_TO_GENERATE = 10;
final int AGE_LIMIT = 100;
final int AGE_DIVIDER = 40;
List<Integer> lesserAge = new ArrayList<>();
List<Integer> upperAge = new ArrayList<>();
Random gen = new Random();
double averageAge = 0.0;
for(int i=0; i<AGES_TO_GENERATE; i++){
int age = gen.nextInt(AGE_LIMIT);
averageAge += age;
if (age < AGE_DIVIDER) lesserAge.add(age);
else upperAge.add(age);
}
averageAge /= AGES_TO_GENERATE;
System.out.println("Here are the values less than 40");
System.out.println(lesserAge);
if (upperAge.isEmpty()) {
System.out.println("There are no values over 40");
}
If using Java 8, you can print values less than the average very simply
lesserAge
.stream()
.filter(x -> x < averageAge)
.sorted() // Assuming you want to sort
.forEach(System.out::println);
upperAge
.stream()
.filter(x -> x < averageAge)
.sorted() // Assuming you want to sort
.forEach(System.out::println);

Related

Program to read seven integer values and print out the number of occurrences of each value

as the title suggests, i'm trying to input 7 integers and be able to output those integers along with a count for how many duplicates there were among them.
Using the code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}
for (int i = 0; i < 7; i++) {
int duplicates = 0;
for (int j = 0; j < 7; j++) {
if (userInput[i] == userInput[j])
duplicates++;
}
System.out.println("Number " + userInput[i] + " occurs " + duplicates + " times.");
}
}
with the input: 12 23 44 22 23 22 55
I keep getting duplicates in my output, like so:
Number 12 occurs 1 times.
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 22 occurs 2 times.
Number 23 occurs 2 times.
Number 22 occurs 2 times.
Number 55 occurs 1 times.
For clarity, what i'm aiming for is:
Number 12 occurs 1 times.
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 22 occurs 2 times.
Number 55 occurs 1 times
I appreciate any and all suggestions.
You can use a vector to store all occurs for each number
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}
int duplicates[] = new int[7];
for(int i = 0; i < 7; i++)
duplicates[i] = 0;
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (userInput[i] == userInput[j])
duplicates[i]++;
}
System.out.println("Number " + userInput[i] + " occurs " + duplicates[i] + " times.");
}
}
The output for the input 12 23 44 22 23 22 55 will be:
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 22 occurs 2 times.
Number 23 occurs 2 times.
Number 22 occurs 2 times.
Number 55 occurs 1 times.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : userInput) {
if (map.containsKey(i))
map.put(i, map.get(i) + 1);
else
map.put(i, 1);
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Number " + entry.getKey() + " occurs " + entry.getValue() + " times.");
}
}
Currently, the program calculates occurrence of each digit in an array and that's where duplicate digits its doing duplicate efforts.
There are different ways of achieving what you are trying to do, the straight forward way could be, store the numbers in a map, which key as number and value as 1, and increment whenever the same digit is encountered again.
There are couple of ways:
Using sorting:
Arrays.sort(userInput);
for(int i=0;i<userInput.length;){
int count = 1;
int j = i + 1;
while(j < userInput.length && userInput[i] == userInput[j]{
j++; count++;
}
System.out.println("Number "+userInput[i]+" occurs "+count +" times");
i = j;
}
This will reduce the time complexity to O(N log N)
you can further improve this till O(N) using HashMap
use HashMap
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i : userInput) {
Integer j = hm.get(i);
hm.put(i, (j == null) ? 1 : j + 1);
}
for (Map.Entry<Integer, Integer> val : hm.entrySet()) {
System.out.println("Number " + val.getKey() + " occurs " + val.getValue() + " times.");
}
You can do the same By using HashMap<Integer, Integer> as shown below.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}
HashMap<Integer, Integer> numberCountMap = new HashMap<>();
for(int element : userInput){
numberCountMap.put(element, (numberCountMap.containsKey(element)) ? numberCountMap.get(element) + 1 : 1);
}
numberCountMap.forEach((key, value) -> System.out.println("Number " + key + " occurs " + value + " times."));
}
My approach would be -
First of all to change j to j = i+1 because you dont need an extra iteration to confirm that array[i]==array[i].
Second thing is to store the results in a Map<digit , occurances> and print from the map at the end of the method.
for (int i = 0; i < 7; i++) {
int duplicates = 1;
for (int j = i+1; j < 7; j++) {
if (userInput[i] == userInput[j])
duplicates++;
}
map.put(i , duplicates);
It would be more efficient to store the numbers in a Map.
Assuming your input is 12 23 44 22 23 22 55
void duplicates(){
//acquire input and store it in a List
Scanner input = new Scanner(System.in);
List<Integer> numbers = input.nextLine().split(" ");
//store the values into a map
HashMap<Integer, Integer> numbersMap = new HashMap<>();
for(int number : numbers){
//if the map contains the number already, then increase it's occurence by one
//otherwise store it into the map with the value of 1
int newValue = numbersMap.containsKey(number) ? numbersMap.get(number) + 1 : 1;
numbersMap.put(number, newValue);
}
//print results
numbersMap.forEach((k, v) -> {
System.out.println(String.format("The number %d occured %d times.", k, v));
});
}
You can implement this in a very clean way using streams:
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class IntegerCounter {
public static Map<Integer, Long> countOccurences(int[] input) {
return Arrays.stream(input)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
}
Here is a test case that demonstrates it's usage:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Map;
public class IntegerCounterTests {
#Test
public void shouldReturnCorrectCount() {
int[] input = {12,23,44,22,23,22,55};
Map<Integer, Long> expectedResult = Map.of(12, 1L, 23, 2L, 44, 1L, 22, 2L, 55, 1L);
Map<Integer, Long> result = IntegerCounter.countOccurences(input);
result
.entrySet()
.stream()
.forEach(e -> System.out.println(String.format("Number %d occurs %d times.", e.getKey(), e.getValue())));
Assertions.assertEquals(expectedResult, result);
}
}
Next to an assertion to verify that the result is indeed what you want I also added the lines to show the output to standard out:
Number 22 occurs 2 times.
Number 55 occurs 1 times.
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 12 occurs 1 times.
You already handled the hard part. The only thing you should do is, putting writed values to a list, and if list contains the next value, simply, not to write this value again
this is your code :
`
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}
for (int i = 0; i < 7; i++) {
int duplicates = 0;
for (int j = 0; j < 7; j++) {
if (userInput[i] == userInput[j])
duplicates++;
}
System.out.println("Number " + userInput[i] + " occurs " + duplicates + " times.");
}
}
`
and this is the code, i modified a bit
List<Integer> values = new ArrayList<>();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}
for (int i = 0; i < 7; i++) {
if(!values.contains(userInput[i]){
int duplicates = 0;
for (int j = 0; j < 7; j++) {
if (userInput[i] == userInput[j])
duplicates++;
}
System.out.println("Number " + userInput[i] + " occurs " + duplicates + " times.");
values.add(userInput[i]);
}
}
}
here, the list creation of me, can be wrong. But i think you got the idea.
Good luck

ArrayList and java.lang.OutOfMemoryError

I am trying to make program that create an ArrayList of initial size of 1 and populate it with random numbers. Next, the ArrayList is cleared and the size of ArrayList is increased by 1 and again filled with random numbers. I want my program to repeat those steps until the ArrayList size will be equal to number specified by user.
So the output will be for example like:
1
3,8
6,3,7
...
n
I have produced so far:
public static void main (String args[]){
ArrayList<Integer> al = new ArrayList<Integer>();
Random rand = new Random();
int val=1;
int ii =1;
while(val<400){
for (int j = 0; j<ii;)
{
ii++;
val++;
pick = rand.nextInt(100);
al.add(pick);
}
System.out.println("Contents of al: " + al);
al.clear();
System.out.print("Array has been cleared: " + al);
}
Any ideas how to make it work?
You never increment j.
You are incrementing ii and val inside the for loop where as I think you actually want to do it in the while loop. Try the example below.
ArrayList<Integer> al = new ArrayList<Integer>();
Random rand = new Random();
int val=1;
int ii =0;
while(val < 400){
for (int j = 0; j<ii; j++) {
int pick = rand.nextInt(100);
al.add(pick);
}
ii++;
val++;
System.out.println("Contents of al: " + al);
al.clear();
System.out.print("Array has been cleared: " + al);
}
Your task would be much easier if you gave your variables meaningful names. e.g.
ArrayList<Integer> al = new ArrayList<Integer>();
Random rand = new Random();
int lineNumber = 1;
int lineLength = 0;
while(lineNumber < 400){
for (int randCount = 0; randCount < lineLength; randCount++) {
int pick = rand.nextInt(100);
al.add(pick);
}
lineLength++;
lineNumber++;
System.out.println("Contents of al: " + al);
al.clear();
System.out.print("Array has been cleared: " + al);
}
for (int j = 0; j<ii;) {
ii++;
val++;
pick = rand.nextInt(100);
al.add(pick);
}
is an infinite loop(j is always 0 and ii is always positive). You should fix it(according to the desired semantics).

Sum of ten random numbers

So far, my code looks like this:
import java.util.Random;
public class StatsCalculator
{
public static void main(String[] args)
{
Random r = new Random();
System.out.println("The ten random values are: ");
for(int i=0; i<10; i++)
{
int randomint = r.nextInt(10);
System.out.print(" ," + randomint);
}
int randomint[];
int sum=0;
for(int i : randomint)
{
sum += i;
System.out.println("Sum = " + sum);
}
}
}
When I run this code, there's an error message come up that say's the following: "variable randomint might not have been initialized, for (int i : randomint)
Try this:
int sum=0;
for(int i=0; i<10; i++)
{
int randomint = r.nextInt(10);
System.out.print(" ," + randomint);
sum = sum + randomint ;
}
System.out.println("Sum = " + sum);
Place all the randoms within an array and then sum them:
Random r = new Random();
System.out.println("The ten random values are: ");
int[] values = new int[10];
for(int i = 0; i < 10; i++) {
int randomint = r.nextInt(10);
values[i] = randomint;
System.out.print(" ," + randomint);
}
int sum = 0;
for(int i : values) {
sum += i;
}
System.out.println("Sum = " + sum);
Your array randomInt is defined as an array but elements are never added to it, then you try iterate through it and there's nothing there.
Initialise it
int[] randomInt = new int[size];
then create elements in it. It looks like you should move this to before the first array and add all the random int you create.
The error is telling you everything: "variable randomint might not have been initialized, for (int i : randomint)"
In your head, you should hear this dialog:
Hmm, why is it telling me randomint might not have been initialised? Have I initialised it?
I better check this randomint...oh, here it is:
int randomint[];
How do I initialise it...the docs...the docs...THE DOCS!
Here it is:
One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for 10 integer elements and assigns the array to the anArray variable.
// create an array of integers
int[] anArray = new int[10];
If this statement is missing, then the compiler prints an error like the following, and compilation fails:
ArrayDemo.java:4: Variable anArray may not have been initialised.
Fine, let's add this:
int randomint[] = new int[10];
compile...run...
errr, why is the sum 0 if I can see random numbers?
(reads the docs again)
Right, need to store those random ints in my array, phew, one more change:
Random r = new Random();
System.out.println("The ten random values are: ");
int randomint[] = new int[10];
for(int i=0; i<10; i++)
{
randomint[i] = r.nextInt(10);
System.out.print(" ," + randomint[i]);
}
int sum=0;
for(int i : randomint)
{
sum += i;
System.out.println("Sum = " + sum);
}
Uff, next time someone asks similar question on SO, I might be able help them. First thing I'll say is to read the docs :)

Java Loop or Arrays

My problem is based on the compound interest formula. A = P(1 + r)^n. I have a number of values for r and n which I must store as an array. I also must output my range of final values A as an array also. I think I have stored r and n correctly as an array. However my problem is with the final values of A and storing each value A. SO far this is what I have written.
import java.util.Scanner;
import javax.swing.*;
public class Prin {
public static void main (String [] args){
System.out.println("Please enter the Principal you wish to invest =>");
Scanner stdio = new Scanner (System.in);
int principal = stdio.nextInt();
stdio.nextLine();
System.out.println("This program will now calculate the final amount A for (years) n = 1,2,3,4 and the rate r = 1%, 1.5%, 2%, 2.5%, 3%");
int yearsarray[] = {1,2,3,4};
double ratearray[] = {0.010, 0.015, 0.020, 0.025, 0.030};
double amountarray[];
amountarray = new double[19];
for(int i=0; i<=3; i++)
{
for(int j=0; j<=5; j++){
amountarray[k] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
System.out.println(" answer " + amountarray[k] );
}
}
Do I need another for loop to increase the values of k in amountarray[]?
I would like to have all values of amountarray i.e amountarray[0], amountarray[1], amountarray[2], .......and so on.
Thanks in advance for any help.
amountarray = new double[19];
The code above is false because you need to have 4x5 = 20 double values
This code will always work properly, You should use this and you need to learn write your codes like this:
public class Prin {
public static void main (String [] args){
//...
int[] yearsarray = {1,2,3,4};
double[] ratearray = {0.010, 0.015, 0.020, 0.025, 0.030};
double[] amountarray = new double[yearsarray.length * ratearray.length];
int k = 0;
for(int i=0; i<yearsarray.length; i++){
for(int j=0; j<ratearray.length; j++){
amountarray[k] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
System.out.println(" answer " + amountarray[k] );
k++;
}
}
"This program will now calculate the final amount A for (years) n = 1,2,3,4 and the rate r = 1%, 1.5%, 2%, 2.5%, 3%"
... this implies your answer comes in the form of a 2-dimensional matrix.
Hence your amountarray needs to be defined as:
double amountarray[][] = new double[yearsarray.length][ratearray.length];
Then you would calculate:
amountarray[i][j] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
No, you don't
int k=0; // initialization
for(int i=0; i<=3; i++)
{
for(int j=0; j<=5; j++){
// use post-increment
amountarray[k] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
System.out.println(" answer " + amountarray[k] );
// now we can increment k
k = k+1;
}
Also this: as you seem to be using yearsarray just to get a value that's i+1, why just not do
amountarray[k] = principal * Math.pow((1 + ratearray[j]), i+1);
That way you can get rid of yearsarray, at least in this case
EDIT: a reworked version that also handles a couple of other minor issues and reduced usage of "magic numbers"
public class Prin {
public static void main(String[] args) {
System.out.println("Please enter the Principal you wish to invest =>");
Scanner stdio = new Scanner(System.in);
int principal = stdio.nextInt();
stdio.nextLine();
System.out.println("This program will now calculate the final amount A for (years) n = 1,2,3,4 and the rate r = 1%, 1.5%, 2%, 2.5%, 3%");
int yearsarray[] = {1, 2, 3, 4};
double ratearray[] = {0.010, 0.015, 0.020, 0.025, 0.030};
double amountarray[];
// this way the array will follow the size of yearsarray and ratearray
amountarray = new double[yearsarray.length * ratearray.length];
int k = 0; // initialization
for (int i = 0; i <= yearsarray.length; i++) {
System.out.println("years=" + yearsarray[i]);
for (int j = 0; j < ratearray.length; j++) {
// use post-increment
amountarray[k] = principal * Math.pow((1 + ratearray[j]), yearsarray[i]);
System.out.println(" " + ratearray[j] + " answer " + amountarray[k]);
k+=1;
}
}
}
}
Try to store your data in a Map, this is an example of your loop
for(int i=0; i<=yearsarray.length; i++) {
for(int j=0; j<=ratearray.length; j++) {
double answer = (yearsarray, principal * Math.pow((1 + ratearray[j]), yearsarray[i]));
Collection<Double> aux;
if (!answers.containsKey(yearsarray[i])){
aux = new ArrayList<Double>();
aux.add(answer);
} else {
aux = answers.get(yearsarray[i]);
aux.add(answer);
}
answers.put(yearsarray[i], aux);
// include the answers in a Map
}
}
Thanks

Calculate average of an array and insert in another array

How can I calculate the average of an array, and insert it in another array and print that in the console.
For example, I have an array of size 100, and I wanna calculate the average of the numbers in the array and then insert in in an array of size 5.
Here's one way of doing it:
public class Main
{
public static void main(String[] args)
{
float averages[] = new float[5];
int aLotOfNumbers[] = new int[100];
// Initialize the numbers to 0, 1, 2, 3, 4, ..., 99
for(int i=0; i<100; i++)
{
aLotOfNumbers[i] = i;
}
// Compute the averages by summing groups of 20 numbers and dividing the sum by 20
for(int i=0; i<5; i++)
{
float runningSum = 0.0f;
for(int j=0; j<20; j++)
{
runningSum += aLotOfNumbers[i*20 + j];
}
averages[i] = runningSum / 20.0f;
}
// Print the 5 average values
for(int i=0; i<5; i++)
{
System.out.println("Average[" + i + "] = " + averages[i]);
}
}
}

Categories