Write an if-else statement with multiple branches. If givenYear is 2100 or great
ID: 670192 • Letter: W
Question
Write an if-else statement with multiple branches. If givenYear is 2100 or greater, print "Distant future" (without quotes). Else, if givenYear is 2000 or greater (2000-2099), print "21st century". Else, if givenYear is 1900 or greater (1900-1999), print "20th century". Else (1899 or earlier), print "Long ago". Do NOT end with newline.
mport java.util.Scanner;
public class YearChecker {
public static void main (String [] args) {
int givenYear = 0;
givenYear = 1776;
/* Your solution goes here */
return;
}
}
Explanation / Answer
Solution :
import java.util.Scanner;
/*
* Problem statement : Write an if-else statement with multiple branches.
* If givenYear is 2100 or greater, print "Distant future" (without quotes).
* Else, if givenYear is 2000 or greater (2000-2099), print "21st century".
* Else, if givenYear is 1900 or greater (1900-1999), print "20th century".
* Else (1899 or earlier), print "Long ago". Do NOT end with newline.
*/
public class YearChecker {
/* 'don't use magic numbers.use constants.'
static final int TWENTYONEHUNDRED = 2100;
static final int TWOTHOUSAND = 2000;
static final int NINETEENHUNDRED = 1900;
*/
public static void main(String[] args) {
System.out.print("Please enter the year : ");
Scanner scanIn = new Scanner(System.in);
String yearStr = scanIn.nextLine();
scanIn.close();
int givenYear = Integer.parseInt(yearStr);
//Here I am using magic numbers for your simplicity.Please replace them with above constant variables.
if(givenYear >= 2100){
System.out.print("Distant future");
}else if(givenYear >= 2000){
System.out.print("21st century");
}else if(givenYear >= 1900){
System.out.print("20th century");
}else{
System.out.print("Long ago");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.