In: Computer Science
IN JAVA
12.11 PRACTICE: Branches*: Listing names
A university has a web page that displays the instructors for a course, using the following algorithm: If only one instructor exists, the instructor's first initial and last name are listed. If two instructors exist, only their last names are listed, separated by /. If three exist, only the first two are listed, with "/ …" following the second. If none exist, print "TBD". Given six words representing three first and last names (each name a single word; latter names may be "none none"), output one line of text listing the instructors' names using the algorithm. If the input is "Ann Jones none none none none", the output is "A. Jones". If the input is "Ann Jones Mike Smith Lee Nguyen" then the output is "Jones / Smith / …".
Hints:
Use an if-else statement with four branches. The first detects the situation of no instructors. The second one instructor. Etc.
Detect whether an instructor exists by checking if the first name is "none".
CODE GIVEN:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String firstName1, lastName1;
String firstName2, lastName2;
String firstName3, lastName3;
firstName1 = scnr.next();
lastName1 = scnr.next();
firstName2= scnr.next();
lastName2= scnr.next();
firstName3= scnr.next();
lastName3= scnr.next();
/* Type your code here. */
}
}
Code:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String firstName1, lastName1;
String firstName2, lastName2;
String firstName3, lastName3;
firstName1 = scnr.next();
lastName1 = scnr.next();
firstName2= scnr.next();
lastName2= scnr.next();
firstName3= scnr.next();
lastName3= scnr.next();
/* Type your code here. */
// case 1 : none exists
if( firstName1.equals("none")){
System.out.println("TBD");
}
// case 2: one instructor exists
else if( firstName2.equals("none") ) {
System.out.println(firstName1.charAt(0) + "." + lastName1);
}
// case 3: two instructor exists
else if( firstName3.equals("none") ) {
System.out.println(lastName1 + "/" + lastName2);
}
// case 4: all three instructor exists
else{
System.out.println(lastName1 + "/" + lastName2 + "/...");
}
}
==================
Screenshot:
Sample Output:
================
Explanation:
The case of no instructor is true if firstName1 is none. So we print "TBD".
If the firstName2 is none it means we only have one instructor
If firstName3 is none means we have two instructor
Other wise all three instructors are present
================
Please upvote.
For any query comment.