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));
}
Related
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;
}
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)";
}
For case "1" it seems to just loop instead of jumping to drunkSong();. If the user selects case "2" it will work fine and ask the user to input the number to return the int "BeerNum".
Case "1" needs to accept a default value of 99 while Case "2" needs to accept user input.
I have attached the code, if you can point my mistake out or where I have gone wrong.
package PartOne;
import java.util.Scanner;
public class View {
public void begin() {
BeerSong.drunkSong();
}
private int setBeerNum() {
return beerNum;
}
private int beerNum;
public Integer Menu() {
Scanner in = new Scanner(System.in);
// print menu
for (int i = 1; i <= 3; i++)
System.out.println(i + ". Menu item #" + i);
System.out.println("0. Quit");
// handle user commands
boolean quit = false;
int menuItem;
do {
System.out.print("Choose menu item: ");
menuItem = in.nextInt();
switch (menuItem) {
case 1:
System.out.println("Default ");
begin();
while (true)
try {
//where I have made a mistake
beerNum = 99;
this.beerNum = setBeerNum();
break;
} catch (NumberFormatException BecauseIsaidSo) {
System.out.print("Try again: ");
}
//working
case 2:
System.out.println("Enter your number to play the song: ");
Scanner scan = new Scanner(System.in);
while (true)
try {
beerNum = Integer.parseInt(scan.nextLine());
this.beerNum = setBeerNum();
return beerNum;
} catch (NumberFormatException BecauseIsaidSo) {
System.out.print("Try again: ");
}
case 0:
quit = true;
break;
default:
System.out.println("Invalid choice.");
}
}
while (!quit) ;
System.out.println("Bye-bye!");
return null;
}
}
I think it is much better to encapsulate menu logic in the separate class and encapsulate all logic in it. Moreover, logic for each menu item should be encapsulated in separate method as well.
public final class Menu {
private Integer res;
private boolean quit;
public static Integer showMenuAndGetResult() {
Menu menu = new Menu();
menu.activate();
return menu.res;
}
private Menu() {
}
private void activate() {
try (Scanner in = new Scanner(System.in)) {
show();
while (!quit) {
System.out.print("Choose menu item: ");
int menuItem = in.nextInt();
if (menuItem == 1)
onMenuItem1(in);
else if (menuItem == 2)
onMenuItem2(in);
else if (menuItem == 0)
onMenuQuit();
else
System.out.println("Invalid choice.");
}
System.out.println("Bye-bye!");
}
}
private void show() {
for (int i = 1; i <= 3; i++)
System.out.println(i + ". Menu item #" + i);
System.out.println("0. Quit");
System.out.println();
}
private void onMenuItem1(Scanner scan) {
System.out.println("Default ");
// TODO menu 1 logic incapsulation
}
private void onMenuItem2(Scanner scan) {
System.out.println("Enter your number to play the song: ");
// TODO menu 2 logic incapsulation
}
private void onMenuQuit() {
res = null;
quit = true;
}
}
P.S. I personally try to avoid using switch. This is not my recomendation, just note. I think that if...else if is more readable and problemless.
I got a couple issues with my code. I know it is not the best looking design/coding but I don't claim to be a good programmer yet. I have to other classes does their work correctly. Dictionary class which contains a word list and HangmanAnimation class which draws the hangman onto console.
Now, I want my game to ask to player if he/she wants to play again after the game finished. Actually, it does asking if player wants to play again but exits the game before the player can type anything.
I would appreciate any other suggestions aswell. Thanks in advance! You guys really rock! :)
public class HangmanGame {
public static void main(String[] args) {
HangmanUI ui = new HangmanUI();
ui.initialize();
String input = "";
if(ui.newGame(input).equalsIgnoreCase("yes"))
main(null);
}
}
public class HangmanUI {
private final Dictionary d = new Dictionary();
private final HangmanAnimation ha = new HangmanAnimation();
private String wordInProgress = d.getWordInProgress();
Scanner sc = new Scanner(System.in);
private int maxTries = 5;
String word;
public void initialize() {
int easyWords = 1;
int hardWords = 2;
System.out.println("Welcome to Hangman game.");
System.out.println("=========================");
System.out.println("Rules: You need to find the given word in 5 tries.");
System.out.println("You will continue guessing letters until you can either");
System.out.println("solve the word or all five body parts are on the gallows.");
System.out.println("In that case you will lose the game. Try not to enter");
System.out.println("same letter more than once. Those are counts too.");
System.out.println();
System.out.println("Choose your game level or Quit:");
System.out.println("1) Easy");
System.out.println("2) Hard");
System.out.println("3) Quit");
try {
int playersChoice = sc.nextInt();
switch (playersChoice) {
case 1:
d.wordList(easyWords);
break;
case 2:
d.wordList(hardWords);
break;
case 3:
System.out.println("Thank you for your time!");
System.exit(0);
default:
System.out.println("Invalid input. Try again!");
initialize();
}
word = d.pickRandomWord(d.getWordList());
hideWord(word);
while(maxTries > 0) {
if(wordInProgress.contains("-")) {
System.out.println(wordInProgress);
revealLetter(notifyGuess());
} else {
System.out.println("Good work! You found the word.");
}
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Use only digits!");
}
}
//TODO: Do not count same letter more than once & let player to know.
public char notifyGuess() {
ArrayList<Character> charSet = new ArrayList<>();
System.out.print("Please enter a letter: ");
char c = sc.next().charAt(0);
if(Character.isDigit(c)){
System.out.println("You can't use numbers. Please enter a letter.");
notifyGuess();
} else if(charSet.contains(c)) {
System.out.println("You already used '" + c + "' before.");
notifyGuess();
} else
charSet.add(c);
return c;
}
public void hideWord(String word) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < word.length(); i++) {
sb.append("-");
}
wordInProgress = sb.toString();
}
public void revealLetter(char c) {
try {
String temp = wordInProgress;
char[] charArray = wordInProgress.toCharArray();
for (int i = 0; i < word.length(); i++) {
if(c == word.charAt(i))
charArray[i] = word.charAt(i);
}
wordInProgress = new String(charArray);
if(temp.equals(wordInProgress)){
maxTries--;
ha.drawHanging(maxTries);
} else {
System.out.println("Good! There is '" + c + "' in the word.");
}
} catch (StringIndexOutOfBoundsException e) {
System.err.println("You have to enter a character!");
}
}
public String newGame(String input) {
System.out.println("Do you want to play again? (yes/no)");
input = sc.nextLine();
return input;
}
}
Try using this:
System.out.println("Do you want to play again? (yes/no)");
input = sc.next(); //<== here is the change
return input;
Hi i have done this program it works fine except if the user tries to write in capital letters i tried .toUpperCase but it still closes the program if you try to use capital letter to search can anyone help please thank you
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class database
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//my arrays
static String country [] = new String[1000];
static String capital [] = new String[1000];
static double population [] = new double[1000];
static List<String> countriesList = Arrays.asList (country); //a new array for user to add data to
public static void main (String args [])throws IOException
{
// now i am adding data to the arrays
country[0] = "Barbados";
capital[0] = "Bridgetown";
population[0] = 65.3;
country[1] = "france";
capital[1] = "paris";
population[1] = 315.8;
country[2] = "nigeria";
capital[2] = "abuja";
population[2] = 170.1;
country[3] = "USA";
capital[3] = "washington";
population[3] = 2840;
country[4] = "japan";
capital[4] = "tokoyo";
population[4] = 126.7;
int option = 0;
System.out.println("WELCOME TO MY COUNTRY DATABASE\n");
while(option!= 5){ //Only five options
options();
option = Integer.parseInt(br.readLine());
if(option > 5 || option < 1)
{
System.out.println("Wrong input! Try Again");
System.out.println("CHOOSE FROM 1 - 5 \n ");
}
if(option == 1) {
addCountry();
}
else if(option == 2){
searchCountry(); //Search from an array
}
else if(option == 3){
ListCountry();
}
else if(option == 4){
getFare(); //show fare to travel
}
else if(option == 5) {
System.out.print("\n Thank you and Goodbye ");
}
}
}
public static void options()
{
System.out.println("Main menu");
System.out.println("=========");
System.out.println("1. Add a new country");
System.out.println("2. Search for a country");
System.out.println("3. Show list of countries available");
System.out.println("4. Get fare from London to countries listed");
System.out.println("5. Exit");
System.out.print("\n Choose an option from 1 - 5: ");
}
public static void addCountry()throws IOException
{
System.out.println("\n Adding a country");
System.out.println("===================");
System.out.print("Enter name of country: ");
String countryInput = br.readLine();
System.out.print("Enter Capital: ");
String capitalInput = br.readLine();
System.out.print("Enter population: ");
String populationInput = br.readLine();
int spareSlot = -1;
for (int i = 0; i < country.length; i++) // loop so data can be added to arraylist
{
if(country[i] == null)
{
spareSlot = i;
break;
}
}
country[spareSlot] = countryInput;
capital[spareSlot] = capitalInput;
population[spareSlot] = Double.parseDouble(populationInput);
System.out.println("\n You added the country " + countryInput + ", the capital is " + capitalInput + ", with a population of " + populationInput + "\n" );
//System.out.println("================================================================================================================");
}
public static void searchCountry() throws IOException
{
Scanner in = new Scanner (System.in);//Scanner to obtain input from command window
String output;
int size, i;
System.out.println("\n Searching countries");
System.out.println("========================= \n");
System.out.print("Search a Country: ");
output = br.readLine();
boolean found = false;
//A loop to search from the array
for(i = 0; i < country.length; i++)
if(output.equals(country[i]))
{
found = true;
break;
}
if (found)
System.out.println(output + " is found at index " + i +"\n");
else
System.out.println(output + ": This country is not found, choose option 1 to Add country \n");
if (output == country[0])
{
System.out.println("The capital of "+ output + "is " + capital[1] + " with a population of " + population[3]);
}
if(output == country[1]) {
System.out.println("The capital is" + capital[4]);
}
if(output == country[2]) {
System.out.println("The capital is" + capital[1]);
}
if(output == country[3]) {
System.out.println("The capital is " + capital[2]);
}
if(output == country[4]) {
System.out.println("The capital is " + capital[3]);
}
}
public static void ListCountry()throws IOException
{
for (String c : countriesList)
{
if(c!=null)
System.out.println("\n" + c +"\n"); // to list all countries so far in the array
}
}
public static void getFare()
{
Scanner input = new Scanner (System.in);
String destination;
int fare;
System.out.println("\n Get a fare:");
System.out.println("============== \n");
System.out.print("Select destination by entering number from 1 -5: \n");
System.out.println("1 Caribbean");
System.out.println("2 Europe");
System.out.println("3 Africa");
System.out.println("4 America");
System.out.println("5 Japan");
destination = input.nextLine(); //get destination from user
fare = Integer.parseInt(destination);
switch(fare)
{
case 1: System.out.println("To travel to the Carribbean the fare is from £600 \n");
break;
case 2: System.out.println("To travel to Europe the fare is from £199 \n");
break;
case 3: System.out.println("To travel to Africa the fareis from £500 \n");
break;
case 4: System.out.println("To travel to America the fare is from £290 \n");
break;
case 5: System.out.println("To travel to Japan the fare is from £550 \n");
break;
default: System.out.println("INVALID ACTION START AGAIN \n");
System.out.println("======================================");
}
}
}
You have one comparison reading
if(output.equals(country[i]))
If you want this to be case-insensitive, you want to change that to
if(output.equalsIgnoreCase(country[i]))
Later in your code, you have lines similar to
if (output == country[0])
which compares object identity rather than string equality. You want to change all these to at least properly compare strings, and possibly to be case-insensitive as above.