how to print an dynamic array with normal For loop - java

I am having trouble printing the values of an array declared with ArrayList.
I am using the enchanced for to print its values but what if i want to sum them.
import java.util.ArrayList;
import java.util.Scanner;
public class Program
{
public static void main(String[] args){
int sum = 0;
ArrayList<Integer> numbers = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
int x = input.nextInt();
while (x != -1){
numbers.add(x);//xonoyme ta stoixeia ston numbers
x = input.nextInt();
}
for (int y: numbers){
sum = sum + numbers;
System.out.print(y + " ");
}
System.out.print("to athroisma einai: " + sum);
}
}
the error is in the command
sum = sum + numbers;

Here:
sum = sum + numbers;
numbers is the list of numbers you are iterating on.
You probably meant:
sum = sum + y;
sum is a primitive int variable. The + operator only allows you to add other primitive numerical values here. You can't add a List<Integer> to an int value.
Alternatively, you can use Java 8 streams here:
numbers.stream().mapToInt(Integer::intValue).sum();
sums up all values in your list, too.

Related

Calculating Sums and Averages of inputted numbers, and sorting numbers in Eclipse

The Problem: Write a program that reads in five whole numbers from the user. The program will calculate and output
the following statistics about the five numbers:
• The sum of all of the positive numbers (greater than zero).
• The sum of all of the non-positive numbers (less than or equal to zero).
• The sum of all five numbers.
• The average of all of the positive numbers (greater than zero).
• The average of all of the non-positive numbers (less than or equal to zero).
• The average of all five numbers.
Here is what I have for my code:
package assignment_09_20_2018;
import java.util.Scanner ;
public class LAB_Assignment_09_20_2018 {
public LAB_Assignment_09_20_2018() {
// TODO Auto-generated constructor stub
public static void main(String[] args) {
// TODO Auto-generated method stub
int length;
Scanner input = new Scanner(System.in) ;
//opens scanner
System.out.println("Enter 5 numbers: ") ;
length = input.nextInt() ;
Int[] numbers = new Int[length]
}
}
someone in my class said to use arrays and for loops but i have no idea how to, please help
Disclaimer, I'm a C# guy so my syntax may not be entirely right.
Create a loop to accept numbers into an array.
Int [] numbers = new Int [5]{};
for (Int i = 0; i < numbers.Length; i++)
{
System.out.println("Enter a number.");
numbers[i] = Scanner(System.in);
}
Then use math on the array with a combination of if statements to determine < or > values.
for (Int i = 0; i < numbers.Length; i++)
{
if ( numbers[i] < 0)
{
// do this math
}
else if (numebers[I] > 0)
{
// do this math.
}
}
and so forth.
This is obviously homework, so I'll just help with the Java code for reading in the numbers, then provide some pseudocode for the required calculations.
public static void main(String[] args)
{
int length = 5;
Scanner input = new Scanner(System.in);
System.out.println("Enter 5 numbers: ") ;
int[] numbers = new int[length];
for(int i=0; i<length; i++)
{
numbers[i] = input.nextInt();
}
// calculations go here
}
Calculations would look something like this:
posSum = posCount = negSum = negCount = 0
for n in numbers
if n > 0
posSum = posSum + n
posCount = posCount + 1
else
negSum = negSum + n
negCount = negCount + 1
You now have the required positive and negative sums. The total sum is obviously these added. Given posSum and posCount you can calculate the average positive number (check for the case where posCount is 0). The same for average negative.
Finally, a question - do you need to keep track of posCount and negCount, or could you calculate one from the other once the loop is done?
You can use array and for loop as shown in below code. I am using an int[] array to store the 5 numbers to be input by the user and populating that using a for loop.
public static void main(String[] args) throws IOException, JSONException, ParseException {
Scanner input = new Scanner(System.in) ;
System.out.println("Enter 5 numbers: ") ;
int[] array = new int[5];
for(int i=0;i<array.length;i++) {
array[i] = input.nextInt();
}
for(int i=0;i<array.length;i++) {
System.out.println(array[i]);
}
}
Now you can use a for-loop and cover all the cases given in the question.
For example: The sum and average of all five numbers can be calculated as shown below:
//sum of all 5 numbers
int sum=0;
for(int i=0;i<array.length;i++) {
sum += array[i];
}
System.out.println(sum); // Prints the sum of 5 numbers
int average = sum/array.length;
System.out.println(average); // Prints the average of 5 numbers
EDIT: Code for sum of positive numbers and negative numbers only
int posSum=0;
int negSum=0;
for(int i=0;i<array.length;i++) {
if(array[i]>0){
posSum += array[i];
}else if(array[i]<0){
negSum += array[i];
}
}
System.out.println("Positive number only sum is "+posSum);
System.out.println("Negative number only sum is "+negSum);

Issue increment sum=0 by long integers pass 9 digits in Java

The program begins by asking the user to give a value assigned to variable n, the user will then be prompted to submit long digits n amounts of times. The digits will then be stored into the initialized array (ar). The function I am trying to create aVeryBigSum is to loop through the numbers in the array, incrementing sum=0 by the numbers in the array to provide the sum (Java).
For some reason however, the program works unless I use two consecutive numbers with greater than 9 digits.
For example:
aVeryBigSum(2,[111111111,111111111]) has n of 2 and two 9 digit numbers in the array
Output:
22222222
aVeryBigSum(2,[1111111111,1111111111]) has n of 2 and two 10 digit numbers in the array
Output:
-2072745074
Any idea what the issue might be? I've provided the program below:
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
static long aVeryBigSum(int n, long[] ar) {
int sum = 0;
for (int i = 0; i < n; i++){
System.out.println(sum);
System.out.println(ar[i]);
sum += ar[i];
System.out.println(" ");
}
return sum;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long[] ar = new long[n];
for(int ar_i = 0; ar_i < n; ar_i++){
ar[ar_i] = in.nextLong();
}
long result = aVeryBigSum(n, ar);
System.out.println(result);
}
}
Your problem is in the line
int sum = 0;
It should read
long sum = 0;
You are triggering integer overflow when the sum of integers exceeds 32 bits.
Yes, agree with Mad Physicist. You have to use long sum = 0. But to be the completely correct, you have possibility to have sum greater than Long.MAX_VALUE. You could use e.g. BigDecimal:
static BigDecimal aVeryBigSum(int n, long[] ar) {
BigDecimal sum = BigDecimal.ZERO;
for (int i = 0; i < n; i++) {
System.out.println(sum);
System.out.println(ar[i]);
sum = sum.add(new BigDecimal(ar[i]));
System.out.println(" ");
}
return sum;
}

Sum and average of values in an array

I want to ask how to add the values and find average of values in an array. I have tried searching multiple times, but I could find something that explains how to do all that in simple code that a new programmer such as myself could understand. If someone could tell me how to do it and explain the codes used, that will be great. Thanks in advance :>
I leave the normal answers for others to do. For java people,Here we go!
public static void main(String[] args) {
int myarr[]={1,2,3,4,4,5,6,5,7,8,4};
IntSummaryStatistics statisticalData=Arrays.stream(myarr).summaryStatistics();
System.out.println("Average is " + statisticalData.getAverage());
System.out.println("Sum is " + statisticalData.getSum());
}
Other data like count,minimum element,maximum element can also be obtained from the IntSummaryStatistics object
public static void main(String args[]) {
Scanner s = new Scanner(System.in); //Define Scanner class object which will aid in taking user input from standard input stream.
int a[] = new int[10]; //Define an array
int i,sum = 0;
for(i = 0; i < 10; i++) {
a[i] = s.nextInt(); //Take the arrays elements as input from the user
}
for(i = 0; i < 10; i++) { //Iterate over the array using for loop. Array starts at index 0 and goes till index array_size - 1
sum = sum + a[i]; //add the current value in variable sum with the element at ith position in array. Store the result in sum itself.
}
double avg = (double) sum / 10; //Compute the average using the formula for average and store the result in a variable of type double (to retain numbers after decimal point). The RHS of the result is type casted to double to avoid precision errors
System.out.print(sum + " " + avg); //print the result
}
At first you have to take an array of numbers. Iterate all the numbers in the array and add the numbers to a variable. Thus after iteration you will get the sum of the numbers. Now divide the sum by count of numbers (which means the size of array). Thus you will get the average.
int[] numbers = {10, 20, 15, 56, 22};
double average;
int sum = 0;
for (int number : numbers) {
sum += number;
}
average = sum / (1.0 * numbers.length);
System.out.println("Average = " + average);
You can also iterate in this way:
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
void sumAndAverage(int a[]){
if(a!=null&&a.length>0{
int sum=0;
//traverse array and add it to sum variable
for(int i=0;i<a.length;i++){
sum=sum+a[i];
}
double avg=(1.0*sum)/a.length;
System.out.println("sum= "+sum);
System.out.println("average= "+avg);
}
}

How to change values using arrays/arraylists to asteriks

Im very new to Java, and I'm trying to write a program using arrays and arraylists where you enter in however many values you want, and it outputs how many values are between two parameters using asterisks.
ex:
[5,14,23,43,54,15]
1-10: *
11-20: **
21-30:*
31-40:
41-50:*
51-60: *
And so on. Here's what I have so far, but I'm getting errors and out of bounds exceptions. Can anyone say whether or not I'm on the right track or not? Any help is appreciated!
package arraylists;
import java.util.ArrayList;
import java.util.Scanner;
public class numberslists {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
ArrayList numbers = new ArrayList();
int [] number = new int[10];
int x, count = 0;
System.out.println("how many numbers would you like?");
count = reader.nextInt();
System.out.println("enter in those numbers please");
for (x=0; x < count; x++){
number[x] = reader.nextInt();
numbers.add(number[x]);
}
System.out.println(numbers);
int x10 = numbers.indexOf(number[x] < 10);
numbers.remove(x10);
System.out.println(numbers);
}
}
In short, as Lahiru said, you need to change the line: int x10 = numbers.indexOf(number[x] < 10);
The main problem with your code is the expression number[x] < 10 which returns a boolean (true or false). Therefore the numbers.indexOf(number[x] < 10) is going to return 1 or -1.
Finally, when the code gets to numbers.remove(x10); and if is -1 (for false) then you will get java.lang.ArrayIndexOutOfBoundsException because there is no way to do a numbers.remove(-1);. See the documentation.
There is room for improvement in your code. Below is a suggestion to what you could do. But just look at this suggestion after you try fixing your own code (so you can have a better learning experience).
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CountOcurrancesInArray {
private static Scanner reader = new Scanner(System.in);
private static List<Integer> numbers = new ArrayList<Integer>(); // Use generics when possible: <Integer>
public static void main(String[] args) {
int x, count = 0;
System.out.println("how many numbers would you like?");
count = reader.nextInt();
System.out.println("enter in those numbers please");
for (x=0; x < count; x++){
// I don't see a need for this line. number[x] = reader.nextInt();
numbers.add(reader.nextInt());
}
System.out.println(numbers);
int[] comparingNumbers = requestComparingNubers();
System.out.println("You entered these numbers: " + numbers);
String matchingNumbers = checkForNumbersInTheList(comparingNumbers);
System.out.println("Numbers between " + comparingNumbers[0] + "-" + comparingNumbers[1] + ":" + matchingNumbers);
}
/**
* Counts how many entries are in the list between 'comparingNumbersInput'
* #param comparingNumbersInput
* #return number of entries as asterisks "*"
*/
private static String checkForNumbersInTheList(int[] comparingNumbersInput) {
String result = "";
for(Integer i : numbers) {
if (i >= comparingNumbersInput[0] && i <= comparingNumbersInput[1]) {
result += "*";
}
}
return result;
}
/**
* Asks the user to enter 2 numbers to be compared against the all the numbers in the list.
* #return returns a int[2] sorted ascendingly
*/
private static int[] requestComparingNubers() {
int [] result = new int[2];
System.out.println("Counting how many numbers there are in between x and y.");
System.out.println("What is the first number?");
result[0]=reader.nextInt();
System.out.println("What is the second number?");
result[1]=reader.nextInt();
// Sort comparingList
if (result[0] > result[1]) {
int temp = result[1];
result[1] = result[0];
result[0] = temp;
}
return result;
}
}
Declare Array after getting count from user.
int x, count = 0;
System.out.println("how many numbers would you like?");
count = reader.nextInt();
int [] number = new int[count];
Also have a look at the Line of code that caused the error.
To me, this makes more sense as a Map, where you store a counter for each range found in the array of inputs. Now that means you have to first figure out what the range if that each input fits within, then update your counter that matches the range. Since we have to calculate the range as a String for output and you want the counter to be represented as a String of asterisk anyway, Storing the range as a String for the Map.key and the counter as a String of asterisk as the Map.value works nicely.
Here is some example code that does just that, where numbers is the ArrayList of the original values input by a user.
//Declare a Map that stores the range as a String ( "01-10") as the key
//and a counter in astericks as the value
Map<String,String> counters = new HashMap<>();
//Loop over the array ov values
for(Integer value: numbers){
//For each value calculate the diviser by diving by 10
Integer lowRange = value / 10;
//To get the low range, multiply the diviser by 10 and add 1
lowRange = (10 * lowRange) + 1;
//The high range is 9 mor ethan the low range
Integer highRange = lowRange + 9;
//Finally calcualte what the range looks like as a String
//Note that it handles "1" as a special case by prepending a "0" to make the value "01"
String rangeString = ((lowRange < 10) ? "0" + lowRange : lowRange) + "-" + highRange;
//Now check the map to see if the rangeString exists as a key, meaning
//we have previously found a value in the same range
String count = "";
if(counters.containsKey(rangeString)){
//If we found the same range, get the previous count
count = counters.get(rangeString);
}
//Place the count back into the map keyed off of the range and add an asterick to the count String
counters.put(rangeString, count + "*");
}
//Finally iterate over all keys in the map, printing the results of the counters for each
for(String range: counters.keySet()){
System.out.println(range + " " + counters.get(range));
}
As an example of output, if the user inputs the values:
[5,14,23,43,54,15,41]
The output would be:
01-10 *
11-20 **
41-50 **
51-60 *
21-30 *
Java arrays are zero-based index. For example, if you declare an array with 10 elements, the index of these elements will be from 0 to 9.
In your code snippet below, when java finishes the "for" loop
for (x=0; x < count; x++){
number[x] = reader.nextInt();
numbers.add(number[x]);
}
The value of x variable will be equal to the number of elements you have inputted to the number array (x = count).
So, when you get the element at x position as below:
int x10 = numbers.indexOf(number[x] < 10);
If x < 10, you will get -1 for x10. Then an exception will occur at:
numbers.remove(x10);
If x >= 10, an ArrayIndexOutOfBoundsException will occur at number[x]
Yet another Homework question
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
public class numberlists {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
LinkedList < Integer > numbers = new LinkedList < Integer > ();
//int [] number = new int[10]; no need, and the input is variable size
int x, count = 0;
System.out.println("how many numbers would you like?");
count = reader.nextInt();
System.out.println("enter in those numbers please");
Map < Integer, Integer > range_numbers = new HashMap < Integer, Integer > ();
for (x = 0; x < count; x++) {
//number[x] = reader.nextInt(); no need
numbers.add(reader.nextInt());
int rs = ((int) numbers.getLast() / 10) * 10 + 1; //range start for number i.e rs(15)=11
if (!range_numbers.containsKey(rs)) { //check if has number in that range
range_numbers.put(rs, 1);
} else { //gets the prev count, add 1 and stores back for range
range_numbers.put(rs, range_numbers.get(rs) + 1);
}
}
System.out.println(numbers);
Map < Integer, Integer > sortedpairs = new TreeMap < Integer, Integer > (range_numbers); // need to sort
for (Map.Entry < Integer, Integer > pair: sortedpairs.entrySet()) {
System.out.printf("\n%d-%d: %s", pair.getKey(), pair.getKey() + 9,
new String(new char[pair.getValue()]).replace("\0", "*"));
//little trick to repeat any string n times
}
}
}
Enjoy.

Find the most frequent value in an array of double in Java (without hashmaps or sorting)

Write a full Java program that does the following:
Creates an array of 100 double.
Reads in an unknown number of doubles from a file named values.txt .
There will be at least 2 distinct values, and no more than 100 distinct values in the file. The values will be in unsorted order. Values will be no smaller than 0, and no larger than 99.
Outputs the most frequently occurring value in the file.
Outputs the least frequently occurring value in the file. The value must occur at least once in order to be output.
Outputs the average of all array values.
You must create and use separate methods for each of the items #2-5.
This is what I have so far. I cannot for the life of me figure out how to get this right:
import java.util.*;
import java.io.*;
public class arrayProgram2 {
static Scanner console = new Scanner(System.in);
static final int ARRAY_SIZE = 100;
static int numOfElements = 0;
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new FileReader("values.txt"));
double[] Arr1 = new double[ARRAY_SIZE];
while (inFile.hasNext()) {
Arr1[numOfElements] = inFile.nextDouble();
numOfElements++;
}
System.out.println("There are " + numOfElements + " values.");
System.out.printf("The average of the values is %.2f%n", avgArray(Arr1));
System.out.println("The sum is " + sumArray(Arr1));
inFile.close();
} //end main
//Method to calculate the sum
public static double sumArray(double[] list) {
double sum = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
return sum;
}
//Method to calculate the average
public static double avgArray(double[] list) {
double sum = 0;
double average = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
average = sum / numOfElements;
return average;
}
} //end program
Notice I am required to make an array of double even though it is not necessary.
If all values are int than you should use int array instead of double. As all values in range 0-99. So, you can increase input value frequency. Look at below logic:
int[] freqArr= new int[100];
while (inFile.hasNext()){
int value = inFile.nextInt();
freqArr[value]++; // count the frequency of selected value.
}
Now calculate the maximum frequency from freqArr
int maxFreq=0;
for(int freq : freqArr){
if(maxFreq < freq){
maxFreq = freq;
}
}
Note: If double array is mandatory than you can also use double array like:
double[] freqArr= new double[100];
while (inFile.hasNext()){
freqArr[(int)inFile.nextDouble()]++;
}
It's possible to find a most-occurring value without sorting like this:
static int countOccurrences(double[] list, double targetValue) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == targetValue)
count++;
}
}
static double getMostFrequentValue(double[] list) {
int mostFrequentCount = 0;
double mostFrequentValue = 0;
for (int i = 0; i < list.length; i++) {
double value = list[i];
int count = countOccurrences(list, value);
if (count > mostFrequentCount) {
mostFrequentCount = count;
mostFrequentValue = value;
}
}
return mostFrequentValue;
}
Pham Thung is right : -
You read in integer inFile.nextInt(), why do you need to use double array to store them? – Pham Thung
You can achieve your first functionality in n time if its integer array.
you question says,
Values will be no smaller than 0, and no larger than 99.
So,
1. Make an array of size 100.(Counter[])
2. Iterate through values of your current array and add count to Counter array.
eg:
if double array contains
2 3 2 5 0 0 0
Our counter array will be like
location : 0 1 2 3 4 5 6 ...........100
values : 3 0 1 1 0 1 0 ..............
and so on.
You can use below algorithm for this
Sort the array (you only need to read unsorted array, but you can sort the array once read from the file)
Make double var : num, mostCommon, count = 0, currentCount = 1
Assign Arr1[0] to num
for i from 1 to length of Arr1
i. if(Arr1[i] == num)
a. Increment currentCount
ii. else
a. if(count > currentCount)
A. Assign currentCount to count
B. Assign num to mostCommon
C. Assign Arr1[i] to num
D. Assign 1 to currentCount
At the end of this loop, you will have most common number in mostCommon var and it's number of occurrence in count.
Note : I don't know how to format the algo

Categories