Reputation: 1
After getting an integer from the user and finding the square root, I need to find the square root of every number from i to 0. I am having trouble figuring out how to properly decrement the input so it prints out the square root of each number in an new line. I apologize if my title is not specific enough, I was having trouble attempting to describe this question.
public class Number {
public static void main(String[] args) {
int i = 1;
Scanner scnr = new Scanner(System.in);
System.out.print("Please enter a number: ");
while (i >= 1)
{
i = scnr.nextInt();
System.out.println(Math.sqrt(i));
i++;
}
System.out.println(i);
}
Upvotes: -3
Views: 1313
Reputation: 1
You can use Function interface :::
int i = 0;
Scanner scnr = new Scanner(System.in);
System.out.print("Please enter a number: ");
i = scnr.nextInt();
while (i >= 1)
{
System.out.println(squareRoot(i));
i--;
}
public Double squareRoot(Double number)
{
Function<Double,Double> sqrtFunction = (Double x) -> Math.sqrt(x);
double squareRoot = sqrtFunction.apply(number);
System.out.println("Square root of"+number+"is:"+squareRoot);
return squareRoot ;
}
Upvotes: 0
Reputation: 2716
decrement i within loop
int i = 0;
Scanner scnr = new Scanner(System.in);
System.out.print("Please enter a number: ");
i = scnr.nextInt();
while (i >= 1)
{
System.out.println(Math.sqrt(i));
i--;
}
Upvotes: 0
Reputation: 27996
If you are comfortable using Java 8 streams then you will be able to do this in a more straightforward way without needing a traditional for
loop:
IntStream.range(0, scanner.nextInt())
.map(Math::sqrt).forEach(System.out::println);
If you are not familiar with streams, this statement can be interpreted as "create a stream of integers from 0 to the input number; map each of these integers to its own square root; print each number in the stream".
While the syntax looks a bit trickier it's worth getting used to using it.
Upvotes: 1
Reputation: 285450
Get the user input before the loop, and decrement the variable, i--
.
The real solution is to not just post code and expect it to work, but rather you should walk through your code mentally or on paper to think through its steps as they're occurring. Also study up on the Java operators, especially the ++
and --
operators, and fully understand they're actions.
Upvotes: 0