Java Average Functions - java

I am new to programming and I am trying to figure out a simple average function. I have written a function to average 3 integers. Now I would like to be able to use any collection class and any number class and get the average. The problem is with these classes you can't use + or / to get the average.
So I am wondering if there are any work-arounds to be able to use these two classes?
here is my first function that works:
package refresh;
import java.util.*;
public class Average {
public static void main( String args[]){
int a, b, c;
float average;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter First Number");
a = scanner.nextInt();
System.out.println("Enter Second Number");
b = scanner.nextInt();
System.out.println("Enter Third Number");
c = scanner.nextInt();
average = (float)(a+b+c)/3;
System.out.println("The Average Is "+average );
}
}
Here what I have so far for my problem:
package refresh;
import java.util.*;
public class Average {
public static void main( String args[]){
Collection numbers;
Number count;
Number average;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Numbers to be averaged");
numbers = (Collection) scanner.match();
count++;
average = numbers/count;
System.out.println("The Average Is "+average);
}
}
Any help would be great! Thanks for your time!

It makes no sense to convert a String into a number (which is what Scanner does) if you don't know what kind of number you're trying to convert it into.
You can represent pretty much any number as a Double. If you need arbitrary precision, use BigDecimal.
The averaging code can be fully generic over the Number interface; just use the doubleValue method. If you need BigDecimal, then it's more complicated and you probably need to do things involving instanceof.

Related

How to make the scanner understand the amount I write?

This is just some homework but I cannot find a way to achieve it like I want. Have a look at my code please.
Once the numbers are typed, I'd just like to play around with them.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//user says if he'd like to use 3 numbers for instance (2,4,5)
System.out.println("How many numbers would you like to use? : ");
int amountOfNumbers = sc.nextInt();
System.out.println("Great! Please type in your numbers: ");
int numbers =sc.nextInt(amountOfNumbers);
// should let him write the amount of numbers he entered
}
Once he has typed the amount of numbers he'd like to use, I would like the scanner to give him the possibility to type in all of those numbers.
Let's say he the amount of numbers he'd like to use is three.
I would like him to be able to type it in the console like this:
First number + enter key
Second number + enter key
Third number + enter key
Not able to write anymore
That is what I meant here by adding "amountOfNumbers" in the scanner itself... (which is not working)
int numbers =sc.nextInt(amountOfNumbers);
BR
Consider a for loop:
for(int i = 0; i < amountofNumbers; i++){
// add to a collection / array / list
}
And then access what you need from there.
import java.util.*;
class EnterNumber{
public void enter_list_function(){
Scanner sc = new Scanner(System.in);
System.out.println("How many numbers would you like to use?");
//Enter the Numbers of amount
int input = sc.nextInt();
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println("Great! Please type in your numbers: ");
//Input - Numbers of amount
for(int j =1; j<=input; j++ ){
int addval = sc.nextInt();
//Add the enter amount in array
list.add(addval);
}
Iterator itr=list.iterator();
while(itr.hasNext()){
//get the enter amount from list
System.out.println(itr.next());
}
}
public static void main(String[] args){
EnterNumber EnterNumber = new EnterNumber();
EnterNumber.enter_list_function();
}
}

Dynamic programming Very large data value

import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner s= new Scanner(System.in);
int t1=s.nextInt();
int t2= s.nextInt();
int n= s.nextInt();
double arr[]= new double[20];
for(int i=0;i<20;i++){
arr[i]=-1;
}
arr[1]= t1;
arr[2]=t2;
if(arr[n]!=-1){
System.out.println((long)arr[n]);
}
else{
for(int i=3;i<=n;i++){
arr[i]= arr[i-2] + Math.pow(arr[i-1],2);
}
System.out.println((long)arr[n]);
}
}
}
This code is a modified Fibonacci series. I want to calculate the tenth digit in this sequence. But the result is very big I want to ask in which type I should cast the answer ? I have used long but it failed...please suggest any other type ...
There's a special type for this kind of computation called BigInteger. Find more infos here.
Edit:
You can create a BigInteger from a String
BigInteger bigInt = new BigInteger("24");
or from an integer type
BigInteger fromInt = BigInteger.valueOf(24);

finding a number that would equalize a set of numbers through addition or subtraction

the user must input a set of numbers of type double that we must then find the number that equalizes the numbers
here is a link to the question
https://www.dropbox.com/s/0hlps5r8anhjjd8/group.jpg
I tried to solve it myself, I did the basics, but for the actual solution I don't even know where to start ?_? any hint would be much helpful
Here my attempt:
import java.util.Scanner;
public class test {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int arr =1000000;
while(arr > 10000) {
System.out.println("enter number of students that are providing the money");
arr = input.nextInt(); //user input for the size of the array
}
double size[] = new double[arr]; //array creation , size based on user input
for (int i =0; i<size.length;i++) { //to input values into the array
System.out.println("enter amount of money");
size[i] = input.nextDouble(); //input values into the array
}
for(int i=0; i<size.length;i++) { //prints out the array
System.out.println(size[i]);
}
}
}
Thank you in advance
Step 1. Read the data for a test case and put it into a suitable structure. I would probably choose a double contribution[] for this assignment.
Step 2. Calculate the average contribution, avg.
Step 3. Sum up the amount of money that need to change hands. sum over abs(contribution[i]-avg). Note: Don't forget to divide the total by 2.

Converting decimal to binary in java having trouble with reversing order

Hey so I'm taking my first cs course ever at my university its taught in java. I'm having trouble converting decimal to binary. I seem to be able to get the correct output but its in reverse order, and I have no idea how to put it in the correct order, here is what I've coded so far,
import java.util.*;
public class lab6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number to convert to binary: ");
int x = input.nextInt();
int y;
String y1="";
while(x!=0){
y=x%2;
x=x/2;
y1 = Integer.toString(y);
System.out.print(y1+" ");
}
}
}
You can store the digits in some container(e.g. ArrayList) and then iterate it back to front printing each digit as you iterate.
It seems you are showing the output in correct order only. But if you want to reverse the current output you can use below code:
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal number to convert to binary: ");
int x = input.nextInt();
int y;
String y1="";
String reverse = "";
while(x!=0){
y=x%2;
x=x/2;
y1 = Integer.toString(y);
// System.out.print(y1+" ");
reverse = y1+" "+reverse;
}
System.out.println("Reverse Order :"+reverse);
For adding to Ivaylo answer, you can also store it in a StringBuilder and reverse it using reverse method.

Issue declaring double two dimensional array

I am writing a program which lets the user put their own size of columns and rows for an array. I am using doubles so that the user can use decimals. However, I am getting this error that is telling me that I cannot convert doubles to integers. I don't understand why. I am using eclipse. I declare the array before the main method so I can use it freely the methods throughout the program.
import java.util.*;
public class array
{
private double themainarray[][];
Scanner input = new Scanner(System.in);
private double columnsize;
private double rowsize;
public static void main(String[] args)
{
System.out.print("Welcome!");
}
//Below on the last line of the method is where I am getting the error from eclipse.
public void arrayDimensions()
{
System.out.println("How many columns would you like?");
columnsize = input.nextDouble();
System.out.println("How many rows would you like?");
rowsize= input.nextDouble();
themainarray= new double [rowsize][columnsize];
}
}
array size variables should be of type int only.Other are not allowed.
In your code rowSize,columnSize should be of type int.
You need an int for sizing an array.
private double themainarray[][];
Scanner input = new Scanner(System.in);
private int columnsize;
private int rowsize;
Then when reading input from the user use nextInt();

Categories

Resources