ArrayList<Integer>, trying to find average of entered values - java

Trying to find the average of the integers entered as input into the list.
Cant figure out how, im getting an error saying that it can't find symbol in
in the line total = total + in;
import java.util.*;
import java.io.*;
import java.lang.*;
import type.lib.*;
public class Lists
{
public static void main(String[] args)
{
PrintStream print = new PrintStream(System.out);
Scanner scan = new Scanner(System.in);
List<Integer> bag = new ArrayList<Integer>();
print.println("Enter your integers");
print.println("(Negative=sentinel)");
int total = 0;
int count = 0;
for (int in = scan.nextInt(); in > 0; in = scan.nextInt());
{
total = total + in;
count = count + 1;
}
double x = total / count;
print.println("The average is: " + x);
}
}
also, is there an easy way to output the numbers above average divided with a comma?

Remove the semi-colon after the for loop:
for (int in = scan.nextInt(); in > 0; in = scan.nextInt())
The reason in is not defined for the compiler is that the semi-colon would de-scope its definition by acting as an empty body of the for loop.

Remove ; from your loop.
for (int in = scan.nextInt(); in > 0; in = scan.nextInt());
change to
for (int in = scan.nextInt(); in > 0; in = scan.nextInt())

You shouldn't have ; after for loop...
for (int in = scan.nextInt(); in > 0; in = scan.nextInt())//remove ; here

The syntax of a for loop is:
for(initialization; Boolean_expression; update)
{
//Statements
}
You have added semicolon ; so it's become empty body for for loop. you have to remove the semicolon after for (int in = scan.nextInt(); in > 0; in = scan.nextInt()) line in your code.
Modified Code : I am providing code after modification.
public class Lists
{
public static void main(String[] args)
{
PrintStream print = new PrintStream(System.out);
Scanner scan = new Scanner(System.in);
List<Integer> bag = new ArrayList<Integer>();
print.println("Enter your integers");
print.println("(Negative=sentinel)");
int total = 0;
int count = 0;
for (int in = scan.nextInt(); in > 0; in = scan.nextInt()){
total = total + in;
count = count + 1;
}
double x = total / count;
print.println("The average is: " + x);
}
}

The above code requires two changes:
1.You need to remove the semicolon after for loop which is making loop useless and all the iterations you want to do won't take place.
2.The second change is you need to cast one of the variables total or count to double to avoid truncation else your results will always be integers.
The modified code is as follows:
import java.util.*;
import java.io.*;
import java.lang.*;
import type.lib.*;
public class Lists
{
public static void main(String[] args)
{
PrintStream print = new PrintStream(System.out);
Scanner scan = new Scanner(System.in);
List<Integer> bag = new ArrayList<Integer>();
print.println("Enter your integers");
print.println("(Negative=sentinel)");
int total = 0;
int count = 0;
for (int in = scan.nextInt(); in > 0; in = scan.nextInt())
{
total = total + in;
count = count + 1;
}
double x = (double)total / count;
print.println("The average is: " + x);
}
}

Related

Finding the minimum of scanner input in a method

I am trying to find the minimum of a variable input of the scanner class. I have as many inputs as the user wants but I cannot seem to find out how to find the minimum of multiple inputs. Any help would be appreciated.
public static void minimum(int count)
{
double input;
boolean lessThan;
double lesser = 0;
for(count = count; count > 0; count--)
{
System.out.print("Enter a double: ");
input = console.nextDouble();
lessThan = input < input;
if(lessThan = true)
{
lesser = input;
}
else
{
lesser = input;
}
}
System.out.println("The minimum is " + lesser);
}
public static void main(String [] args){
Scanner scanner = new Scanner(System.in);
System.out.println("How many inputs?: ");
int answer = scanner.nextInt();
int arr[] = new int[answer];
int y = 0;
while(y < answer){
System.out.println("Enter a value: ");
arr[y] = scanner.nextInt();
y++;
}
int smallNum = arr[arr.length - 1];
for(int i = arr.length; i > 0; i--){
if(smallNum > arr[i - 1]){
smallNum = arr[i - 1];
}
}
System.out.println("Minimum is: " + smallNum);
}
Here is the answer but my answer is a little bit different. Firstly I created an initialized array because we need to execute the code several times, then I stored the user inputs into the array after that I found the min value using array indexes.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double arr[] = new double[5];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the double");
arr[i] = scanner.nextDouble();
}
double min = arr[0];
for (int j=0;j<arr.length;j++){
if(arr[j]<min)
min=arr[j];
}
System.out.println("min value is"+" "+min);
}

Looping a dice simulation

I seem to be having some trouble looping my dice simulator. I've placed the body of my code in a do-while loop but when the output prints to console it adds the previous output from the last simulation. I've tried initializing my "n" variable in a couple different places but have had no luck. Any help would be greatly appreciated.
My code follows...
import java.util.Random;
import java.util.Scanner;
public class Trash{
public static int getInt(Scanner scan) {
int input;
while ( !scan.hasNextInt() ) {
String garbage = scan.nextLine();
System.out.println("Please enter an integer. ");
}
input = scan.nextInt();
scan.nextLine();
return input;
}
public static void main(String [] args){
Scanner scan = new Scanner(System.in);
Random rand = new Random();
int dice1, dice2;
int [] frequency = new int [13];
int [] rolls = new int [13];
String again;
String stars = "";
double percentage;
do{
System.out.println("Enter the number of trials:");
int n = getInt(scan);
for (int i = 0; i < n; i++) {
dice1 = rand.nextInt(6)+1;
dice2 = rand.nextInt(6)+1;
frequency[dice1+dice2]++;
}
System.out.printf("Outcome\tFrequency\tPercentage\t\tHistogram\n");
for (int i = 2; i < frequency.length; i++) {
stars = "";
for ( int j = 0; j < frequency[i]; j++) {
stars = stars + "*";
}
percentage = (frequency[i] * 100.0) / n;
System.out.printf("%7d\t%9d\t%10.2f\t\t%1.50s\n",i,frequency[i], percentage, stars);
}
System.out.println("Run simulation again?");
String answer = scan.nextLine();
again = answer.toLowerCase();
} while (again.equals("yes"));
}
}
The reason is because you are not re-initializing the array when you re-started the simulation again.
do {
// re-initialize here
frequency = new int [13];
rolls = new int [13];
System.out.println("Enter the number of trials:");
// the rest of your code
} while (again.equals("yes"));

Adding numbers of a list together

3
100 8
15 245
1945 54
The numbers above, first is the amount of pairs, and then I want to add line by line, and have been stuck for hours. Can someone please help me?
import java.util.Scanner;
import java.util.ArrayList;
public class sumInLoops2 {
public static void main(String[] args)
{
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("Enter your variables: ");
int cases = in.nextInt();
int sum = 0;
for(int i = 0; i < cases; i++) {
list1.add(in.nextInt());
list2.add(in.nextInt());
System.out.println(list1);
System.out.println(list2);
}
You are overcomplicating things. If you don't need to store the read values, only output the sum, then you don't need all the lists.
import java.util.Scanner;
public class sumInLoops2 {
public static void main(String[] args)
{
// ArrayList<Integer> list1 = new ArrayList<Integer>();
// ArrayList<Integer> list2 = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("Enter your variables: ");
int cases = in.nextInt();
for(int i = 0; i < cases; i++) {
int val1 = in.nextInt();
int val2 = in.nextInt();
int sum = val1 + val2;
System.out.println(val1 + " + " + val2 + " = " + sum );
}
}
}
If you need to store the results, make a helper object (eg LineSum) with properties val1, val2, sum, and put that in one output list.
As #thst said stated, if there is no need to store the data being inputted by the user, don't over complicate things and just output the result you need. However if your intention is to learn how to output matching number pairs within those separate lists.
Whenever you want to access a item inside a List you use the lists get() method which returns the item at that index. So in your case to print out the matching pairs added together.
for (int i = 0; i < cases; i++)
{
int num1 = list1.get(i);
int num2 = list2.get(i);
int sum = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + sum);
}
A fast example using Java8(best way,give it a try):
import java.util.Arrays;
import java.util.Scanner;
public class Java8Way {
public static void main(String[] args) {
//Create a Scanner Object
Scanner in = new Scanner(System.in);
System.out.println("Enter your variables(separated by a space): ");
//what the following is doing
//Arrays.asList(in.nextLine().split(" ")->Splits the line that user gave to individual strings
//makes a list from them using method asList(..); from
//Arrays Class
//mapToInt(Integer::valueOf)-> makes a stream an map each string to and integer
//sum()->a special kind of reduce function which sums all the Integer elements
System.out.println("Your sum is...:"+Arrays.asList(in.nextLine().split(" ")).stream()
.mapToInt(Integer::valueOf)
.sum());
}
}

ArrayIndexOutOfBoundsException exception which I just cant figure out

I simply cant figure out why I keep getting an indexoutofboundserror. I believe its pop up in the line
profits[i] = storeDays
The code is:
import java.util.Arrays;
import java.util.Scanner;
class Business
{
public static void main(String[] args) {
Scanner inputScanner;
inputScanner = new Scanner (System.in);
System.out.println("Welcome to the profit-calculation program.");
System.out.println("how many days of data do you have?");
int n = Integer.parseInt (inputScanner.nextLine());
//call upon a function to store the profits into an array for further use.
double[] dayProfitList = inputProfit(n);
//call upon a function to calculate average profit and its standard devation
//calcAverageProfit(dayProfitList);
}
public static double[] inputProfit(int days) {
Scanner inputScanner;
inputScanner = new Scanner (System.in);
System.out.println("input the profit on..");
double[] profits = new double [days];
for(int i = 1; i<days +1; i++) {
System.out.println("day " + i + "?");
double storedDays = Double.parseDouble(inputScan ner.nextLine());
profits[i] = storedDays;
}
return profits;
}
}
Arrays are enumarated from 0 so the first element of it is profits[0], next one is profits[1] and so on.
You are trying to reach an index that does not exist here:
for(int i = 1; i<days +1; i++) {
...
It actually should be
for(int i = 0; i<days; i++) {
...

Adding multiple java arrays once

I am trying to create a simple program that asks you 10 integers and the program will automatically add them all. I always get an error from Java which is this
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 55
at Sum2.main(Sum2.java:29)
How can I add those multiple array values once?
I tried using
integerArray[0]+[1].....
But it is still not working, please help.
import java.util.Scanner;
public class Sum2 {
private static Scanner sc;
public static void main(String[] args) {
int totalsum;
int[] integerArray = new int[11];
sc = new Scanner(System.in);
System.out.println("Please enter your 10 integers : ");
integerArray[0] = sc.nextInt();
integerArray[1] = sc.nextInt();
integerArray[2] = sc.nextInt();
integerArray[3] = sc.nextInt();
integerArray[4] = sc.nextInt();
integerArray[5] = sc.nextInt();
integerArray[6] = sc.nextInt();
integerArray[7] = sc.nextInt();
integerArray[8] = sc.nextInt();
integerArray[9] = sc.nextInt();
integerArray[10] = sc.nextInt();
totalsum = integerArray[0+1+2+3+4+5+6+7+8+9+10];
System.out.println("The sum of the first 10 integers is: " +totalsum);
}
}
> totalsum = integerArray[0]
+ integerArray[1]
+ integerArray[2]
+ integerArray[3]
+ integerArray[4]
+ integerArray[5]
+ integerArray[6]
+ integerArray[7]
+ integerArray[8]
+ integerArray[9];
Or
totalsum = 0;
for(int i = 0; i < 10; i++) {
totalsum += integerArray[i];
}
By the way, your array contains 11 Integers, not 10.
EDIT: (reply on your comment)
About making code cleaner, this is a lot better than 10 times the same line:
System.out.println("Please enter your 10 integers : ");
for(int i = 0; i < 10; i++) {
integerArray[i] = sc.nextInt();
}

Categories

Resources