Hello! Tell me by code, what can I redo or add?

Task:

Create a program that will report whether the integer entered by the user is even or odd. If the user does not enter an integer number, then inform him about the error.

public class Test { public static void main(String args []){ int number; Scanner sr = new Scanner(System.in); System.out.print("Введите челое число -> "); if(sr.hasNextInt()){ number = sr.nextInt(); if ((number % 2) == 0){ System.out.print("Четное число " + number); }else{System.out.print("Не четное число " + number);} }else{System.out.print("Вы ввели не целое число");} } } 
  • why add something? - Nofate
  • Or you can cut the thread as a code? "Nofate" - turtles
  • It may be worthwhile to read a non-integer string. Otherwise, if the input is done in a cycle, you will not get to the next whole (loop). - avp

1 answer 1

You can slightly reduce the amount of code using the ternary operator:

 import java.util.Scanner; public class Test { public static void main(String args []) { Scanner sr = new Scanner(System.in); System.out.print("Введите челое число -> "); if(sr.hasNextInt()) { int number = sr.nextInt(); String category = (number % 2) == 0 ? "Четное" : "Нечетное"; System.out.println(category + " число: " + number); } else { System.out.println("Не целое число"); } } } 

And it is better to add the declaration of a variable inside the block where it is used. And so everything is ok.

  • Thank you! The answer is found The topic is closed! - turtles
  • Well, if you shorten the lines int n; if (sr.hasNextInt ()) System.out.println ("Permission" + (((n = sr.nextInt ())% 2) == 0? "Even": "Odd") + "number:" + n); else System.out.println ("Not an integer:" + sr.next ()); - avp