KaiquanMah commited on
Commit
2b714be
·
verified ·
1 Parent(s): 765c82e
Week 3: Objects, files and exceptions/[GRADING PROBLEM]2. Names to list - equals ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Write a program that asks the user for names.
2
+ The given names are added to the list.
3
+
4
+ However, if the name is already in the list, it is not added again, but an error message is printed to the user.
5
+ When the user enters 'quit', the list of names is printed and the program is terminated.
6
+
7
+ Example execution:
8
+ Give a name: Jack
9
+ Hello, Jack
10
+ Give a name: Jill
11
+ Hello, Jill
12
+ Give a name: Jack
13
+ Name has already been given
14
+ Give a name: Ann
15
+ Hello, Ann
16
+ Give a name: Jill
17
+ Name has already been given
18
+ Give a name: quit
19
+ Names: [Jack, Jill, Ann]
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+ import java.util.Random;
28
+ import java.util.ArrayList;
29
+ import java.util.Scanner;
30
+
31
+
32
+
33
+ public class Test{
34
+ public static void main(String[] args){
35
+ final Random r = new Random();
36
+
37
+ ArrayList<String> names = new ArrayList<String>();
38
+
39
+ while (true) {
40
+ Scanner reader= new Scanner(System.in);
41
+ System.out.print("Give a name: ");
42
+ String name = String.valueOf(reader.nextLine());
43
+
44
+ if (name.equals("quit")) {
45
+ break;
46
+ }
47
+
48
+ if (names.contains(name)) {
49
+ System.out.println("Name has already been given");
50
+ }
51
+ else {
52
+ names.add(name);
53
+ System.out.println("Hello, " + name);
54
+ }
55
+ }
56
+ System.out.println("Names: " + names);
57
+
58
+
59
+ }
60
+ }