Code efficiency. Effective way of using loops - java

I am building a framework for a web application and would like to perform certain simple tasks like input retrieval and displaying them. Below is have the code, I feel the code can be improved and isn't efficient. Note:All three methods have the same implementation.
The Switch needs to be implemented twice one within the IF loop and the other for general case.
public class selector8
{
public static void main (String [] args){
selector8 obj1 = new selector8();
Scanner inputString = new Scanner (System.in);
Scanner inputYN = new Scanner (System.in);
String input, A,B,C;
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
char contLoop1 = 'y';
do{
if(input.equalsIgnoreCase("y")) {
input = "";
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
switch (input){
case("a"):
obj1.startMethod1(input);
break;
case("b"):
obj1.startMethod2(input);
break;
case("c"):
obj1.startMethod3(input);
break;
case("x"):
System.out.println("Goodbye");
break;
case ("n"):
System.out.println("See ya");
break;
default:
System.out.println("Invalid argument. Try again");
break;
}
} else
switch (input){
case("a"):
obj1.startMethod1(input);
break;
case("b"):
obj1.startMethod2(input);
break;
case("c"):
obj1.startMethod3(input);
break;
case("x"):
System.out.println("Goodbye");
break;
case ("n"):
System.out.println("See ya");
break;
default:
System.out.println("Invalid argument. Try again");
break;
}
System.out.println("Do want to try again " +"Y/N" );
input = inputYN.nextLine();
contLoop1 = input.charAt(0);
}while(contLoop1 != 'n');
}
public void startMethod1(String A){
String input;
Scanner inputString = new Scanner (System.in);
System.out.println("Enter a or b");
input = inputString.nextLine();
switch (input){
case("a"):
System.out.println("output parsed");
break;
case("b"):
System.out.println("output parsed");
break;
default:
System.out.println("Invalid argument");
}
}
public void startMethod2(String B){
String input;
Scanner inputString = new Scanner (System.in);
System.out.println("Enter a or b");
input = inputString.nextLine();
switch (input){
case("a"):
System.out.println("output parsed");
break;
case("b"):
System.out.println("output parsed");
break;
default:
System.out.println("Invalid argument");
break;
}
}
public void startMethod3(String C){
String input;
Scanner inputString = new Scanner (System.in);
System.out.println("Enter a or b");
input = inputString.nextLine();
switch (input){
case("a"):
System.out.println("output parsed");
break;
case("b"):
System.out.println("output parsed");
break;
default:
System.out.println("Invalid argument");
}
}
}
On a side note could you also tell me why can static classes be called without an object?
public class StaticImplementation{
public static void main (String [] args){
StaticImplementation obj1 = new StaticImplementation();
obj1.stat(); //is invalid
stat(); //is valid
}
static void stat(){
System.out.println("Static class");
}
Thanks a bunch. Have a good day!

using Java you'd probably take a more "Object Oriented" approach and leave those switches to C programming :)
do something like:
interface Action {
void start();
}
class Jumper implements Action {
public void start() {
System.out.println("Jump!");
}
}
class Sitter implements Action {
public void start() {
System.out.println("Sit!");
}
}
class Runner implements Action {
public void start() {
System.out.println("Run!");
}
}
class Test {
public static void main(String[] args) {
// init phase
Map<String, Action> map = new HashMap<String, Action>();
map.put("a", new Jumper());
map.put("b", new Runner());
// usage
map.get("a").start();
}
}
you can have two Maps one for Y and the other for the rest, you can also have a key composed from the two strings Pair

Oh yes, it can. You don't need two scanners, and I would extract your switch into a method (let's call it startMethods) like so -
private static void startMethods(selector8 obj1,
String input) {
switch (input) {
case ("a"):
obj1.startMethod1(input);
break;
case ("b"):
obj1.startMethod2(input);
break;
case ("c"):
obj1.startMethod3(input);
break;
case ("x"):
System.out.println("Goodbye");
break;
case ("n"):
System.out.println("See ya");
break;
default:
System.out.println("Invalid argument. Try again");
break;
}
}
public static void main(String[] args) {
selector8 obj1 = new selector8();
Scanner inputString = new Scanner(System.in);
String input, A, B, C;
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
char contLoop1 = 'y';
do {
if (input.equalsIgnoreCase("y")) {
input = "";
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
startMethods(obj1, input);
} else
startMethods(obj1, input);
System.out.println("Do want to try again "
+ "Y/N");
input = inputString.nextLine();
contLoop1 = input.charAt(0);
} while (contLoop1 != 'n');
}

Try this:
public class Selector8 {
public static void main(String[] args) {
Selector8 obj1 = new Selector8();
Scanner inputString = new Scanner(System.in);
Scanner inputYN = new Scanner(System.in);
String input, A, B, C;
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
char contLoop1 = 'y';
while (contLoop1 != 'n') {
if (input.equalsIgnoreCase("y")) {
System.out.println("Choose. A || B || C || X to exit");
input = inputString.nextLine();
}
switch (input) {
case ("a"):
case ("b"):
case ("c"):
obj1.startMethod();
break;
default:
System.out.println(validate(input));
break;
}
System.out.println("Do want to try again " + "Y/N");
input = inputYN.nextLine();
contLoop1 = input.charAt(0);
}
}
public static String validate(String input) {
if (input.equalsIgnoreCase("x"))
return "Goodbye";
if (input.equalsIgnoreCase("n"))
return "See ya";
return "Invalid argument. Try again";
}
public void startMethod() {
Scanner inputString = new Scanner(System.in);
System.out.println("Enter a or b");
String input = inputString.nextLine();
switch (input) {
case ("a"):
case ("b"):
System.out.println("output parsed");
break;
default:
System.out.println("Invalid argument");
}
}
}

Related

Java -how can I store an array in switch case

I need to build code that first gets a 2d array and then prints it.
for this, I built a menu with a switch case.
when the user clicks 0, the user types the size of the array (the size is always n*n), and then the user types the values. then I need to create a function that uses this info to build a char array.(the values is hex base 0-F)
when the user clicks 1, the code needs to print the same 2d array.
I have a difficult time understanding how I can move the array from case 0.
import java.util.Scanner;
public class Assignment3 {
static Scanner reader = new Scanner (System.in);
public static void main(String[] args) {
int checker=1;
int user_selction;
do {
user_selction=Menu();
switch(user_selction) {
case 0:
Menu_0(user_selction);
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
checker=GoodBye(checker);
break;
default:
break;
}
}while(checker==1);
}
public static int Menu ()
{
int menu_num;
System.out.println("~ Photo Analyzed ~");
System.out.println("0. Load Photo");
System.out.println("1. Print Photo");
System.out.println("2. Circle Check");
System.out.println("3. Random Check");
System.out.println("4. Exit");
System.out.println("Please select an option>");
menu_num=reader.nextInt();
if(menu_num>4||menu_num<0)
{
System.out.println("Invalid input");
}
return menu_num;
}
public static int GoodBye(int GB)
{
GB=0;
System.out.println("Goodbye!");
return GB;
}
public static int Menu_0 (int a)
{
int Ps;
System.out.println("Please insert the photo size>");
Ps=reader.nextInt();
if(Ps<0||Ps>12)
{
System.out.println("Invalid Photo Input!");
return a;
}
System.out.println("Please insert the photo value>");
String strPhoto;
do {
strPhoto = reader.nextLine();
} while(strPhoto.length() == 0);
if(strPhoto.length()!=Ps*Ps)
{
System.out.println("Invalid Photo Input!");
return a;
}
for(int i=0;i<Ps*Ps;i++)
{
if(strPhoto.charAt(i)<'0'||strPhoto.charAt(i)>'F')
{
System.out.println("Invalid Photo Input!");
return a;
}
}
return a;
}
This is an example
import java.util.Scanner;
public class Assignment3 {
static Scanner reader = new Scanner (System.in);
public static void main(String[] args) {
int checker=1;
int user_selction;
char [][]array = null;
do {
user_selction=Menu();
switch(user_selction) {
case 0:
array = Menu_0();
break;
case 1:
print_array(array);
break;
case 2:
break;
case 3:
break;
case 4:
checker=GoodBye(checker);
break;
default:
break;
}
}while(checker==1);
}
public static int Menu ()
{
int menu_num;
System.out.println("~ Photo Analyzed ~");
System.out.println("0. Load Photo");
System.out.println("1. Print Photo");
System.out.println("2. Circle Check");
System.out.println("3. Random Check");
System.out.println("4. Exit");
System.out.println("Please select an option>");
menu_num=reader.nextInt();
if(menu_num>4||menu_num<0)
{
System.out.println("Invalid input");
}
return menu_num;
}
public static int GoodBye(int GB)
{
GB=0;
System.out.println("Goodbye!");
return GB;
}
public static char[][] Menu_0 ()
{
int Ps;
System.out.println("Please insert the photo size>");
Ps=reader.nextInt();
if(Ps<0||Ps>12)
{
System.out.println("Invalid Photo Input!");
return null;
}
System.out.println("Please insert the photo value>");
char [][]array = new char[Ps][Ps];
for(int i=0;i<Ps;i++)
{
for (int j = 0 ; j < Ps ; j++)
{
char c = reader.next().charAt(0);
if(c<'0'||c>'F')
{
System.out.println("Invalid Photo Input!");
return null;
} else {
array[i][j] = c;
}
}
}
return array;
}
public static void print_array(char [][]array){
for (int i = 0 ; i < array[0].length ; i++)
{
for (int j = 0 ; j < array[0].length ; j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
Use Scanner like this:
Scanner sc = new Scanner(System.in);
System.out.println("Select 1 to input array size or 2 to do sth");
int option = sc.nextInt();
switch(option) {
case 1 :
Scanner sc = new Scanner(System.in);
System.out.println("Enter array size: ");
int size = sc.nextInt()
int[] array = new array[size*size];
break;
case 2 :
something;
break;
default:
System.out.println("No such option ");
break;
}

How to automatically return to main menu without user input?

The "main menu" is the place where System.out.print("enter letter P T L S A or Q");. When the user has entered his/her surname, the console should automatically return to the first System.out.print statement i.e the menu. How do I set it up to be like that?
class myOwnTryAginLoopThatWorks{
public static void main (String [] args){
Scanner console = new Scanner(System.in);
boolean valid;
char choice = '\0';
String persnr;
do{
valid = true;
System.out.print("enter letter P T L S A or Q"); //menu
String input = console.nextLine();
if (!isValid(input)){
valid = false;
System.out.print("You did not enter the correct menu option, ");
if (input.length() != 1) {
System.out.println("and your input length is too long (must be 1 character long), ");
valid = false;
}
}
choice = input.charAt(0);
}while(!valid);
switch (choice) {
case 'P':
do {
valid = true;
System.out.print("Enter persnr in the format of (YYYYMMDD): ");
try {
persnr = console.nextLine();
if (!persnr.matches("[1-9]{1}[0-9]{7}")) {
throw new IllegalArgumentException("You printed wrong format, try again");
}
System.out.println("Processsing...");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
valid = false;
}
} while (!valid);
break;
}
System.out.print("enter first name ");
String firstName = console.nextLine();
System.out.print("enter surrname ");
String surName = console.nextLine();
}
public static boolean isValid (String n){
switch(n){
case "P":
case "T":
case "L":
case "S":
case "A":
case "Q":
return true;
default:
return false;
}
}
}
You MUST ask the question better. As I understand it, you need your menu is shown again asking to enter another data.
private static boolean exit = false;
public static void main(String[] args) {
while (exit == false){
readValues();
}
}
private static boolean isValid(String n) {
switch (n) {
case "P":
case "T":
case "L":
case "S":
case "A":
case "Q":
return true;
default:
return false;
}
}
private static void readValues() {
Scanner console = new Scanner(System.in);
boolean valid;
char choice = '\0';
String persnr;
do {
valid = true;
System.out.print("enter letter P T L S A or Q"); //menu
String input = console.nextLine();
if (!isValid(input)) {
valid = false;
System.out.print("You did not enter the correct menu option, ");
if (input.length() != 1) {
System.out.println("and your input length is too long (must be 1 character long), ");
valid = false;
}
}
choice = input.charAt(0);
} while (!valid);
switch (choice) {
case 'P':
do {
valid = true;
System.out.print("Enter DATE in the format of (YYYYMMDD): ");
try {
persnr = console.nextLine();
if (!persnr.matches("[1-9]{1}[0-9]{7}")) {
throw new IllegalArgumentException("You printed wrong format, try again");
}
System.out.println("Processsing...");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
valid = false;
}
} while (!valid);
break;
}
System.out.print("enter first name ");
String firstName = console.nextLine();
System.out.print("enter surrname ");
String surName = console.nextLine();
String query = " insert into Person (PNr, FName, ENamn)"
+ " values (persnr, firstName, surName)";
}

Validate the input using a while loop

I doing a little practice on Computer Science because when I leave the military I want to start taking classes on the basics of java. I'm a little stuck on this question i was wondering if i can get some assistance.
a program that allows the user to enter a character. The only valid values are 'A', 'M', and 'S'. Validate the input using a while loop so that if the user enters any value other than one of those 3 characters, an error message is displayed and the user is prompted for another value. Once the user has finally entered valid data, print the character they entered back to the screen.
You can look into this basic example
import java.util.Scanner;
public class Read {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean isCheck = true;
while (isCheck) {
String str = sc.next();
switch (str) {
case "A":
System.out.println("A");
isCheck = false;
break;
case "M":
System.out.println("M");
isCheck = false;
break;
case "S":
System.out.println("S");
isCheck = false;
break;
default:
System.out.println("Not Valid : Enter next");
isCheck = true;
}
}
}
}
Reading you input within the loop will enforce repetitive reading of input.
public class Read {
public static void main(String[] args) {
boolean isCheck = true;
while(isCheck){
Scanner sc = new Scanner(System.in);
String str = sc.next();
switch (str) {
case "A":
System.out.println("A");
isCheck = false;
break;
case "M":
System.out.println("M");
isCheck = false;
break;
case "S":
System.out.println("S");
isCheck = false;
break;
default:
System.out.println("Not Valid : Enter next.");
isCheck = true;
}
}
}
}

Creating a Basic Java phone book

I'm just learning Java and trying to make a simple phone book. For this part I'm trying to prompt the user to choose one of the 3 options below.
public class PhoneBook {
public static void main (String[] args){
options();
/*This method prompts the user to enter phone number
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter Phone Number");
s = in.nextLine();
System.out.println("You entered phone number ");
System.out.println(s);*/
}
public static void options (){
//This method gives the user choices on what to do
char choice;
char enterNumber = 'n';
char showNumber = 's';
char closeBook = 'c';
String read;
String freeLine = "error";
Scanner keyboard = new Scanner(System.in);
while (true){
System.out.println("Please select from the following");
System.out.println("n to Enter the number");
System.out.println("s to Show the number ");
System.out.println("c to Close the Phone book");
read = keyboard.nextLine();
choice = read.charAt(0);
switch (choice) {
case 'n': enterNumber;
system.out.println();
case 's':showNumber;
system.out.println();
case 'c': closeBook;
break;
default: System.out.println("Invalid Entry");
}
}
}
}
When I compile it i get errors on lines 37, 39, and 41 saying "Error: not a statement". I feel like something is missing. If anyone can help it would be greatly appreciated.
I am assuming that with the following lines you want to achieve to print the letter n for enterNumber in the console?
case 'n': enterNumber;
system.out.println();
This is not correct Java syntax. You will have to pass the variable value to the System.out.println method call:
case 'n': System.out.println(enterNumber);
Also note that Java is case sensitive, so you have to spell System with a capital letter.
On a side note, you will want to break; after each of your case statements, otherwise the code of the following cases will be executed as well:
switch (choice) {
case 'n': System.out.println(enterNumber);
break;
case 's': System.out.println(showNumber);
break;
case 'c': System.out.println(closeBook);
break;
default: System.out.println("Invalid Entry");
}
you do not have to write variable after 'cast' statement.
Refer below code.
import java.util.Scanner;
public class PhoneBook {
public static void main (String[] args){
options();
/*This method prompts the user to enter phone number
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter Phone Number");
s = in.nextLine();
System.out.println("You entered phone number ");
System.out.println(s);*/
}
public static void options (){
//This method gives the user choices on what to do
char choice;
char enterNumber = 'n';
char showNumber = 's';
char closeBook = 'c';
String read;
String freeLine = "error";
Scanner keyboard = new Scanner(System.in);
while (true){
System.out.println("Please select from the following");
System.out.println("n to Enter the number");
System.out.println("s to Show the number ");
System.out.println("c to Close the Phone book");
read = keyboard.nextLine();
choice = read.charAt(0);
switch (choice) {
case 'n':
System.out.println();
case 's':
System.out.println();
case 'c':
break;
default: System.out.println("Invalid Entry");
}
}
}
}
I have made a special answer for you. I don't add additional explanation. It's a large answer. I tell more than you ask, but I've done my best to make a readable code, so that you can analyse step-by-step to understand what you need at least when trying to make a Phone Book (console test drive application). If you need more explanation, write under comments.
First make a PhoneEntry class:
import java.util.Objects;
public class PhoneEntry implements Comparable<PhoneEntry> {
// https://jex.im/regulex/#!embed=false&flags=&re=%5E%5Ba-zA-Z%5D%7B2%2C%7D((-%7C%5Cs)%5Ba-zA-Z%5D%7B2%2C%7D)*%24
private static final String NAME_PATTERN = "^[a-zA-Z]{2,}((\\-|\\s)[a-zA-Z]{2,})*$";
// https://jex.im/regulex/#!embed=false&flags=&re=%5E%5C%2B%3F%5Cd%2B((%5Cs%7C%5C-)%3F%5Cd%2B)%2B%24
private static final String NUMBER_PATTERN = "^\\+?\\d+((\\s|\\-)?\\d+)+$"; //^\+?\d+((\s|\-)?\d+)+$
private final String name;
private final String number;
public PhoneEntry(String name, String number) {
if (!name.matches(NAME_PATTERN) || !number.matches(NUMBER_PATTERN)) {
throw new IllegalArgumentException();
}
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
public boolean nameContainsIgnoreCase(String keyword) {
return (keyword != null)
? name.toLowerCase().contains(keyword.toLowerCase())
: true;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof PhoneEntry)) {
return false;
}
PhoneEntry phoneEntry = (PhoneEntry) obj;
return name.equalsIgnoreCase(phoneEntry.name)
&& number.equalsIgnoreCase(phoneEntry.number);
}
#Override
public int hashCode() {
int hash = 5;
hash = 17 * hash + Objects.hashCode(this.name.toLowerCase());
hash = 17 * hash + Objects.hashCode(this.number.toLowerCase());
return hash;
}
#Override
public int compareTo(PhoneEntry phoneEntry) {
return name.compareToIgnoreCase(phoneEntry.name);
}
}
Then the test drive
public class TestDrive {
private static final String choices = "nspc";
enum Choice {
CREATE, READ, PRINT, CLOSE;
static Choice getChoice(char c) {
switch (c) {
case 'n':
return Choice.CREATE;
case 's':
return Choice.READ;
case 'p':
return Choice.PRINT;
case 'c':
return Choice.CLOSE;
}
return null;
}
}
// Main
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
final Set<PhoneEntry> entries = new TreeSet<>();
Choice choice;
while ((choice = getChoice(kbd)) != Choice.CLOSE) {
switch (choice) {
case CREATE:
PhoneEntry entry = getPhoneEntry(kbd);
if (entry != null) {
entries.add(entry);
}
break;
case READ:
print(readEntries(entries, kbd));
break;
case PRINT:
print(entries);
break;
}
}
}
private static Choice getChoice(Scanner kbd) {
System.out.println("\nPlease select from the following");
System.out.println("\tn to Enter the number");
System.out.println("\ts to Show numbers by keyword ");
System.out.println("\tp to Show all numbers ");
System.out.println("\tc to Close the Phone book");
System.out.print("> ");
String input = kbd.nextLine();
Choice choice = null;
if (!input.isEmpty()
&& choices.contains(input.toLowerCase())
&& ((choice = Choice.getChoice(input.toLowerCase().charAt(0))) != null)) {
return choice;
}
System.out.println("ERR: INVALID ENTRY. TRY AGAIN");
return getChoice(kbd);
}
private static PhoneEntry getPhoneEntry(Scanner kbd) {
System.out.print("Type contact name: ");
String name = kbd.nextLine();
System.out.print("Type phone number: ");
String number = kbd.nextLine();
try {
return new PhoneEntry(name, number);
} catch (IllegalArgumentException ex) {
System.out.println("\nERR: WRONG ENTRY");
}
return null;
}
private static void print(Set<PhoneEntry> entries) {
System.out.println("\nPHONE NUMBERS\n");
entries.stream().forEach(entry -> {
System.out.printf("Name: %s%nPhone: %s%n%n",
entry.getName(), entry.getNumber());
});
}
private static Set<PhoneEntry> readEntries(Set<PhoneEntry> entries, Scanner kbd) {
System.out.print("Type keyword: ");
return entries.stream().filter(entry
-> entry.nameContainsIgnoreCase(kbd.nextLine()))
.collect(Collectors.toCollection(TreeSet::new));
}
}
Instead of enterNumber;, you have to write enterNumber();.
The parentheses mean: Call the method.

Adding words and checking in Arraylist Hangman

I'm having trouble with adding words and using do while in my code:
ArrayList<String> word = new ArrayList<>();
word.add("fish");
word.add("chicken");
word.add("icecream");
int lengthz = word.size();
Scanner sc = new Scanner(System.in);
System.out.println("Hangman");
System.out.println("1. 1 Player");
System.out.println("2. 2 Player");
System.out.println("3. Add word");
System.out.println("4. Quit");
System.out.print("Choice : ");
int opsi = sc.nextInt();
if (opsi == 3) {
boolean show = false;
boolean founded = false;
System.out.println("Input the words to be added : ");
boolean showall = true;
do {
String input = sc.next() + sc.nextLine();
for (int i = 0; i < lengthz; i++) {
if (!input.equals(word.get(i))) {
while (!founded) {
word.add(input);
System.out.println("Succeed!");
founded = true;
}
} else if (input.equals(word.get(i))) {
while (!show) {
System.out.println("Already Added");
show = true;
}
}
}
System.out.println("Want to add more words?");
String answer = sc.next() + sc.nextLine();
if (answer.equals("no")) {
System.out.println("Thanks for adding");
showall = false;
} else if (answer.equals("yes")) {
opsi = 3;
}
} while (showall);
for (int i = 0; i <= lengthz; i++) {
System.out.println(word.get(i));
}
}
My desired output will be like if the user wants to add more word with "yes" then it will repeat the program, and if the user types "no" then it will display all the words together with the addition, and then going back to show the menu 1-4 option. Please help me ... Thanks in advance !
Structure your code, e.g. as follows:
static final Scanner in = new Scanner(System.in);
static List<String> words = getStandardWords();
public static void main(String[] args) {
while (true) {
System.out.println("-- Hangman --");
System.out.println("1. 1 Player");
System.out.println("2. 2 Player");
System.out.println("3. Add word");
System.out.println("4. Quit");
System.out.print("Choice : ");
String choice = in.nextLine();
switch (choice) {
case "1":
//todo
break;
case "2":
//todo
break;
case "3":
addWord();
break;
case "4":
System.exit(0);
break;
default:
System.out.println("Invalid choice: " + choice);
break;
}
}
}
static List<String> getStandardWords() {
List<String> result = new ArrayList<>();
result.add("fish");
result.add("chicken");
result.add("icecream");
return result;
}
static void addWord() {
System.out.println("Input the word to be added: ");
String word = in.nextLine();
// add word
if (words.contains(word)) {
System.out.println("Already Added");
} else {
words.add(word);
System.out.println("Succeed!");
}
// add more words?
while (true) {
System.out.println("Want to add more words?");
String choice = in.nextLine();
switch (choice.toLowerCase(Locale.ROOT)) {
case "n":
case "no":
System.out.println("Thanks for adding");
// print all words
for (int i = 0; i < words.size(); i++) {
System.out.println(words.get(i));
}
return;
case "y":
case "yes":
addWord();
return;
default:
System.out.println("Invalid coice: " + choice);
break;
}
}
}
1) You need to initialize the
founded = false;
inside do - while loop
2) use last printing for loop as below :
for(int i=0; i<word.size();i++)
{
System.out.println(word.get(i));
}

Categories

Resources