Below is a simple program to compare two numbers using Java. It is the solution to Deitel’s Java How to Program (10th Edition) Chapter 2 Exercise 2.16.
Question: Write an application that asks the user to enter two integers, obtains them from the user and displays the larger number followed by the words “is larger”. If the numbers are equal, print the message “These numbers are equal”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
/** * * Website: www.cscprogrammingtutorials.com * * Exercise 2.16 - Comparing Integers * This Program Compares Any Two Numbers and Displays The Larger Number. * */ import java.util.Scanner; public class ComparingIntergers { public static void main (String [] args) { Scanner value = new Scanner (System.in); int num1; //first number entered by the user int num2; //second number entered by the user System.out.println ("Enter Your First Number"); num1 = value.nextInt (); System.out.println ("Enter Your Second Number"); num2 = value.nextInt (); System.out.println (); if (num1>num2) System.out.println (num1 + " is Larger\n"); if (num2>num1) System.out.println (num2 + " is Larger.\n"); if (num1 == num2) System.out.println ("These numbers are equal.\n"); } } |
2 Comments
Yes you can use else if but the instruction in the textbook says "use programming techniques you have learned so far". That means, even though the problem can be solved using another and probably better method, do not use it unless it has been taught in the previous or present chapter.
In this case, the else if selection statement have not been taught in chapter two of the textbook.
Shouldn't you use else if?