I am slightly new to coding, I am solving a problem which should print all the integers between variables L and R including L,R. but I am getting the required output repeatedly. I don't understand the reason for it.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int L = sc.nextInt();
int R = sc.nextInt();
for (int i = 0; ; i++) {
if (i >= L && i <= R) {
System.out.print(i + " ");
}
}
}
Input: L=4 ,R=8
Output: 4 5 6 7 8 4 5 6 7 8 4 5 6 7 8 and so on...
You put the condition is the wrong place, so your loop is infinite.
To further explain, since your loop has no exit condition, i will be incremented forever, but after reaching Integer.MAX_VALUE, the next i++ will overflow, so i will become negative (Integer.MIN_VALUE). Then it will continue to increment until it reaches again the range you wish to print, so that range will be printed again and again, forever.
The correct loop should be:
for(int i = L; i <= R; i++) {
System.out.print(i+" ");
}
Now i will start at the first value you wish to print (L), and the loop will terminate after printing the last value you wish to print (R).
If are new to coding then follow this link to understand how for loop works
And you are not defining any condition when for loop should stop executing the code block
for(int i = L; i <= R; i++) {
System.out.print(i+" ");
}
This is how your for loop should be
Related
import java.util.*;
public class happy_number
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
String num = in.next();
for (int i = 0; i < num.length(); i++){
double index = num.charAt(i);
(double)index = Math.pow((double)i,2);
System.out.println(index);
}
}
}
For some reason, the second line in the for loop is returning as unexpected type– required: variable found: value. Any insight?
error: image of the error
It doesn't continue to ask you for an input. What is happening here is that the execution get's struck in an infinite loop, for certain types of inputs (in this case non-magic numbers).
For Eg.:
Let's take the example 44, below will be the values for each iteration in the for loop.
num
num1
num2
Start
44
-
-
After 1st iteration
8
4
4
After 2nd iteration
8
8
0
After 3rd iteration
8
8
0
…
…
…
…
We can see that the execution get's struck in the loop.
You have to exit out of the loop when you get such inputs.
One way to exit out of the loop is to add a condition in the for loop.
Another way is to add an if statement inside the for loop, and exit out of the loop based on the condition.
You have to decide what condition you should use in order to exit the loop, based on your problem statement.
Look on to the loop and the value populated inside. There is no breaking condition found and the correct test for a magic number:
A simple code:
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number to check: ");
int num = in.nextInt();
int n = num;
while (n > 9) {
int sum = 0;
while (n != 0) {
int d = n % 10;
n /= 10;
sum += d;
}
n = sum;
}
if (n == 1)
System.out.println(num + " is Magic Number");
else
System.out.println(num + " is not Magic Number");
}
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.
This question already has answers here:
Sum numbers using loop
(2 answers)
java for loop sum and average of range
(3 answers)
Closed 2 years ago.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Last Number ");
int inputedNumber = Integer.valueOf(scanner.nextInt());
int result = 0;
int outcome = 0;
for(int i = 0; i < inputedNumber; i++) {
result += ;
}
/*/*while (outcome <= inputedNumber) {
result += inputedNumber;
outcome++;
}*/
System.out.println(result);
}
}
I have a problem to understand what is wrong here, because I would like to solve the task , originally it should be (Implement a program, which calculates the sum 1+2+3+...+n where n is given as user input.) but it gives me another answer, please , pin out for me in a both way , to understand what I went wrong , because everything so far make sense for me , but code doesn't work as it should to be
You can try the code below:
for(int i = 1; i <= inputedNumber; i++) {
result += i;
}
Note: you should start with i=1 based on your requirement:
1+2+3+..+n
You need to replace result += ; with result += i;
For the first case. This is not a valid Java code, you should put a value/variable after += operator.
for (int i = 0; i < inputedNumber; i++) {
result += ;
}
If you put the variable i after it, and use i<= inputedNumber. You will get the expected answer.
for (int i = 0; i <= inputedNumber; i++) {
result += i;
}
In the second case, you are actually doing n*(n+1)
while (outcome <= inputedNumber) {
result += inputedNumber;
outcome++;
}
This can be tested as input the value as 2:
The first iteration:
outcome -> 0
inputedNumber -> 2
result -> 2
The second iteration:
outcome -> 1
inputedNumber -> 2
result -> 4
The third iteration:
outcome -> 2
inputedNumber -> 2
result -> 6
The fix is similar to what I suggested before. You could take this as an exercise.
I'm stuck on a program from mooc.fi course; wherein I can't get my program to print results.
The program should 'print all the numbers divisible by three in the given range. The numbers are to be printed in order from the smallest to the greatest.'
Thanks for the help.
public class DivisibleByThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = Integer.valueOf(scanner.nextLine());
int b = Integer.valueOf(scanner.nextLine());
divisibleByThreeInRange(a, b);
}
public static void divisibleByThreeInRange(int beginning, int end) {
for (int i = 0; i >= beginning && i <= end; i++) {
if (i % 3 == 0) {
System.out.println(i);
}
}
}
}
Welcome to stack overflow, Entropy!
The problem is this line:
for (int i = 0; i >= beginning && i <= end; i++) { ... }
Let's break up that for loop:
for says its a loop, with the first statement initializing the loop, the second giving the condition for executing the next iteration, and the third saying how to update after an interation. Inside the quotes is what to execute in an interation.
Loop initializing: int i = 0 defines the loop variable i and sets it to 0.
Loop condition: i >= beginning && i <= end. So we will execute the next iteration if i lies in the entered range.
Loop post update: i++ just increments the counter.
So effectively, you start with i being 0, and then execute the loop WHILE that number is within the entered range. But if i BEGINS outside your range, the loop is never executed, because the condition is false at the very beginning.
You can confirm that by entering making the range contain 0, i.e. enter a non-positive lower and a non-negative upper range (like -10 to 10). Then, the initial condition is fulfilled and your loop happily shows all the number divisable by 3.
So simply change the loop to
for (int i = beginning; i <= end; i++) { ... }
and it will work as intended: Start at the beginning of the range, and go the end of it -- done!
These for-loops can be tricky sometimes, don't they? :)
That's a great first post, by the way. Having a Minimal Reproducible Example (MRE, also called reprex or MCVE [Minimal, Complete, Verifiable Example]) always help others to quickly verify, debug and solve your problem.
public class DivisibleByThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = Integer.valueOf(scanner.nextLine());
int b = Integer.valueOf(scanner.nextLine());
divisibleByThreeInRange(a, b);
}
public static void divisibleByThreeInRange(int beginning, int end) {
for (int i = beginning ; i <= end; i++) {
if (i % 3 == 0) {
System.out.println(i);
}
}
}
}
The output of this program this is: iiiii .
and this is because of i++ used after print statement. ++ means increment and without i++ its printing i 10 times .then how it will give this output iiiii .it has to be increment one more
class array_output {
public static void main(String args[])
{
char array_variable [] = new char[10];
for (int i = 0; i < 10; ++i) {
array_variable[i] = 'i';
System.out.print(array_variable[i] + "" );
i++;
}
}
}
That's an expected output as you are incrementing the i twice. simple solution is to remove last line in the for loop.
output from your program:
i = 0
i = 2
i = 4
i = 6
i = 8
i = 10
After removing the last increment
iiiiiiiiii
Your code should be
class array_output {
public static void main(String args[])
{
char array_variable [] = new char[10];
for (int i = 0; i < 10; ++i) {
array_variable[i] = 'i';
System.out.print(array_variable[i] + "" );
// i++; // you are incrementing i again. No need to do if you want a jump of 1 step.
}
}
}
Ok. After reading again here is the answer for the question. When you enter forloop for the first time your i is 0 and after entering you said i++ which will be 1 and then ++i which becomes 2 so for every i you are making a jump of 2 steps so that's the reason after 5 iterations you are reaching 10 and your for loop condition i<10 fails. So, the loop further won't execute and exit successfully.
Sorry for the wrong output in my previous answer. Here is the right output. .
i = 0
i = 2
i = 4
i = 6
i = 8