Wrong results from for loop in a method - java

I would like to understand, why is it when I specify the number for the method to sum up numbers it returns 21, but when i enter the value through scanner it gives me the correct value. For example number 3 should be 1 + 2 + 3 = 6 but its giving me 21, any ideas thanks.
public class sumInt
{
public static void main(String[] args)
{
int i = sumInt(3);
int j = sumInt(10);
Scanner in = new Scanner (System.in);
System.out.println("Please enter posiutive integer: ");
int k = in.nextInt();
System.out.println(sumInt(i));
System.out.println(sumInt(j));
System.out.println(sumInt(k));
}
public static int sumInt(int n)
{
int sum = 0;
for (int i = 0; i <= n; i++)
{
sum += i;
}
return sum;
}
}

You are actually summing up to 6 for i, your current code could also be written as:
System.out.println(sumInt(sumInt(3)));
You'll need to print out i directly instead of calling sumInt on it again.

When you first do int i = sumInt(3);, i gets set to 6 (1 + 2 + 3). When you System.out.println(sumInt(i)), it does sumInt(6), which is 21, because you haven't reset i to 3.
To see the actual results, you should change what you're outputting to:
System.out.println(i);
System.out.println(j);
System.out.println(sumInt(k));
Or change your initial definitions of i and j to:
int i = 3;
int j = 10;

It's because you're calling sumInt in two places, when you only meant to call it in one:
int i = sumInt(3); // sets i = sumInt(3) == 6
System.out.println(sumInt(i)); // prints sumInt(i) == sumInt(6) == 21

Because you're calling sumInt() twice; once at the beginning, then again in the print statements.

You are saying i = sumInt(3) so i == 6.
Then your print sumInt(i) == sumInt(6) which I'm guessing is 21..

You call sumInt twice for the same number.
int i = sumInt(3); //i gets 6
System.out.println(sumInt(i)); //called with 6 =21

This is because of the following lines
System.out.println(sumInt(i));
System.out.println(sumInt(j));
System.out.println(sumInt(k));
You are already calculating i and j as the sum of the integers you want, and when you printout , you are again calculating sum of i and j
change the above three lines to the following:
System.out.println(i);
System.out.println(j);
System.out.println(sumInt(k));

Related

split the numbers and add them together code is not working properly, What is it am doing wrong?

I wrote the below code to split the numbers and add them together, it is working fine if my number is not starting with 1 eg, 123456 -- not working, 234567 -- working, can anyone tell me what I am doing wrong here?
public class Basic {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int sum =0;
for (int i = 0; i <input; i++) {
int A = input%10;
System.out.println("test1 " +A);
input = input/10;
System.out.println("test " +input);
sum = sum + A;
}
System.out.println(sum);
}
It's the loop:
for (int i = 0; i <input; i++) {
You are dividing the int input into its digits. So the loop should run until all digits are eaten up:
while (input > 0) {
That should fix it
In every iteration, you're updating input, so for example, step by step:
input = 123
i = 0
sum = 0
input = 12
i = 1
sum = 3
input = 1
i = 2
sum = 5
Then check the condition i < input it's 2 < 1, it's not, so it's skipping the last digit, the same happens for 234 it returns 7 rather than 9, because of the same thing.
You could change your for-loop for a do-while:
do {
//Your code here
} while (input > 0);
The problem is in i < input; i++ in your loop. It's not problem with only numbers starting with 1, for example 23445352 isn't work correctly too. I see 26 instead of 28.
Check the next steps in the loop, for 123 input, after two steps, you have sum = 5, input = 1 and... i = 2. So the condition for exiting the loop returns true without considering the last digit.

The loop runs twice in a single run

This problem is from https://www.hackerrank.com/ and link to it is https://www.hackerrank.com/challenges/java-list/problem .
In the below code while loop is running twice as according to question we need to enter Q, Q times an operation to perform in the Array Declared. For this, i am running twice the loop so that I can get the desired result.
import java.util.*;
public class javaList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int i, x;
ArrayList L = new ArrayList(N);
for (i = 0; i < N; i++) {
L.add(sc.nextInt());
}
int Q = sc.nextInt();
i = 0;
// for normal running i have multiplied Q by 2 so that i can get the results
while (i < Q * 2) {
System.out.println("Loop: " + i);
String s = sc.nextLine();
int sz = L.size();
// code for checking insert
if (s.equals("Insert")) {
x = sc.nextInt();
int y = sc.nextInt();
//if the position i am looking exists then just replace
// i need to insert at index x of array L but array.size() gives one more than the last index
if ((sz - 1) >= x) {
L.add(x, y);
}
//if the position i am looking does not exist then create
else {
for (int j = sz; j <= x; j++) {
//add number to desired place
if (j == x)
L.add(y);
//in between the two endings of array and insertion adding default value 0
else
L.add(0);
}
}
//checking code for Delete
} else if (s.equals("Delete")) {
x = sc.nextInt();
//if the desired location exists then only replace
if ((sz - 1) >= x) {
L.remove(x);
}
}
i++;
}
for (i = 0; i < L.size(); i++) {
System.out.print(L.get(i) + " ");
}
}
}
I want to Know why the loop is running twice in a single run.
So, from discussion in the comments, you've stated that your question is:
if Q = 2 then it should ask operations Insert or Delete 4 times as of my code. But it asks only 2 times. Simply that is my problem
First, you may not fully understand your own program flow. Before the while loop, you need to enter three sets of values, a value for N, values for L, and a value for Q.
Once you enter your while loop, you will be prompted for a value for s (which it seems you intend to be either "Insert" or "Delete"). However, the first time around, it will get an empty string and s will be "\n". Why? Because for N, L, and Q, the user will enter values as follows:
[value] [ENTER]
The return key is itself a value. So, in the input buffer (assuming Q = 2), is "2\n". When your code runs to get s String s = sc.nextLine(); it will see the next line symbol and skip prompting user for input.
Because s is not "Insert" or "Delete", it will skip those the first time around. You will then be prompted to enter a value for "s" after the start next loop.
To help you realize what's going on, I suggest adding statements everywhere you ask users to enter a value, like System.out.println("Enter a value for Q:");
This will help you keep track of program flow.
Your code is waaay to complicated. Try this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
for (int i = 0, n = scanner.nextInt(); i < n; i++) {
list.add(scanner.nextInt());
}
for (int i = 0, n = scanner.nextInt(); i < n; i++) {
if (scanner.next().equals("Insert")) {
list.add(scanner.nextInt(), scanner.nextInt());
} else {
list.remove(scanner.nextInt());
}
}
String result = list.stream()
.map(String::valueOf)
.collect(Collectors.joining(" "));
System.out.println(result);
}

Moving Average Using User-Input Array

I need to write a program that calculates a moving average by a user inputted array. The first element of the array is the window size, and the input is terminated by a 0. The output values are printed with two digits after the decimal point.
Example input: 3 2 4 7 7 8 11 12 0
Corresponding Output: 4.33 6.00 7.33 8.67 10.33
(4.33 is average of 2,4,7 and 6 is average of 4,7,7 etc.)
Here's my code so far:
package movingaverage;
import java.util.Scanner;
public class MovingAverage {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
avg[0] = sum / 5;
int j = 1;
for (int i = 5; i < arr.length; i++) {
sum = sum + arr[i] - arr[i - 5];
avg[j++] = sum / 5;
}
}
}
I think I have the loop right, but I'm not sure how to get the array to end at 0.
This is a possible solution.
public class Test
{
private static final Scanner SCANNER;
static {
SCANNER = new Scanner(System.in);
}
public static final void main(final String... args) {
final String[] numbers = SCANNER.nextLine().trim().split(" ");
final int consideredElements = Integer.parseInt(numbers[0]);
float sum = 0;
int value = 0;
for (int i = 1; i < numbers.length; i++) {
sum = 0;
for (int k = 0; k < consideredElements; k++) {
value = Integer.parseInt(numbers[i + k]);
if (value == 0) {
return;
}
sum += value;
}
System.out.println(new BigDecimal(sum / consideredElements).setScale(2, RoundingMode.HALF_EVEN));
}
}
}
First, you are using 5 in a couple of places in your program, I see no justification for that. Could it be that your expectation of user input lead you to put 5 where the number you really should use, depends on user input? Maybe you should use the window size instead? I’m guessing a bit here.
Next, as #lppEdd pointed out, you are not reading the numbers from your input — only the window size.
Next, you are declaring your array of size n, which I believe was your window size, not your array size. I believe the real solution to this problem is using better and more explanatory variable names.
Your code does not compile since you have not declared the array avg that you try to store your moving average into.
Fifth, when you want your average as a double, you need to convert to double before dividing (this is a classic pitfall that has already generated many questions on Stack Overflow).
I hope this gets you a couple of steps further.

Java For Loop Practice

Was doing some Java practices and I got stuck at this particular question, I am given the following code:
public class DistanceSeparator {
public static void main(String[] args) {
printSeparatorSequence(3);
printSeparatorSequence(5);
printSeparatorSequence(8);
}
public static void printSeparatorSequence(int numberOfElements) {
for () {
}
System.out.println();
} //end of method printSeparatorSequence
} // end of class
And I am supposed to modify the code using A SINGLE FOR LOOP to show that:
If numberOfElements = 5
1 3 7 13 21
If numberOfElements = 7
1 3 7 13 21 31 43
Each showing an increment of + 2, +4, +6, +8, +10 and +12
The final output is to be this:
1 3 7
1 3 7 13 21
1 3 7 13 21 31 43 57
I just can't seem to get my head around how to get that outcome, and this is after 2hours of trying (yes I am that bad). Any help, please?
edit This was what I had, before deciding to seek help, it's obviously not working.
int j = 0;
for (int i = 1; i <= numberOfElements; i++) {
j = i * 2; // + by how much
int z = i + j; //sum
System.out.print(z + "");
}
edit 2 now I get it, oh my, to think I was so close. Guess I was too cluttered after being stuck for some time. Thanks a ton!
Here is the code to accomplish result you expected.
int current = 1;
for(int i = 0; i < numberOfElements; i++) {
current += i*2;
System.out.print(current + " ");
}
You just need to keep another variable to keep track of the difference (the change), and then constantly update it by the power of 2 of the iteration, i.e. for the first loop only increase it by 2^1, then by 2^2, then 2^3 and so on).
An example of how to achieve that:
for (int i = 0, diff = 0; i < numberOfElements; i++, diff += 2*i) {
System.out.print((1 + diff) + " ");
}
UPDATE: After you've edited your question with your code segment, you can see your problem was with this line:
int z = i + j; //sum
Since both i and j advance with each iteration, you lose your offset (you constantly reset it). You need to keep it static (like in my example: 1), and only update j by 2*i each iteration, otherwise your "base" for calculation is constantly changing and the formula doesn't hold anymore.
In your case, you are regenerating int z everytime the loop is called,
All you have to do is define z outside the loop and instantiate z as 1 and also, you are not retaining the previous values of z so that's why it wasn't working. So it should be z = z + j and put this line below the print statement and you are done.
Here is an snippet of code which would help you my way:
int j = 1;
for(int i=1; i<=numberOfElements; i++) {
System.out.println(j);
j = j + 2*i;
}
And, here is an snippet of code which would help you your way:
int j = 0;
int z = 1;
for (int i = 1; i <= numberOfElements; i++)
{
j = i * 2; // + by how much
System.out.print(z + " ");
z = z + j; //sum
}
Note the trend.
You are adding a multiple of 2 to the previous number to get the next number. The multiple of 2 to be added depends upon the position of the number. For example, to get the 1st number, you add 2 x 0 to 1. To get the 2nd number, you add 2 x 1 to the previous number (that gives 3). To get the 3rd number, you add 2 x 2 to the previous number (that gives 7). To get the 4th number, you add 2 x 3 to the previous number (that gives 13).
To get the number at nth position, you add 2 x (n-1) to the previous number.
Now take a look at the example below, keeping the above explanation in mind.
public static void printSeparatorSequence(int numberOfElements) {
int number = 1;
for (int i = 0; i<numberOfElements;i++) {
number = number + 2 * i;
System.out.print(number);
}
System.out.println();
} //end of method printSeparatorSequence
} // end of class
This is the solution of your problem. I have discussed the code by the comment lines given within the code.
public class DistanceSeparator
{
/* Main Method */
public static void main(String[] args)
{
/* printSeparatorSequence Function is Called */
printSeparatorSequence(3);
printSeparatorSequence(5);
printSeparatorSequence(8);
}
/* printSeparatorSequence Function Definition */
public static void printSeparatorSequence(int NumberOfElements)
{
/* variable j is used to get the multiples of
2 by multiplying with variable i within the for loop
and variable sum is used to get the total value */
int j=2,sum=1;
for(int i=0;i<NumberOfElements;i++)
{
sum=sum+(j*i);
/* Here total sum is printed with a space */
System.out.print(sum+" ");
}
/* It is used for new line */
System.out.println();
}
}

not a statement error, illegal start of type

import java.util.*;
public class ulang {
public static void main(final String[] args) {
int a;
int b;
int sum;
Scanner scan = new Scanner(System.in);
System.out.println("Enter num 1: ");
a = in.nextLine();
System.out.println("Enter num 2: ");
b = in.nextLine();
{
sum = a + b;
}
for (i = 0; i < 5; i++) {
(sum >= 10)
System.out.println("Congratulations");
else
System.out.println("Sum of the number is Less than 10");
}
}
}
I'm weak on looping especially in Java. So I need some corrections on my coding, but I have no idea how to fix it.
The coding should run like this: User need to insert 2 numbers and the program will calculate the sum of both number. After that, the program will determine if the total of sum is >=10 or <10. If the sum >=10, "Congratulations" will appear but if it is <10, then "The sum of number less than 10" will appear. How to fix it?
This is the immediate problem:
(sum>=10)
I believe you meant that to be an if statement:
if (sum>=10)
Additionally:
You're trying to use an in variable, but the Scanner variable is called scan
Scanner.nextLine() returns a String - I suspect you wanted Scanner.nextInt()
Your for loop uses a variable that hasn't been declared. You probably meant:
for (int i = 0; i < 5; i++)
A few other suggestions though:
The sum isn't going to change between the loop iterations... why are you looping at all?
You've got a new block in which you're calculating the sum, but for no obvious reason. Why?
It's generally a good idea to declare variables at the point of initialization, e.g.
Scanner scan = new Scanner(System.in);
System.out.println("Enter num 1: ");
int a = scan.nextInt();
System.out.println("Enter num 2: ");
int b = scan.nextInt();
int sum = a + b;
Given that you want to take the same basic action (writing a message to the screen) whether or not the user was successful, you might consider using the conditional operator like this:
String message = sum >= 10 ? "Congratulations"
: "Sum of the number is Less than 10";
System.out.println(message);
That would then allow you to refactor the loop to only evaluate the condition once:
String message = sum >= 10 ? "Congratulations"
: "Sum of the number is Less than 10";
for (int i = 0; i < 5; i++)
{
System.out.println(message);
}
(sum>=10)
This line needs an if at the beginning, or it won't be read as a branch.
if (sum >= 10)
You also should name your main-class Ulang, because java class identifiers should start with an upper case letter, for readability.
The loop should look like the following:
for (int i = 0; i < 5; i++) {
The first part defines the counter and assigns zero to it. The second is your condition and the last counts for you.
for (int i = 0; i < 5; i++) {
if (sum >= 10)
System.out.println("Congratulations");
else
System.out.println("Sum of the number is Less than 10");
}

Categories

Resources