I have a sample question where we are required to find multiples of 10 between two numbers. Here's the code I've written, and although it works, is there a better way to write this code?
Scanner keyboard = new Scanner(System.in);
int value = keyboard.nextInt();
int limit = keyboard.nextInt();
int div = 10;
for (;div<value;div+=10)
System.out.print("");
for (;div<=limit;div+=10)
System.out.println(div);
keyboard.close();
The first for loop irks me. Any suggestions?
Using java-8 :
IntStream.rangeClosed(value, limit).filter(i -> i % 10 == 0).forEach(System.out::println);
Here value
is the begin index and limit
is the ending index.
System.out.print("")
does nothing, so your first loop can be re-written as:
int div = 10;
for (; div < value; div += 10)
;
The effect of that code is that div
is the value of value
rounded up to the nearest multiple of 10. This can be calculated as follows, using int
math (where division by 10 rounds down):
int div = (value + 9) / 10 * 10;
The original code will result in a minimum value of 10
, so if value <= 0
the formula will calculate incorrectly. We can use a ternary conditional operator to account for that:
int div = (value <= 10 ? 10 : (value + 9) / 10 * 10);
So, the abbreviated version of your code becomes:
Scanner keyboard = new Scanner(System.in);
int value = keyboard.nextInt();
int limit = keyboard.nextInt();
for (int div = (value <= 10 ? 10 : (value + 9) / 10 * 10); div <= limit; div += 10)
System.out.println(div);
keyboard.close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.