Integer to Double variable - java

I need to create a program that will prompt the user to enter salaries and get the highest and lowest salaries.. Ive been working on it for 4 days now.. and I finally created my program using some of the tutorials on the internet but I only have one problem... I just can't convert the INT to Double ## its giving me a headache.. where did I go wrong? can someone help me? I need to pass java class ;;
here's the code:
import java.util.*;
public class HighestLowestSalary
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many salary do you want to enter?: ");
int sal = input.nextInt();
//starting here should be double already..
System.out.println("Enter the "+sal +" salaries");
int[]salary = new int[sal];
for (int i=0; i<sal; i++)
{
salary[i]=input.nextInt();
}
System.out.println("The Highest Salary is: " +high(salary));
System.out.println("The Lowest Salary is: " +low(salary));
}
public static int high(int[] numbers)
{
int highsal = numbers[0];
for (int i=1; i<numbers.length;i++){
if (numbers[i] > highsal){
highsal = numbers[i];
}
}
return highsal;
}
public static int low(int[] numbers){
int lowsal = numbers[0];
for (int i=1;i<numbers.length;i++){
if (numbers[i] < lowsal){
lowsal = numbers[i];
}
}
return lowsal;
}
}
anyone who can help me and teach me how to convert it in double? thank you in advance..

Erm ... to convert an int to a double you can just assign it. The assignment will cause a a "primitive widening conversion" to occur; see JLS 5.1.2.
int myInt = 42;
double myDouble = myInt; // converts to a double.
(No typecast is necessary for a primitive widening conversion ... though adding one does not harm.)
To convert an int array to a double array ....
int[] myInts = ....
double[] myDoubles = new double[myInts.length];
for (int i = 0; i < myInts.length; i++) {
myDoubles[i] = myInts[i];
}

You could just assign an int value to double like:
int n = 1;
double j = n;
System.out.println(j);
Output:
1.0
Note: you could ask for salary to be of double type by using nextDouble api instead of nextInt

I was able to solve the problem because of your help! here is what I did.. like everyone said to convert int to Double
//this is where I changed all the int to double
System.out.println("Enter the "+sal +" salaries");
double[]salary = new double[sal];
for (int i = 0; i<sal; i++){
salary[i] = input.nextDouble();
}
System.out.println("The Highest Salary is: " +high(salary));
System.out.println("The Lowest Salary is: " +low(salary));
}
public static double high(double[] numbers)
{
double highsal = numbers[0];
for (int i=1; i<numbers.length;i++){
if (numbers[i] > highsal){
highsal = numbers[i];
}
}
return highsal;
}
public static double low(double[] numbers){
double lowsal = numbers[0];
for (int i=1;i<numbers.length;i++){
if (numbers[i] < lowsal){
lowsal = numbers[i];
}
}
return lowsal;
}
}

Related

Print the smallest number in java

I need to take the user input and get the program to run it through all the methods and stuff to output the largest and smallest number. I got it to print the largest, but it always has the smallest at 0. This is probably simple to fix, but It's the end of the quarter and i'm stressing to get this last one done. Here is my code.
import java.io.*;
import java.util.*;
public class P4_6
{
private int sum;
private int count;
private int largest = Integer.MIN_VALUE;
private int smallest = Integer.MAX_VALUE;
public P4_6()
{
sum = 0;
largest = 0;
smallest = 0;
count = 0;
}
public void addValue(int x)
{
smallest = Math.min(smallest, x);
largest = Math.max(largest, x);
sum = sum + x;
count++;
}
public int getSum()
{
return sum;
}
public int getLargest()
{
return largest;
}
public int getSmallest()
{
return smallest;
}
public static void main(String[] args)
{
Scanner kbreader = new Scanner(System.in);
System.out.println("Enter your first integer: ");
int num1 = kbreader.nextInt();
System.out.println("Enter your second integer: ");
int num2 = kbreader.nextInt();
System.out.println("Enter your third integer: ");
int num3 = kbreader.nextInt();
System.out.println("Enter your fourth integer: ");
int num4 = kbreader.nextInt();
P4_6 data = new P4_6();
data.addValue(num1);
data.addValue(num2);
data.addValue(num3);
data.addValue(num4);
System.out.println("The largest was " + data.getLargest());
System.out.println("The smallest was " + data.getSmallest());
}
}
You do not need to use No-argument Constructor. Java compiler by default add No-argument Constructor . You can remove the below part.
public P4_6()
{
sum = 0;
largest = 0;
smallest = 0;
count = 0;
}
if you want to keep this part in your code then you should initialize your variable like below
public P4_6()
{
sum = 0;
largest = Integer.MIN_VALUE;
smallest = Integer.MAX_VALUE;
count = 0;
}
You don't need to initialise the 'smallest' and 'largest'. Just remove them
public Test()
{
sum = 0;
//largest = 0;
//smallest = 0;
count = 0;
}

ArrayIndexOutOfBoundsException computing the average

I'm working on this book by Randall S. Fairman, 3D Astronomy with Java, having limited experience with Java myself. He uses this LineReader class instead of Scanner or anything to take user input. The exercise I'm stuck on asks you to use LineReader to get values for an array and find the average of the values in the array. This is what I came up with, doing my best, and it doesn't work. When I try to run it, it says
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Average.main(Average.java:10)
Code:
import ui.LineReader;
public class Average {
public static void main(String[] args) {
int average;
int sum = 0;
for (int j = 0; j < 5; j++) {
int i = LineReader.queryInt("Give me a number: ");
int [] M = new int [i];
sum = sum + M[i];
}
average = sum/5;
System.out.println("The average of those numbers is " +average);
}
}
You don't need the int[]M = new int[i]; line.
Just do sum += i;
Your updated code:
import ui.LineReader;
public class Average {
public static void main(String[] args) {
int average;
int sum = 0;
for (int j = 0; j < 5; j++) {
int i = LineReader.queryInt("Give me a number: ");
sum += i;
}
average = sum/5;
System.out.println("The average of those numbers is " +average);
}
}

possible lossy conversion from double to int

Write a program that contains two overloaded methods that return the average of an array with the following headers:
public static int average(int[] array)
public static double average(double[] array)
my program contains the errors
list2[i] = sc.nextDouble(); // possible lossy conversion from double to int
return average; // possible lossy conversion from double to int
not sure what the problem is I have declared within my methods what needs to be declared I don't know why my double in put would give me that error
import java.util.Scanner;
public class Lab7A {
public static void Main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter 10 Integer values: ");
int list[] = new int[10];
for (int i = 0; i < list.length; i++) {
list[i] = sc.nextInt();
}
double avg1 = average(list);
System.out.println("Average of First Array: " + avg1);
System.out.println();
System.out.print("Enter Ten Double Values: ");
double list2[] = new double[10];
for (double i = 0; i < list2.length; i++) {
list2[i] = sc.nextDouble();
}
double avg2 = average(list2);
System.out.println("Average of Second Array: " + avg2);
System.out.println();
}
public static int average(int[] list) {
double average = 0;
double total = 0;
for (int i = 0; i < list.length; i++) {
total = total + list[i];
}
average = total / list.length;
return average;
}
public static double average(double[] list2) {
double average = 0;
double total = 0;
for (int i = 0; i < list2.length; i++) {
total = total + list2[i];
}
average = total / list2.length;
return average;
}
}
Your average(double[]) method is attempting to use a double as an array index, but Java only allows ints as an array index. This is the source of the "possible lossy conversion from double to int".
Everything else is and should be double, but declare your index d as int to remove this error.
Additionally, in the for loop of that method, the condition should be d < list2.length instead of d < 5.
Also, the average of int values may not necessarily be an int. In your average(int[]) method, declare it to return a double, and declare average to be a double. The variable avg1 will need to be a double in main also.

Not ignoring a value?

import java.util.Scanner;
import java.util.Arrays;
public class Improved {
//I resize the array here so that it only counts inputs from the user
//I want to ignore the 0 input from the user
//I think the error happens here or in my main method
public static double[] resizeArray(double[] numbers, double size) {
double[] result = new double[(int)size];
for (int i = 0; i < Math.min(numbers.length, size); ++i) {
result[i] = numbers[i];
}
return result;
}
//compute average nothing is wrong here
public static double getAverage( double[] numbers) {
double sum = 0;
for (int i = 0; i < numbers.length; ++i)
sum += numbers[i];
double average = sum/numbers.length;
return average;
}
//SD nothing is wrong here
public static double getSD( double[] numbers, double average) {
double sd = 0;
for ( int i = 0; i < numbers.length; ++i)
sd += ((numbers[i] - average)*(numbers[i] - average)/ numbers.length);
double standDev = Math.sqrt(sd);
return standDev;
}
//maximum nothing is wrong here
public static double getMax( double[] numbers) {
double max = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] > max){
max = numbers[i];
}
return max;
}
//minimum nothing is wrong here
public static double getMin( double[] numbers) {
double min = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] < min) {
min = numbers[i];
}
return min;
}
//median value nothing is wrong here
public static double getmed( double[] numbers) {
double median;
if (numbers.length % 2 == 0)
median = (((numbers[numbers.length/2 - 1])
+ (numbers[numbers.length/2]))/2);
else
median = numbers[numbers.length/2];
return median;
}
//the problem is in the main method i think or in the call method to resize
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] statArr = new double[99];
double size = 0;
int i = 0;
System.out.println("Type your numbers: ");
double number = input.nextDouble();
//I don't want the zero in the array, I want it to be excluded
while (number != 0){
statArr[i] = number;
i++;
number = input.nextDouble();
++size;
if ( size == statArr.length) {
statArr = resizeArray(statArr, statArr.length * 2);
}
++size;
}
statArr = resizeArray(statArr, size);
java.util.Arrays.sort(statArr);
double average = getAverage(statArr);
System.out.println( "The average is " + getAverage(statArr));
System.out.println( "The standard deviation is " + getSD(statArr, average));
System.out.println( "The maximum is " + getMax(statArr));
System.out.println( "The minimum is " + getMin(statArr));
}
}
// I don't have any concerns with computing the math parts, but I can't seem to make it so my array ignores the 0 that ends the while loop. In other words, I want every number included up until the user enters the number 0. Everything else is right. Thank you very much!
You have ++size twice. This means your resizeArray method won't work correctly:
double[] result = new double[(int)size];
Here you're allocating more than what you actually want. This is why you're getting zeroes in your array. Java arrays are initialized to 0 (in case of numeric primitive types).
As Giodude already commented, I suggest you using List implementations (typically ArrayList) instead of arrays everytime you can.
Also size could be declared as int altogether and avoid that cast (and save some extremely slight memory), you're not using it as a double anywhere.

Finding the average of a column in a matrix with unknown elements

Can anyone help me with my code? I have to find the average of every column in a matrix but I don't know what's wrong with my code cause it doesn't work.This is my code: (By the way it shows no mistakes and I had to put the numbers with JOptionPane, thanks for your help)
import javax.swing.JOptionPane;
public class Matrix {
private static final int String = 0;
public static void main(String[] args) {
double[] numbers = new double[10]; // 10 doubles
double sum = 0.0;
for (int i = 0; i < numbers.length; ++i) {
sum += numbers[i];
String input = JOptionPane.showInputDialog("Enter a number");
double d = Double.parseDouble(input);
double avg = 0.0;
avg = sum/numbers[i];
}
}
}
You never assign any numbers to your numbers array, so they all default to 0.
Try:
numbers[i] = Double.parseDouble(input);
double avg = 0.0;
sum += numbers[i];
avg = sum / (i + 1); // (i + 1) is the number of inputted numbers

Categories