Java, My numbers getting printed rounded down - java

My setAverage method is getting a list of numbers to sum them up. If I give an ArrayList of lets say 200 200 200, the outcome is 600. But if I give it 200 200 250, the coutome is the same. I do not get it.
Also: I do not want to get the average now, I am at the point of just sum up the array.
import java.util.ArrayList;
public class calculation {
private ArrayList<Integer> x;
private int z;
public void setAverage(ArrayList<Integer> myList) {
x = myList;
for(int i: myList) {
z += i;
break;
}
}
public int getAverage() {
return z;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class eingaben {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
calculation rechneAVG = new calculation();
ArrayList<Integer> myList = new ArrayList<Integer>();
while(scan.hasNextInt()) {
myList.add(scan.nextInt());
rechneAVG.setAverage(myList);
}
System.out.println(rechneAVG.getAverage());
}
}

Typically you're not looking to use a break statement in a foreach style loop, the break will terminate the loop which is what is causing your issues here.
Also I'm not a big fan of what you're doing with the setting of x to the value of the input list. Could you maybe restructure the function to return a value that is added to your list? Not really part of your question, more of an aside.

Assuming you are doing something like this before
ArrayList<Integer> list = Arrays.asList(new int[] {200,200,250});
calculation calc = new calculation();
calc.setAverage(list);
Then you should rewrite your class like this:
import java.util.ArrayList;
public class Calculation {
private ArrayList<Integer> intList;
private int avg;
public void setAverage(ArrayList<Integer> myList) {
intList = myList;
avg = 0;
for(int i: myList) {
avg += i;
}
}
public int getAverage() {
return avg;
}
}
That is: initialize z (I renamed it to avg) and ditch the break;
Also, never use break. I am fighting my own crusade to stop coders from using break/continue, but they tell me I'm crazy.

Related

How do I save an output from a method to use it in a different method?

Im sorry if this question has been asked a lot. Im still pretty new to programming and obviously have some issues in phrasing questions/searching for answers.
I want to do the following:
My algorithm includes 2 methods. One has the task to find out how many of the numbers between 0 to 30 are even and which one are not. I want those even numbers to be somehow stored and redirected to my second method to get added. How can I store those even numbers?
My code looks currently like this: (not even close to being finished)
public class Add
{
static long method(long end)
{
long number = even;
return;
}
static long even() {
if (i%2 == 0) { // even
}
else { // uneven
}
}
public static void main(String[ ] args)
{
int number = method(30);
System.out.println("");
}
}
edit:Im having formating problems... Im sorry the code looks even harder to understand. Im trying to fix it this instant.
Like it was said in the comments, add them to a list, then iterate the list while updating a variable that will be the sum of the even numbers.
public class Add {
private static ArrayList<Integer> evenNums = new ArrayList<>();
private static void evenNumbers(int max) {
for (int i = 0; i < max; i++) {
if (i % 2 == 0) {
evenNums.add(i);
}
}
}
private static int sum(ArrayList<Integer> array){
int sum = 0;
for(int i = 0; i < array.size(); i++){
sum = sum + i;
}
return sum;
}
public static void main (String[]args){
evenNumbers(30);
int sum = sum(evenNums);
System.out.println(sum);
}
}

Creating a list with input, however nothing shows up after compiling

I wish to create a list, and the list has a input as length, however after I put in the preferable length as input, the list won't show up;
import java.util.ArrayList;
import java.util.Scanner;
public class JJ {
public static void main(String args[]) {
JJ.getalist();
}
public static ArrayList<Integer> getalist(){
ArrayList<Integer> JJ = new ArrayList<Integer>();
System.out.println("Oh, How long would you want your list to be?");
Scanner in = new Scanner(System.in);
int length = in.nextInt();
for (int i=0; i<length; i++) {
int point = (int) (Math.random()*9);
JJ.add(new Integer(point));
}
return JJ;
}
}
You didn't use System.out.println() in the main method when invoking JJ.getalist(). You can pass JJ.getalist() return value as the argument of the method printing to the console like this:
System.out.println(JJ.getalist()).

Sum of elements of an Integer ArrayList without looping

I have gone through a few web resources and links, however, I am unable to find the sum of elements of an Integer ArrayList without looping. I am looking for a function which will allow me to do this in a single line.
I was able to find the same for a normal array as follows
import java.util.ArrayList;
import java.util.stream.IntStream;
public class sumArray
{
public static void main(String[] args)
{
int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);
}
}
I can write a user-defined function as follows
import java.util.ArrayList;
public class sumAL
{
public static void main(String[] args)
{
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(3);
al.add(5);
System.out.println(sum(al));
}
static int sum(ArrayList<Integer> al)
{
int value = 0;
for(int i : al)
{
value += i;
}
return value;
}
}
However, I'm looking for something in-built.
Please advise.
EDIT : I have tried the following but I get build errors
import java.util.ArrayList;
public class sumAL
{
public static void main(String[] args)
{
System.out.println(getVersion());
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(3);
al.add(5);
System.out.println(al.stream().mapToInt(Integer::intValue).sum());
}
static double getVersion () {
String version = System.getProperty("java.version");
int pos = version.indexOf('.');
pos = version.indexOf('.', pos+1);
return Double.parseDouble (version.substring (0, pos));
}
}
Errors
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Integer cannot be resolved to a variable
Syntax error on tokens, delete these tokens
You can easily map a Stream<Integer> to an IntStream and then calculate the sum :
a1.stream().mapToInt(Integer::intValue).sum();
al.stream().reduce(0, (x,y) -> x+y)

Java:Local variable may not have been initialized?

Problem: Write a program that reads a list of real numbers. After the program ends it should print out only the unique numbers. That is, only numbers that appear once in the list. If there are more than 50 unique numbers on the list, then you should only print the first 50.
import java.util.*;
import java.io.*;
import java.util.Arrays;
public class Hmwk {
public static void main(String[] args) throws FileNotFoundException {
Scanner input=new Scanner (new File ("input.txt"));
int n = 0;
final int MAX_SIZE = 50;
double[] numbersArray;
while (input.hasNextDouble() && n<MAX_SIZE){
double in = input.nextDouble();
if (inList(in,numbersArray))
numbersArray[n]=in;
n++;
}
printReport(numbersArray);
}
public static boolean inList(double number, double[] list){
for (double i : list) {
if (i == number){
return false;
}
else
return true;
}
}
public static void printReport(double[] list) {
System.out.printf("The unique numbers were", Arrays.toString(list));
}
}
I'm getting errors saying that numbersArray may not have been initialized. I'm also getting an error saying that my boolean method inList must return a type boolean which confuses me because I have two options of returning true or false. Any help is much appreciated.
In fact, your variable
double[] numbersArray;
is not initialized, just declared. You can initialize it as:
double[] numbersArray = new double[MAX_SIZE];
After your comment:
It prints out "The unique numbers were" but thats it, no unique numbers
You're using
System.out.printf("The unique numbers were",Arrays.toString(list));
Two options:
Send a String parameter using %s where you want/need to print the array as string:
System.out.printf("The unique numbers were %s.",Arrays.toString(list));
Use System.out.println
System.out.println("The unique numbers were " + Arrays.toString(list));
public static void main(String[] args) throws FileNotFoundException {
Scanner input=new Scanner (new File ("input.txt"));
int n = 0;
final int MAX_SIZE = 50;
double[] numbersArray; // local variable are initialized at time of declaration
while (input.hasNextDouble() && n<MAX_SIZE){
double in = input.nextDouble();
if (inList(in,numbersArray))
numbersArray[n]=in;
n++;
}
printReport(numbersArray);
}
you have to initialize it like
double[] numbersArray = new double[SIZE];
In both cases you are not account for the fact that you might not end up inside the loop(s).
in your 1st case:
double[] numbersArray;
while (input.hasNextDouble() && n<MAX_SIZE){
double in = input.nextDouble();
if (inList(in,numbersArray))
numbersArray[n]=in;
n++;
}
what if, input does not have double from the get go? if that is the case your numbersArray never initialized. Though in more general terms even if there is a double not initializing your numbersArray will cause an exception.
in your second case:
for (double i : list)
{
if (i == number){
return false;
}
else
return true;
}
if list is empty, then there is no return statement to return from.
Hope that helps
As stated above, you need to initialize numbersArray as shown:
double[] numbersArray = new double[100]; //100 can be replaced with any integer, such as 50, 67, 62152, etc.
Try rewriting inList like this:
public static boolean inList(double number, double[] list){
for (double i : list)
{
if (i == number){
return false;
}
}
return true;
}

Stackoverflow error in counting the minimum number of coins to make the sum S

Here I am working on the following problem where we are given n types of coin denominations of values v(1) > v(2) > ... > v(n) (all integers) The following code tries to find the minimum number of coins that are required to make a sum-C. Here the C is 100(see main function).When I run the code, error--"java.lang.StackOverflowError" comes. Please help.
import java.util.ArrayList;
public class Problem2 {
public static int count=4;
public static int []v={25,10,5,1}; //Array storing denominations
private static int findminimum(ArrayList<Integer> v2) {
int count=v2.get(0);
for(int i=0;i<v2.size();i++)
{
if(count>v2.get(i))
{
count=v2.get(i);
}
}
return count;
}
public static int countmincoins(int n)
{
int t;
if(n<0)
{
t=Integer.MAX_VALUE-100 ;
}
if(n==0)
{
t= 0;
}
else
{
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=0;i<v.length;i++)
{
int temp=0;
temp=countmincoins(n-v[i])+1; //Stackoverflow error
a.add(temp);
}
t=findminimum(a);
}
return t;
}
public static void main(String args[])
{
System.out.println(countmincoins(100));
}
}
If you use recursion then you need to reach a condition to terminate the recursion. But in your code I do not seen any termination logic. Thats why, it get to infinite loop and StackOverflowException. In your code you use following code to terminate.
if(n==0)
{
t= 0;
}
But here n may not be zero. Becuase countmincoins(n-v[i]) do not ensure you to n will be 0.
Your code is infinite cause t will never be <0 or ==0 given that the values in the array and the condition (n - v[i] )+1, v[i] will always return the same value in every call to the method, therefore infinite recursion.
If your not restricted to using recursion the following would be much simpler:
public static int[] denominations = {25,10,5,1};
public static int minimumCoins(int amount){
int total = 0;
for(int denomination: denominations){
while(amount - denomination >= 0){
amount -= denomination;
total++;
}
}
return total;
}
public static void main(String args[])
{
System.out.println(minimumCoins(98));
}

Categories

Resources