Java Average of integers - java

i seem to be having trouble figuring out what to set the variable intValue to under the read value methods. The program is supposed to take 10 integers and average them, it works fine as far as catching exceptions and input, but the output displays all the numbers as 0 (because i set it to 0 temporarily but can not figure out what to change it to). Heres the code
package averagenumdriver;
import static java.lang.Integer.parseInt;
import java.util.Scanner;
public class AverageOfIntegers {
//Declare variables
private int numberOfValues;
private int[] integerValues;
private double average;
public AverageOfIntegers(int numberOfValues){
this.numberOfValues = numberOfValues;
}
//Define the readValues()
public void readValues(){
String stringValue = null;
int intValue = 0, i;
Scanner console = null;
i = 0;
integerValues = new int[numberOfValues];
while(i < numberOfValues){
try
{
console = new Scanner(System.in);
System.out.print("Enter value : ");
//read the value
stringValue = console.nextLine();
//check for number
intValue = 0;
parseInt(stringValue);
//Store only integer values
integerValues[i++] = intValue;
}
catch(NumberFormatException ex)
{
//Catch exception and handle it
System.out.println("Invalid Number entered" + "Reenter again ");
continue;
}
}
}
//read integer values
public void printValues()
{
System.out.println("Given values are ");
for (int i = 0; i < numberOfValues; i++)
{
System.out.println("Number: " + (i + 1) + " = " +
integerValues[i]);
}
}
public double getAverage()
{
int sum = 0;
//Calcualte the sum of integer values
for (int i = 0; i < numberOfValues; i++)
{
sum += integerValues[i];
}
//calculate average
average = (double)sum / numberOfValues;
return(average);
}
}
EDIT* question seems to be marked as a duplicate, but I am not asking about why division with two integers where the denominator is greater than numerator yields a 0.

Change
//check for number
intValue = 0;
parseInt(stringValue);
TO
//check for number
intValue = parseInt(stringValue);

Related

What am I missing from my code to meet all the requirements of my program?

I have to design and implement a program that counts the number of integer values from user input. Produce a table listing the values you identify as integers from the input. Provide the sum and average of the numbers.This is what I have so far.
public class Table {
public static void main(String [] strAng) {
int sum = 0;
double average;
int min = 1;
int max = 10;
for(int number = min;
number <= max; ++number) {
sum += number;
}
System.out.print("Sum:" +sum);
System.out.print("Average:" +average);
You have not get an input from user and also you do nothing to make average.
Try this code, and if you have other requirements, update the question.
int sum = 0;
double average;
Scanner userInputScanner = new Scanner(System.in);
System.out.println("Please enter the integers with space between each two integer: ");
String inputNumberFilePath = userInputScanner.nextLine();
String[] numStrArray = inputNumberFilePath.split(" ");
for (String string : numStrArray) {
sum += Integer.parseInt(string);
}
average = (double) sum / (double) numStrArray.length;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
output sample:
Please enter the integers with space between each two integer:
10 20 30 40 50
Sum: 150
Average: 30.0
Im not sure if this is exactly what you are looking for but it could be. With this code you enter a string with integers "in it". The integers get extracted, counted and have sum & average operations performed on what is basically a bar graph. Hope this helps.
import java.util.*;
public class Table {
This part is used to read ANY user input Strings included.
public static String getInput(){
String outPut = "";
System.out.println("Type something to parse: ");
Scanner sc = new Scanner(System.in);
if(sc.hasNextLine()) {
outPut = sc.nextLine();
}
return outPut;
}
Here we build our "bar graph":
public static Map<Long,Integer> makeTable(String input){
Map<Long,Integer> table = new HashMap<>();
long in = Long.parseLong(input);
long lastDig = 0;
int count = 1;
while(in > 0){
lastDig = in % 10;
in /= 10;
if(!table.containsKey(lastDig)) {
table.put(lastDig, count);
} else {
table.replace(lastDig,count,count+1);
}
}
return table;
}
Here we calculate the sum:
public static int sum(Map<Long,Integer> table){
int sum = 0;
for (Long key: table.keySet()
) {
sum += (key*table.get(key));
}
return sum;
}
Here we get our average:
public static int average(Map<Long,Integer> table){
int sum = 0;
int divisor = 0;
for (Long key: table.keySet()
) {
sum += (key*table.get(key));
divisor += table.get(key);
}
return sum/divisor;
}
public static void main(String[] args){
int sum = 0;
double average = 0;
String input = "";
input = getInput();
System.out.println("Unsanitized In: " + input);
Here the integer digits are extracted!
input = input.replaceAll("[^\\d.]","");
Long.parseLong(input);
System.out.println("Sanitized In: " + input);
Map<Long,Integer> myMap = makeTable(input);
System.out.println(myMap);
System.out.println("Sum:" +sum(myMap));
System.out.print("Average:" + average(myMap));
}
}
Our example output for: asdf45313ha is:
Unsanitized In: asdf45313ha
Sanitized In: 45313
{1=1, 3=2, 4=1, 5=1}
Sum:16
Average:3

How do I computer average into a method?

I'm attempting to call a method in order to calculate average (calcavgnow).. I'm trying to have it calculate the average of all the numbers in the array and return the average to the caller. I'm hoping it can deal with any size array. I tried attempting below.. can anyone help me figure out what I am doing wrong?
import javax.swing.JOptionPane;
public class sdasfs {
public static void main(String[] args) {
double total = 0;
double SelectNumber = 0;
int a = 0;
double calcavgnow = 0;
do {
try {
String UserInput = JOptionPane.showInputDialog("Enter the amount of numbers you would like to average");
SelectNumber = Integer.parseInt(UserInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Value must be an integer!");
}
} while (SelectNumber < 1);
double Numbers[] = new double[(int) SelectNumber];
for (a = 0; a < Numbers.length; a++) {
String EnterNumber = JOptionPane.showInputDialog("Please enter a number.");
Numbers[a] = Double.parseDouble(EnterNumber);
total += Numbers[a];
calcavgnow = total / SelectNumber;
}
JOptionPane.showMessageDialog(null, getTotal(numbers) + " divided by " + Numbers.length + " is " + getAvg(Numbers));
}
//Create method in order to calculate calcavgnow
public static double getAvg(int numbers[]){
return (double)getTotal(numbers)/numbers.length;
}
public static int getTotal(int numbers[]){
int total = 0;
for(int i:numbers)
total +=i;
return total;
}
}// end class
Have a separate method to calculate average. Don't do everything inside the same method. Learn to modularize your code. So others can easily get adopt to your code.
public static double getAvg(double numbers[]){
return getTotal(numbers)/numbers.length;
}
public static double getTotal(double numbers[]){
double total = 0;
for(double i:numbers)
total +=i;
return total;
}
import javax.swing.JOptionPane;
public class AvgCalculator {
public static void main(String[] args) {
double total = 0;
double SelectNumber = 0;
int a = 0;
double calcavgnow = 0;
do {
try {
String UserInput = JOptionPane.showInputDialog("Enter the amount of numbers you would like to average");
SelectNumber = Integer.parseInt(UserInput);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Value must be an integer!");
}
} while (SelectNumber < 1);
double Numbers[] = new double[(int) SelectNumber];
for (a = 0; a < Numbers.length; a++) {
String EnterNumber = JOptionPane.showInputDialog("Please enter a number.");
Numbers[a] = Double.parseDouble(EnterNumber);
total += Numbers[a];
}
calcavgnow = total / SelectNumber;
JOptionPane.showMessageDialog(null, "The average entered is " + calcavgnow);
}
}

Finding an average of a loop from a different method?

I am in the middle of an exercise on arrays and I am currently stuck on one of the variations in which
I have to use an Array (no arraylists) to gather user input with a
max number of 100 inputs and the inputs must stop if a negative
number is inserted.
The program then prints each value input by the user on a separate
line with the "Above", "Below", or "EqualTo" relating to the average
of the inputs.
Issue :- I am currently stuck in how I am supposed to get the value of the inputs from the load method into the correct spots on the print method. The program will compile but will only return an average1 equal to zero. Any help is appreciated, I just can't use an arraylist
import java.util.Scanner;
public class ScoreSetNumber3
{
private int[] scores;
private static final int SIZE= 100;
private double average1;
Scanner keyboard = new Scanner(System.in);
public ScoreSetNumber3()
{
scores = new int[SIZE];
}
public void load()
{
System.out.println("Please enter scores");
double sum = 0;
for( int used = 0; used < scores.length; used++)
{
scores[used] = keyboard.nextInt();
if(scores[used] >= 0)
{
sum += scores[used];
}
else
{
System.out.println("End of Inputs");
double average1 = sum / used;
System.out.println("Average value of array elements is" + " " + average1);
break;
}
}
}
public double getAverage()
{
return average1;
}
public void print()
{
for(int used=0; used < scores.length; used++)
{
if(scores[used] > getAverage())
{
System.out.println(scores[used] + " Above");
}
else if(scores[used] == getAverage())
{
System.out.println(scores[used] + " EqualTo");
}
else
{
if(scores[used] < 0)
{
break;
}
System.out.println(scores[used] + " Below");
}
}
}
}
That's because you are not saving the average to the global variable average1 but to a local variable. That is why average1 returned by getAverage() equal to zero.
Change the below line in load() method from
double average1 = sum / used;
to
average1 = sum / used;

Im getting a null pointer exception in my array

I'm getting a null pointer exception whenever I enter a value to be added at that point in my int[] array and I'm uncertain where I should go from here or if another array is necessary. Any help would be greatly appreciated.
import java.util.Scanner;
public class Range
{
private int[] range;
private int begin,end,falseLoop,numInts,count;
Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
Range r = new Range();
r.getRange();
r.getAmount();
r.getInts();
//r.printAll();
}
private void getRange()
{
System.out.println("Please enter the first number in the range you would like to use: ");
begin = scan.nextInt();
System.out.println("Please enter the second number in the range you would like to use: ");
end = scan.nextInt();
falseLoop = end;
int[] range = new int[(Math.abs(begin) + Math.abs(end))];
for(int x = 0; x < range.length; x++)
{
range[x] = 0;
}
}
private void getAmount()
{
System.out.println("Please enter the amount of integers you would like to enter "
+ "in the range of " + begin + " to " + end);
numInts = scan.nextInt();
}
private void getInts()
{
for(int y = 0; y < numInts; y++)
{
System.out.println("Please enter an integer: ");
range[scan.nextInt()]++;
}
}
private void printAll()
{
for(int i = 0; i < range.length; i++)
{
System.out.println("Value: " + falseLoop + "equals: " + range[i]);
falseLoop++;
}
}
}
You're shadowing your class variable inside of getRange.
int[] range = new int[(Math.abs(begin) + Math.abs(end))];
Should actually be:
range = new int[(Math.abs(begin) + Math.abs(end))];
You get null pointers because you've declared an array, but nothing's been allocated for it.
Don't understand statement from your code
ragne[x] = new int[0];
You are here trying to assign array of integer to a integer variable. Like
integer = integerArray;

decimal to binary in java

I'm having trouble in getting the binary. I do not know what's wrong. The binary number always ends up in gibberish. Also some parts like the new int[31] thing was from HW but I can't get around to make print the actual binary.
public class DectoBinary {
public static void main(String[]args) {
Scanner CONSOLE = new Scanner(System.in);
System.out.print("Please enter a nonnegative integer: ");
int value = CONSOLE.nextInt();
while (value < 0) {
System.out.print("number outside range.");
System.out.print
("Please enter a nonnegative interger more than 0: ");
value = CONSOLE.nextInt();
}
int[] intArray = new int[31];
decimalToBinary(value, intArray);
System.out.println(value + "" + intArray);
}
public static int[] decimalToBinary(int value, int[]intArray) {
int i = 0;
while (value != 0) {
if (value % 2 == 1)
intArray[i] = 1;
else
intArray[i] = 0;
value /= 2;
i++;
}
return intArray;
}
}
I think the error is on this line:
System.out.println(value + "" + intArray);
You cannot print an array of integers like this: you should either convert it to string, or write a loop that prints the array digit by digit:
for (int i : inrArray) {
System.out.print(intArray[i]);
}
System.out.println();
You do not need to pass in the output array as well: you can create it inside the function.
public static int[] decimalToBinary(int value) {
int count = 1;
int tmp = value;
while (tmp != 0) {
tmp /= 2;
count++;
}
int[] intArray = new int[count];
// Do the conversion here...
return intArray;
}
You can simply use Integer.toBinaryString(int).
Actually the is a very simple way to get binary numbers in java using BigInteger
public String dectoBin(int num){
String s = ""+num;
BigInteger bi = new BigInteger(s);
String bin = bi.toString(2);
return bin
}
BigInteger.toString(2) returns the number stored on the numerical base specified inside the parenthesis. Is a very easy way to get arround this problems.
System.out.println(value + "" + intArray);
the 'intArray' is a arrays's address, so, if you want to get actual binary you can use Arrays.toString(intArray)
As dasblinkenlight you need to print the array item by item. If you want a nice alternative, you can use a recursive printing of value mod 2 (modulo 2 gives you 1 or 0)
/** print directly*/
public static void decimalToBinary(int value) {
if(value > 1){
System.out.print(decimalToBinary(value/2) + "" + (value%2));
/**recursion with implicit cast to string*/
} else {
System.out.print( (value==0)?"":"1");
}
}
It works with any Base
Well actually to print the array, because all the slots in the array are initialized at 0 you need to detect where the first one begins, so.
you need to replace
System.out.println(value + "" + intArray);
with something like this;
System.out.println(vale + " ");
boolean sw = false;
for(int i=0;i<intArray.length;i++){
if(!sw)
sw = (intArray[i]==1);//This will detect when the first 1 appears
if(sw)
System.out.println(intArray[1]); //This will print when the sw changes to true everything that comes after
}
Here is a program to convert Decimal nos. into Binary.
import java.util.Scanner;
public class decimalToBinary {
static int howManyTerms (int n) {
int term = 0;
while (n != 0) {
term ++;
n /= 2;
}
return term;
}
static String revArrayofBin2Str (int[] Array) {
String ret = "";
for (int i = Array.length-1; i >= 0; i--)
ret += Integer.toString(Array[i]);
return ret;
}
public static void main (String[] args) {
Scanner sc=new Scanner (System.in);
System.out.print ("Enter any no.: ");
int num = sc.nextInt();
int[] bin = new int[howManyTerms (num)];
int dup = num, el = -1;
while (dup != 0) {
int rem = dup % 2;
bin [++el] = rem;
dup /= 2;
}
String d2b = revArrayofBin2Str(bin);
System.out.println("Binary of " + num + " is: " + d2b);
}
}
This is simple java code for decimal to binary using only primitive type int, hopefully it should help beginners.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DtoB {
public static void main(String[] args) {
try { // for Exception handling of taking input from user.
System.out.println("Please enter a number");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
int x = Integer.parseInt(input);
int bin = 0;
int p = 1;
while (x > 0) {
int r = x % 2;
bin = (r * p) + bin;
x = x / 2;
p *= 10;
}
System.out.println("Binary of " + input + " is = " + bin);
} catch (Exception e) {
System.out.println("Please enter a valid decimal number.");
System.exit(1);
e.printStackTrace();
}
}
}

Categories