Java help - Output range with increment of 5

Write a program whose input is two integers, and whose output is the first integer and subsequent increments of 5 as long as the value is less than or equal to the second integer.

-15 10

the output is:

-15 -10 -5 0 5 10

Ex: If the second integer is less than the first as in:

20 5

the output is:

Second integer can't be less than the first. For coding simplicity, output a space after every integer, including the last.

Here is the code I have gotten so far, however, it is producing an error at the bottom I have an example of the input, my output and what was expected. If anyone has any pointers or can show me updated code it would be appreciated.

import java.util.Scanner;
public class LabProgram { public static void main(String[] args) { Scanner in = new Scanner(System.in); int first = in.nextInt(), second = in.nextInt(); if (first > second) { System.out.println("Second integer can't be less than the first."); } else { while (first <= second) { System.out.print(first + " "); first += 10; } System.out.println(); } }
}

Here's what kind of error it is showing:

Input

-15 10

Your output

-15 -5 5 

Expected output

-15 -10 -5 0 5 10 
2

1 Answer

You can use the range function from IntStream:

IntStream.range(-15, 10).filter(x -> x % 5 == 0);

As suggested by MC Emperor, there also is a faster solution:

IntStream.iterate(-15, i -> i + 5).limit((10+15)/5);
/** * The algorithm is as follows: * iterate(start, i -> i + step).limit((stop-start)/step) */
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like