How to divide doubles in an array in java? - java

I have in array with some doubles in them. I want to divide them, for example with an array that contains 6.0, 3.0 and 2,0 the result should be 1 (6/3/2). I wrote the following code:
System.out.print("How many numbers do you want to divide? ");
int division = input.nextInt();
double[] divisionArray = new double[division];
for(int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
}
for(int k = 0; k < division; k ++) {
double resultDivision = divisionArray[k] / divisionArray[k + 1];
}
System.out.println("Result: " + resultDivision);
but that doesn't seem to work. I get the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 I'm a complete java beginner. Could anyone help me out? Thanks

Your code has three issues.
resultDivision is defined within the scope of the for loop, so it's not visible afterwards, when you print the result.
With #1 fixed, you'll get an ArrayOutOfBounds exception because the second for loop tries to access divisionArray[k+1].
You don't check the arguments that the user gives you. What if a user specifies that it wants to divide -5 numbers? Your code will try to create an array with a length of -5, causing an Exception. Also, What if a user wants to divide by zero? Are you fine with that?
Here's a slightly better version:
Scanner input = new Scanner(System.in);
int division = 0;
do {
System.out.print("How many numbers do you want to divide? ");
division = input.nextInt();
} while (division <= 0);
double[] divisionArray = new double[division];
for (int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
if (divisionArray[i] == 0 && i>0) { // Remove this if you want to allow the user to divide by zero. Entering zero as the first argument is legal
System.out.println("Zero is an illegal argument, please enter a different number");
i--;
}
}
double resultDivision = divisionArray[0];
for (int k = 1; k < division; k++) {
resultDivision = resultDivision / divisionArray[k];
}
System.out.println("Result: " + resultDivision);
Good luck.

this should work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many numbers do you want to divide? ");
int division = input.nextInt();
double[] divisionArray = new double[division];
for(int i = 0; i < division; i++) {
System.out.print("Enter your " + (i + 1) + ". number: ");
divisionArray[i] = input.nextDouble();
}
//remember the first value and divide it trough the second,
//third, fourth and so on...
double result = divisionArray[0];
for(int k = 1; k < division; k ++) {
result = result / divisionArray[k];
}
System.out.println("Result: " + result);
}

Related

How do I make a calculator that multiplies more than two numbers?

I made a calculator that does multiple things (adding consecutive numbers, adding multiple numbers, etc) but I am having trouble making it so that the calculator can multiply multiple numbers. So far, I've basically copied the code that adds multiple numbers, but I can't figure out how to make it multiply instead of add.
Here is my code:
import java.util.Scanner;
public class SumOfNumbers {
public static void main(String arg[])
{
int n;
int sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Please enter how many numbers you want to add up to: ");
n = s.nextInt();
System.out.println("you entered: " + n + "");
sum = addConsecutiveNumbers(n);
System.out.println("sum of 1 to "+n+" = "+sum);
//following code is sum of any numbers you entered from console
//store the numbers into an array
int num;
int sumOfNums=0;
System.out.print("Please enter how many numbers you want to sum: ");
num=s.nextInt();
System.out.println("you want to sum "+num+" numbers ");
sumOfNums = addNumbers(num);
System.out.println("sum of "+num+" numbers = "+sumOfNums);
}
//Define a method which add consecutive numbers based on user's input and return the sum of the numbers
private static int addConsecutiveNumbers (int number)
{
int sum = 0;
for (int i = 1; i <= number; i++)
{
sum = sum + i;
}
return sum;
}
//Define a method which add numbers based on user's input and return the sum of the numbers
private static int addNumbers (int num)
{
Scanner s = new Scanner(System.in);
int a[] = new int[num];
int sumOfNums = 0;
for(int k = 0; k < num; k++)
{
System.out.println("enter number "+(k+1)+":");
a[k] = s.nextInt();
System.out.println("The array of a[" + k + "] = " + a[k]);
}
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
return sumOfNums;
}
//below is the part of code that I am having trouble with.
public static int multiplyNumbers(int num)
{
int Area = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[num];
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
for(int l = 0; l < num; l++)
{
System.out.println("enter number "+(l+1)+":");
a[l] = s.nextInt();
System.out.println("The array of a[" + l + "] = " + a[l]);
}
return Area;
}
}
I see one thing right away; The way I see your code, the following two lines a redundant:
System.out.println("Please enter how many numbers you want to multiply:");
num=s.nextInt();
You should have already asked the user how many numbers they want to multiply, because it's passed in as a parameter. As for your actual problem, take a look at these lines from the addNumbers() method:
for(int j = 1;j < num ; j++)
{
sumOfNums += a[j];
}
All you gotta do is copy that code in right before your return statement (return Area;). You'll need to tweak it a bit so instead of using the sumOfNums variable, it uses the Area variable, and instead of adding, it multiplies. This can be done like so:
for(int j = 0;j < num ; j++) //j also needs to start at 0, I think you may have made a mistake when writing the summing method
{
Area *= a[j];
}
You'll notice there's an issue with this algorithm though (almost didn't catch it myself). Area starts off with a value of 0, so 0 multiplied by any number will always still be 0. Simple fix; just manually set Area to the first value before the loop. Something like this:
Area = a[0];
for(int j = 1; j < num; j++)
{
sumOfNums += a[j];
}
Also notice I started the for loop at j = 1 this time. This is because I already started Area as a[0], so we don't want to multiply that number twice.
You don't need to store values in an array for multiplication similarly for addition you can directly update the final result
public static int multiplyNumbers(int num) {
int Area = 1;
Scanner s = new Scanner(System.in);
System.out.println("Please enter how many numbers you want to multiply:");
num = s.nextInt();
for (int l = 0; l < num; l++) {
System.out.println("enter number " + (l + 1) + ":");
int temp = s.nextInt();
Area *= temp;
System.out.println("The array of a[" + l + "] = " + temp);
}
return Area;
}

Looping in Java and getting the sum without using any buitin function

I have a problem which I am trying to solve. The work is like:
The user will input a number say 5 and the output will be
Output:
5 55 555 5555 55555
sum: 61725
Another example,
Input: 4
Output:
4 44 444 4444
sum: 4936
I have displayed the series but can't do the sum.
Scanner input = new Scanner(System.in);
System.out.print("Input: ");
int in = input.nextInt();
int sum = 0;
System.out.println("Output: ");
for(int i=1;i<=in;i++){
for(int j=0;j<i;j++){
System.out.print(in);
}
System.out.print(" ");
}
this will print the series. You can change the whole code, no problem. Just CAN'T use any builtin function like Math.pow() etc.
I was thinking of using :
for(int a=1;a<=in;a++){
f=f*10+in; sum+=f;
}
int in = ...
int sum = 0;
int term = in;
for (int i = 0; i < in; i++) {
sum += term;
term = 10 * term + in;
}
The point is that you can compute the series 4, 44, 444, ... by simple arithmetic and a loop.
But note that this will break for large values of in for two reasons.
Challenge: See if you can figure out what they are!
You can use String#repeat function and parse it to integer. At every loop you would have to append it to sum:
sum = sum + Integer.valueOf(("" + in).repeat(in));
Without using ANY build-in functions, we have to notice, that in the sum in appears in times, 10 * in - (in - 1) times and so on (sum = in * in + 10 * in * (in - 1) + ...), hence you can use the following loop:
int sum = 0;
int currentIn = in;
for(int i = 0; i < in; i++) {
sum = sum + (in - i) * currentIn;
currentIn = currentIn * 10;
}
System.out.println(sum);
Notice this does it with single loop.
isnt it rather simple?
Scanner input = new Scanner(System.in);
System.out.print("Input: ");
int in = input.nextInt();
int sum = 0;
int product=1;
System.out.println("Output: ");
for(int i=1;i<=in;i++){
for(int j=0,prod=in;j<i;j++){
System.out.print(in);
prod=(j>0)?(prod*10)+in:prod;
}
sum+=prod;
System.out.print(" ");
}
System.out.println("sum: "+sum);
Try the below implementation:
long sum = 0;
String num;
for(int i=1;i<=in;i++){
num = ""; //re-initialize number
for(int j=0;j<i;j++){
num += in; //keep track of every individual number
System.out.print(in);
}
System.out.print(" ");
//sum up each number after space
sum += Integer.parseInt(num);
}
System.out.print("sum: " + sum);

Alternating signs + loops

I'm supposed to recreate this code
public static void main(String[] args) {
// TODO, add your application code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = keyboard.nextInt();
double x = 0;
System.out.print("The total is: ");
for (int i = 1; i <= n; i++){
x = x+-(1.0/i);
}
System.out.print(+x);
}
But with alternating signs in the loop (1 – 1/2 + 1/3 – 1/4 + 1/5 – 1/6 + ... + 1/N) and have it print out the value (Enter an integer: 5
The total is: 0.7833333333333332)
I was wondering how I could do this? I was able to write the original code, but I am unaware as to how I could replicate the code but with alternating signs.
public static void main(String[] args) {
// TODO, add your application code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = keyboard.nextInt();
double x = 0;
System.out.print("The total is: ");
for (int i = 1; i <= n; i++){
if(i%2==0){ //even
x = x-(1.0/i);
}
else{ //odd
x = x+(1.0/i);
}
}
System.out.print(+x);
}
This may be what you are trying to do. The important change is the if(i%2==0) logic - Here I use it as a way of alternating on the different iterations of the for loop based on whether i is even or odd.
Hope this helps, feel free to ask any questions
double s = -1; // Sign factor
for (int i = 1; i <= n; i++) {
s = -s;
x += s/i;
}
Change x = x+-(1.0/i); to x -= Math.pow(-1,i)/i;. That should do the trick.

Novice java code about sorting numbers

This is the code I was working on in class. I would be asking my teacher but today is a sunday.
okay straight off the bat, I need to sort through some numbers and find the highest number and the lowest.
So what works and what doesn't?
The code finds the highest number under the variable of iMax. With the tweaking of a new variable name iMin, and a < (lesser sign) it should be giving me the lowest number found but it doesn't and that's the problem. Instead its telling me 0.0 and that is not one of the many random numbers I could choose. To put it plainly, the numbers 1000,2000,3000,4000,5000. it tells me 5000 is the highest number and 0.0 was the lowest. 0.0 was not one of my numbers and I have scratched my head for too long, please help me with this problem as it is driving me up the wall. So here's the code:
import java.util.Scanner;
public class JustWork {
public static void main(String[] args) {
double [] run1 = new double[7];
double iMax = run1[0];
double iMin = run1[0];
Scanner input = new Scanner(System.in);
for (int i = 0; i<run1.length; i++)
{
System.out.println("Score from Judge " + (i+1) + ": ");
run1[i] = input.nextDouble();
}
for (int i = 1; i<run1.length; i++)
{ if (run1[i]< iMin)
iMin = run1[i];
}
for (int i = 1; i<run1.length; i++)
{ if (run1[i]> iMax)
iMax = run1[i];
}
System.out.println("the minimum score is: " + iMin);
System.out.println("the maximum score is: " + iMax);
}
}
For example, if I put in the following numbers:3,4,5,6,7,8,9 System.out.prints out this:
Score from Judge 1:
3
Score from Judge 2:
4
Score from Judge 3:
5
Score from Judge 4:
6
Score from Judge 5:
7
Score from Judge 6:
8
Score from Judge 7:
9
the minimum score is: 0.0
the maximum score is: 9.0
When you initialize the double array, they are by default assigned 0s for each element.Then when you assign run1[0] to iMin and iMax, you have already set 0 as min implicitly.
To avaoid that, just assign the initial values after getting the input
public static void main(String[] args) {
double [] run1 = new double[7];
Scanner input = new Scanner(System.in);
for (int i = 0; i<run1.length; i++)
{
System.out.println("Score from Judge " + (i+1) + ": ");
run1[i] = input.nextDouble();
}
double iMax = run1[0];
double iMin = run1[0];
for (int i = 1; i<run1.length; i++)
{ if (run1[i]< iMin)
iMin = run1[i];
}
for (int i = 1; i<run1.length; i++)
{ if (run1[i]> iMax)
iMax = run1[i];
}
System.out.println("the minimum score is: " + iMin);
System.out.println("the maximum score is: " + iMax);
}
Initialize iMin and iMax after your first for loop. When you initialize before, then the values are 0.
double [] run1 = new double[7]; // <-- an array of 7 elements, all 0.0
// double iMax = run1[0]; // <-- 0.0
// double iMin = run1[0]; // <-- 0.0
Scanner input = new Scanner(System.in);
for (int i = 0; i < run1.length; i++)
{
System.out.println("Score from Judge " + (i+1) + ": ");
run1[i] = input.nextDouble();
}
double iMax = run1[0];
double iMin = run1[0];

Sum of all integers defined by user that are divisible by 5

What is not working is the sum part. Its not equaling the right number. Ex: user puts in 25 so the sum should be 75, but the program prints out 50.
My code:
import java.util.Scanner;
public class SumH4
{
public static void main(String[] args)
{
//define data
int x;
int sum;
//scanner is needed
Scanner sc = new Scanner(System.in);
//get user data and initialize variables
System.out.println("Please input a positive whole number.");
x = sc.nextInt();
sc.nextLine();
sc.close();
System.out.println();
sum = 0;
//do computation
for(int a = 0; a < x; a = a + 1)
{
if(a%5==0)
{
sum = sum + a;
}
}
//print results
System.out.println("Sum = " + sum);
}
}
You're not including the number itself that is input by the user. Simply change the for loop to the below so that the input x gets added:
for (int a = 0; a <= x; a = a + 1) {
Change
for(int a = 0; a < x; a = a + 1)
to
for(int a = 0; a <= x; a = a + 1)
At the moment you're not including 25, that only goes upto 24 i.e. a < x means "while a is less than x", then you want "while a is less than OR EQUAL TO x".
Your loop test should be <= (not <), also I suggest you define variables when you need them. Finally, you shouldn't close() a Scanner on System.in because that closes System.in and if you refactor your code you may cause yourself a lot of pain with that. So, I would change your method like
Scanner sc = new Scanner(System.in);
System.out.println("Please input a positive whole number.");
int x = sc.nextInt();
int sum = 0;
for (int a = 0; a <= x; a++) {
if (a % 5 == 0) {
sum += a;
}
}
// print results
System.out.println("Sum = " + sum);

Categories

Resources