Subtraction of arrays elements in java [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
please see my code below :
package calc;
import java.util.Arrays;
import java.util.Scanner;
public class calc {
public static void main(String[] args) {
double[]numbers= {6 , 5 ,7};
Arrays.sort(numbers);
double diff = numbers[3-1];
for (int i =2 ; i<= 0; i--) {
System.out.println(numbers[i]);
diff-=numbers[i-1];
}
System.out.println("Answer --> "+diff);
}
}
My problem is that i am trying to subtract the elements in the array. I have assumed that the user have inserted the values randomly , so i have sorted the array and i have iterated the array "inversely" (From the highest index to the lower one) , so that i can subtract like this --> 7-6-5=-4 . Unfortunately the for loop is not executed , can someone tell me what is the problem here ? Thanks

The for loop is not executed because of the conditions in your loop statement.
Right now, you have int i=2; i <= 0; i--. When Java goes to execute this loop, it finds that i=2 which is not <= 0, so the loop is never executed.
To make the loop execute, change i <= 0 to i >= 0

Check your looping.
double[]numbers= {6 , 5 ,7};
Arrays.sort(numbers);
// start with last number
double diff = numbers[numbers.length-1];
for (int i=numbers.length-2 ; i>= 0; i--) {
// substract other number one by one
diff-=numbers[i];
}
System.out.println("Answer --> "+diff);

Related

If else loop not adding valuing to variable using +=? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have a 1D matrix with data and another with scores. I'm trying to loop across all of the elements in the data and find the element in the same position in the score matrix, and keep adding these values together during each loop. For some reason, my script keeps starting from sum = zero instead of retaining and adding to the sum from the previous loop. For the below example, I expect sum = 1 in the first loop, 3 after the second loop (since 1+2=3) and 6 after the third loop (3+3=6). Instead, sum just yields the last value retrieved from scores. What am I doing wrong here?
public static int calc_score( )
{
String [] dat = {"A", "B","C"};
int [][] scores = new int [1][3];
scores[0][0] = 1;
scores[0][1] = 2;
scores[0][2] = 3;
int sum = 0;
for (int i = 0; i < dat[0].length(); i++)
{
if (dat[i].equals("A")) {
sum = sum + scores[i][0];
// scores[i][0] returns the expected value of 1 in the first loop
}
else if (dat[i].equals("B")) {
sum = sum + scores[i][1];
}
else if (dat[i].equals("C")) {
sum = sum + scores[i][2];
}
}
System.out.println(sum);
return sum;
}
I tried modifying sum = sum + scores[i][1]; to sum+=scores[i][1] but that doesn't fix this. I have to be missing something simple.
Learn to debug. Add println statements, or use a debugger, and track, on paper if you prefer, what you think the program should do. Where the computer does something different from what you thought: Voila. You found a bug; there may be more.
If you can't figure out why something is happening, go back and re-check assumptions.
Had you done that here, for example, you might have eventually noticed: Huh, that for loop really is only running exactly once, that's bizarre. Eventually you'd check what dat[0].length() returns and then realized it returns, mysteriously, 1, and perhaps then you'd have one of those slap yourself on the forehead moments: dat[0] refers to the first entry in the dat array, so, the string "A". Then you ask that string about length, which dutifully returns 1.
I assume you wanted dat.length instead.
Note that scores[1][0] is 0 too, you have more than one problem here.

Java Recursive Method (Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to take an object array and print out the reverse using a recursive method but I'm getting the above listed error. Could someone help me out?
public static void main(String[] args) {
int v = 1;
int x = 2;
String y = "dog";
String z = "cat";
Object[] a = {v, x, y, z};
printReverse(a, a.length);
}
public static void printReverse(Object[] arr, int i) {
if (i > 0) {
System.out.println(arr[i]);
printReverse(arr, i - 1);
}
else {
return;
}
}
}
Your initial call to printReverse needs to pass a.length -1. You’re going out of bounds on the initial call before it ever recurses since arrays are 0-indexed
The error message means you are accessing array element 4 but there are only elements with index 0 to 3. Array indices in Java start at 0.

Printing "*" with recursion [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I would need some help to solve one exercise. In this method I have to print the number of asterisks ("*") that are equal of 2 of power of x.
For example, if I have 2 of power of 2 it should print 4 asterisks ("****");
I have a method that returns me the right number, but I have problems using that number for printing those asterisks.
Here is my code:
public static int writeStars(int number) {
if (number == 0) {
return 1;
} else {
int number2 = 2 * writeStars(number - 1);
System.out.println(" number " + number2);
return number2;
}
}
Here's one idea for solving the problem, without giving away the solution in code.
Your thoughts are on the right track, realizing that 2x = 2 * 2x-1. To print 2x * characters, you can print 2x-1 twice. In your recursive method, have your base case print one * character, and have your recursive case make the recursive call twice, passing the appropriately adjusted value.
One way to do it is to create a string of 2^(i-1) stars at the i-th iteration. So, for 4 iterations (x=4), you will have 8,4,2,1 stars for each iteration. You can return the string of stars for each iteration and concatenate them to get the final string.
The terminating condition will be when the input size is 0. This code might help:
public static String writeStars(int y) {
//y is 2^x
if( y == 0)
return "";
int num_stars = y - y/2;
StringBuffer stars_Buffer = new StringBuffer(num_stars);
for (int i = 0; i < num_stars; i++){
stars_Buffer.append("");
}
return stars_Buffer.toString() + writeStars(y/2);
}
Call writeStars with input 2^x:
writeStars(Math.pow(2, x));
Because it is a return method in your client you should have
int num = writeStars(someNum);
Then to print, you just need a simple for loop
for(int i=0; i < num; i++)
System.out.print("*");

Does my program have a runtime error or does my computer not have the power to run my program? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
So I started the Euler Project and the first problem was very easy, however I cannot get the answer because the program I created is not running. It compiles fine but when I run it, it never runs. Project Euler says that the problems " with efficient implementation will allow a solution to be obtained on a modestly powered computer in less than one minute." Which leads to my question. Am i stuck in an infinite loop or does my computer not have the power to run my program?
The problem is: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
public class Euler1
{
public static void main(String[] args)
{
double x = 1;
int count = 0;
int total = 0;
while( x < 1000)
{
if((x/3 == (int)x) || (x/5 == (int)x))
{
count++;
x++;
total += x;
}
}
System.out.println(total);
}
}
Your program is wrong.
while( x < 1000)
{
if((x/3 == (int)x) || (x/5 == (int)x))
{
count++;
x++;
total += x;
}
}
Notice that x is only incremented if the condition is true. x starts at 1, so the condition is not true, so x never gets incremented and stays at 1.
Also, x/3 == (int)x and x/5 == (int)x are not correct tests for divisibility. Neither of them are ever true unless x is 0.
The problem is that if your if condition is false in the while loop, x never gets incremented...
(and it will always be false unless x is 0)
You are getting stuck in an infinite loop. Your if-statement is never being called because it will never return true unless x is 0, and thus your x variable is never being incremented. I would suggest looking into the % (modulus) operator for this problem.

drawString in loop writes only once instead of multiple times [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What would this code do?
for(int i = 0; i < enemysno; i++){
g.drawString("\nArray size: " + i, 200, 200);
}
enemysno is a random number between 0 and 10, and works fine. Problem is, it loops once, but then stops adding new lines after the first iteration.
As Psuedo code, I though the i starts as 0. Then compares the condition, if its false, does the code, then makes the ++ iterations, then repeats the loop?
Ultimatly, I want to add n objects to an array, but I can quite get this to work simple array to work!
A simple test proves the loop indeed works as intended:
public static void main(String[] args)
{
int enemysno = 5;
for (int i = 0; i < enemysno; i++)
{
System.out.println("lalala " + i);
}
}
this works fine producing
lalala 0
lalala 1
lalala 2
lalala 3
lalala 4
It was kind of obvious, but via debugging or such a test you could determine that the loop itself is entered the desired numer of times. The problem must be in your string display: most probably your drawString method overwrites the printed string each time.
It should be obvious if you checked the numbers on your output.
The solution?
use a string builder to concatenate the partial strings and then draw the final string using your drawString method

Categories