If else loop not adding valuing to variable using +=? [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 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.

Related

Understanding Recursion Function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Recently in class, there was a recursion function that returned an array as either being true or false (sorted or not). However, I had trouble understanding it. The function is:
int[] array = { 3, 5, 2, 57, 8, 20 };
int start=0;
boolean sorted = sorted( array, start, array.length );
System.out.print( "array: ");
for ( int i=0 ; i<array.length ; ++i ) System.out.print( array[i] + " " );
if (sorted) System.out.println(" is sorted" );
else System.out.println( "is not sorted" );
static boolean sorted(int array[], int i, int count ) {
if (count == 1 || count == 0) return true;
if (array[count - 1] < array[count - 2]) return false;
return sorted(array, i-1, --count);
}
What is happening in the method and how is the recursion working? What does the variable count do if there is already an integer i? Why must it be equal to 0(or null) and 1? Why are the variables different for when you initialize "sorted" in the main method and for the sorted method? I believe some of the additional questions I asked may be redundant or unnecessary if I knew how the whole method worked. I would really appreciate your help!
First of all, welcome to the forum! :) Indubitably, recursion is something that's really difficult to come to grips with, but if you have learned about stack - as a part of the memory - you can understand recursion more easily. This article might appear useful in investigating what exactly happens in these types of algorithms.
The code might not be written in Java, but the syntax itself will be fairly understandable. I suggest you skip the memoization part - since it is more advanced and you can learn it later -, but the factorial code and the image are really self-explanatory.
You could also practice and write these algorithms and I agree: debugging is excessively useful if you don't understand something.
Finally, let me add some practical pieces of advice in the future for coding in Java:
Auto-format your code (the hotkeys are different in every major IDE's, but they definitely exist)
Avoid C-style coding when declaring arrays:
instead of
int array[]
, Java devs tend to do it in the following way:
int[] array
(Fun fact about multidimensional arrays: int[][] array, int array[][] and int[] array[] (!) work too.)
Last, but not least, do not miss curly braces also if there is only one statement in that particular block of code.
These are only coding conventions, though that code is syntactically alright, as you might have already seen it.
Happy coding!
The sorted method could just be:
static boolean sorted(int array[], int count) {
if (count == 1 || count == 0) {
// If the array has no elements or if it just has a single element,
// then it means that the array is sorted.
return true;
}
if (array[count - 1] < array[count - 2]) {
// If an element is less than the previous element,
// then the array is not sorted.
return false;
}
// check rest of the array.
return sorted(array, count-1);
}
I would suggest you to debug through the whole code so that you could get a better picture of what is happening.

Subtraction of arrays elements in java [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 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);

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("*");

Logic errors within java segment [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
The following Java code segment is supposed to print, as a double, the mean average of a sequence of non-negative integers entered by the user. A negative input signals the end of the sequence (it is not itself part of the sequence). However, the code is not working. I am supposed to find 4 logic errors within this segment. Please help me find the 4 logic errors?? I know one is its integer division.
public class practice
{
public static void main (String[]args)
{
int sum = 0;
int numVals = 0;
Scanner scan = new Scanner(System.in);
System.out.println(("enter next integer (-ve to stop): "));
int i = scan.nextInt();
while (i > 0)
{
sum = sum + i;
numVals = numVals + 1;
}
System.out.println("average = " + sum / numVals);
}
}
I won't give you full solution, however, it'll be helpful if you pay attention to:
int division as you said,
does your loop terminate? Is someone changing i? Hint: No, and
how do you ask for input? Do you see any loops there? Why it's asking you for only one input?
Not an error, but pay attention to Java Naming Conventions, class name should begin with upper case
Since the homework is for logic errors, I could point out other errors.
the class name should start with upper case letter.
the println doesn't need two nested parenthesis.
the sum should be a long rather than an int to avoid overflows.

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