Problem:
Write a program that reads an integer N followed by N lists of strings. Each list ends with the string “xyz”. If your first name appears in list K (1 <= K <= N), and K is the smallest such value, then your program prints “My name is in list K!” Otherwise, it prints “My name is not listed. Please add it somewhere.”
Output:
3
Mike
Gregory
Henning
John
xyz
George
Faisal
xyz
Mathew
Faisal
Rolf
xyz
My name is in list 2
Mike
Gregory
Henning
John
xyz
George
Faisal
xyz
Mathew
Faisal
Rolf
xyz
My name is in list 2
Solution:
import java.util.Scanner; public class lauprob2 { public static void main (String[] args) { Scanner scan = new Scanner(System.in); String str = "e"; int input = scan.nextInt(); /*We're making an array of n integers, with n being the number of lists we're going to read from the screen*/ int[] name_appearance = new int[input]; //Note: the value of all 3 integer variables of this array is zero by default //We're going to loop over each entered list to keep track //of where my name is appearing for (int count = 0; count < input; count++) { //We just need a random initial value for the String variable that we //will be using to check the scanned string str = "e"; //In this inner loop, we're going to loop over each scanned string //from the same list to check if my name is there. //Note: the condition will stop the loop when we reach our end marker=xyz for (int index = 0; !(str.equals("xyz"));index++) { str = scan.nextLine(); //If we found out that my name is equal to the entered String //in list number n, we're going to make if (str.equalsIgnoreCase("george") && index < input) //In this step, we're going to make the array element (list number) that //has my name be equal to well, the actual list number name_appearance[count] = count+1; //for example, if the second list has my name, then what we're really doing here //is having count=1 and making name_appearance[1]=1+1=2 //If the name was at the first list (i.e., at our first try without increasing count) //then the variables would be count=0 and name_apperance[0]=1 } } //We're going to go through each array element to check which element has a value //other than zero; this is because we changed the array element value of the list that //has my name in the loops above. Kinna sounds complicated and weird, but this is // just one way of solving this problem so don't get freaked out over not // wanting to ever do this code again :P for (int NameList : name_appearance) if (NameList != 0) System.out.println("My name is in list" + NameList); } }
No comments :
Post a Comment