user5048972
user5048972

Reputation:

Java: Scanner reads integer, but doesn't use it in while/for loop

My book I'm learning with uses another libary for reading Inputs so it can't help me....

I can't see where my mistake is. The algorithm:

  1. Read the value of n
  2. Set the value of i to 3
  3. Follow the steps

Iterate

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 trying it, it results in: Please enter a number! 5

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 that code? Thanks for your help.

Upvotes: 3

Views: 105

Answers (2)

Eran
Eran

Reputation: 393771

1/(2*i+1) will result in 0 for any positive i, since 1 < (2*i+1) and int division can't result in fractions.

change

System.out.println(1/(2*i+1));

to

System.out.println(1.0/(2*i+1));

You want to perform floating point division, not int division.

Upvotes: 6

Tilman Hausherr
Tilman Hausherr

Reputation: 18851

This line

System.out.println(1/(2*i+1));

has the problem that it performs an 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 float, e.g. like this:

System.out.println(1.0/(2*i+1));

or do this:

System.out.println(1/(float)(2*i+1));

Upvotes: 3

Related Questions