Java: scanner reads integer but does not use it during / for loop
My book I am studying uses a different library for reading Inputs, so it cannot help me.
I can't see where my mistake is. Algorithm:
- Read the value n
- Set value i to 3
- Follow steps
Iteration
While i < 2*n
i+1
Write 1/(2*i+1) to the console.
My code:
import java.util.Scanner;
public class Aufgabe420 {
public static void main (String[] args) {
int i, n;
System.out.println("Please enter a number!");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
System.out.println("n ="+n);
System.out.println("The while-loop starts!");
i = 3;
while (i < 2*n){
i += 1;
System.out.println(1/(2*i+1));
}
System.out.println("now with for-loop");
for (i = 3; i < (2*n); i+=1) {
System.out.println(1/(2*i+1));
}
}
}
But after trying it results in: Please enter the number! five
n = 5 The while loop starts! 0 0 0 0 0 0 0
now with for-loop 0 0 0 0 0 0 0
What's wrong with this code? Thanks for your help.
+3
user5048972
source
to share
2 answers
This line
System.out.println(1/(2*i+1));
has a problem that it does integer division. And 1 divided by any value greater than 1 will always be 0. Solution: One of the operands must be a float for the result to be floating, for example. eg:
System.out.println(1.0/(2*i+1));
or do the following:
System.out.println(1/(float)(2*i+1));
+3
source to share