Problem:
Write a program that keeps reading strings until it reads the string “xyz”. If your first name is among the entered strings, the program prints “My name is there.” Otherwise, it prints “My name is not listed. Please add it.”
Solution:
mport java.util.Scanner; public class lauprob1 { public static void main (String[] args) { Scanner scan = new Scanner (System.in); //We made the String equal to null because we just //need a default initial value for it first to be //able to play with the String later String str = null; //And we played with it now :P str = scan.nextLine(); //We will now loop over the word that is entered //through the Scanner until we scan xyz and stop while (!(str.equals("xyz"))) { //We will check if the entered String is my name if ( str.equalsIgnoreCase("George")) { //Since my name is present, then I'll print this //and then scan the next entered String System.out.println("My name is there."); str = scan.nextLine(); } else { //If my name isn't there, then I'll just print this //and scan the next word so that loop will continue //and continue till we type xyz and end the program System.out.println("My name is not listed. Please add it"); str = scan.nextLine(); } } } }
No comments :
Post a Comment