Recursive Palindrome - java

First of all I am not telling anyone to "do my homework." I just need a little help on how to keep repeating a process. This is the program I did below and it has a tester class with it.
The class:
class RecursivePalindrome {
public static boolean isPal(String s)
{
if(s.length() == 0 || s.length() == 1)
return true;
if(s.charAt(0) == s.charAt(s.length()-1))
return isPal(s.substring(1, s.length()-1));
return false;
}
}
Then the tester class which has the main method:
public class RecursivePalindromeTester {
public static void main(String[] args)
{
RecursivePalindrome Pal = new RecursivePalindrome ();
boolean quit = true;
Scanner in = new Scanner(System.in);
System.out.print("Enter a word to test whether it is a palindrome or not(press quit to end.): ");
String x = in.nextLine();
while(quit) {
boolean itsPal = Pal.isPal(x);
if(itsPal == true){
System.out.println(x + " is a palindrome.");
quit = false;
}
else if (x.equals("quit")) {
quit = false;
}
else {
quit = false;
System.out.println(x + " is not a palindrome.");
}
}
}
}
This program find if the letter is Palindrome or not. I got all the calculations and stuff in but what do i do to keep asking the user for input and every time the user inputs it says if it is a Palindrome word or not.

Just move the lines asking for user input and reading it:
System.out.print("Enter a word to test whether it is a palindrome or not(press quit to end.): ");
String x = in.nextLine();
...into your loop, e.g., just after the
while (quit) {
...line.
Side note: quit seems like an odd name for a boolean which, when true, means you keep going. :-)

Simply wrap with another while loop.
Look into the continue and break statements. They are very helpful for loops, which is what you're looking for information on here.
public class RecursivePalindromeTester {
public static void main(String[] args) {
RecursivePalindrome Pal = new RecursivePalindrome ();
Scanner in = new Scanner(System.in);
while(true){
System.out.print("Enter a word to test whether it is a palindrome or not(press quit to end.): ");
String x = in.nextLine();
boolean itsPal = Pal.isPal(x);
if(itsPal == true){
System.out.println(x + " is a palindrome.");
} else if (x.equals("quit")) {
break;
} else {
System.out.println(x + " is not a palindrome.");
}
}
}
}

Related

How to get "else" not to loop

My code is a "guessing game" and so if you enter a southeast asian country to the input it will display a "you are correct" text but if not then otherwise, my problem is that the else loops whatever times the length of my array is that i put the countries in, how to stop loop plz?
Code--
package guessinggame;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
String ans;
String[] countries = {"Philippines", "Brunei", "Burma", "Cambodia",
"Timor Leste", "Indonesia", "Laos", "Malaysia", "Singapore", "Thailand", "Vietnam"};
Scanner sc=new Scanner(System.in);
System.out.println("Please enter a Southeast Asian country");
ans = sc.nextLine();
for (int x=0; x<countries.length; x++) {
if (ans.equals(countries[x])){
System.out.println("Your answer (" + ans + ") is correct.");
}
else System.out.println("Your answer (" + ans + ") is incorrect.");
}
}
}
Currently your code takes user input, then within a loop it compares user input to one of the coutries and
if match gives a message
if not match gives a message
That means if your list is 20 entries long, in case of incorrect enty the user would be told so 20 times. For a correct entry, the user would be told 19 times that he is wrong and one time that he is correct.
What you need to do is:
take user input
loop over the list and find out if there is a match. Do not print a result during the loop
after the loop has finished, print whether some match was found
You could set a variable
boolean found = false;
and set it to true once you found a match. Later your output can look like
if (found) {
System.out.println("correct");
} else {
System.out.println("incorrect");
}
If you want to tune your code terminate the loop as soon as you found a match.
You need to add break to your loop and a flag to can know if the user answer incorrect. Check the comments in my code.
I hope the code below will help you!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String ans;
String[] countries = {"Philippines", "Brunei", "Burma", "Cambodia", "Timor Leste", "Indonesia", "Laos", "Malaysia", "Singapore", "Thailand", "Vietnam"};
Boolean found = false; //Init the flag
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a Southeast Asian country");
ans = sc.nextLine();
for (int x = 0; x < countries.length; x++) {
if (ans.equals(countries[x])){
System.out.println("Your answer (" + ans + ") is correct.");
found = true; //Change the flag to true if the answer is correct
break; //Leave the loop so the flag can't change more
}
}
// Check for the flag value. If the flag remains false, means that the answer is incorrect so will print the message below
if (!found) {
System.out.println("Your answer (" + ans + ") is incorrect.");
}
}
}
for (int x = 0; x < countries.length; x++) {
if (ans.equals(countries[x])) {
System.out.println("Your answer (" + ans + ") is correct.");
return;
}
}
System.out.println("Your answer (" + ans + ") is incorrect.");
public static void main(String[] args) {
String ans;
String[] countries = {"Philippines", "Brunei", "Burma", "Cambodia",
"Timor Leste", "Indonesia", "Laos", "Malaysia", "Singapore", "Thailand", "Vietnam"};
Scanner sc=new Scanner(System.in);
System.out.println("Please enter a Southeast Asian country");
ans = sc.nextLine();
int flag =0;
for (int x=0; x<countries.length; x++) {
if (ans.equals(countries[x])){
flag =1;
break;
}
}
if(flag==1){
System.out.println("Your answer (" + ans + ") is correct.");
}
else {
System.out.println("Your answer (" + ans + ") is incorrect.");
}
}
here you go
public class GuessingGame {
public static void main(String[] args) {
String ans;
String[] countries = { "Philippines", "Brunei", "Burma", "Cambodia", "Timor Leste", "Indonesia", "Laos",
"Malaysia", "Singapore", "Thailand", "Vietnam" };
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a Southeast Asian country");
ans = sc.nextLine();
boolean available = false;
for (int x = 0; x < countries.length; x++) {
if (ans.equals(countries[x])) {
available = true;
break;
}
}
if (available) {
System.out.println("Your answer (" + ans + ") is correct.");
} else {
System.out.println("Your answer (" + ans + ") is incorrect.");
}
}
}

simple UDP / TCP java Hangman

i have an assignment to write simple game using UDP / TCP connection. I already have a simple Hangman game on java. i want the game to be played between 2 client or between server client. this is my hangman code
package gameexample;
import java.util.Arrays;
import java.util.Scanner;
public class Hangman{
public static void main(String[] args) {
String[] words = {"writer", "that", "program"};
// Pick random index of words array
int randomWordNumber = (int) (Math.random() * words.length);
// Create an array to store already entered letters
char[] enteredLetters = new char[words[randomWordNumber].length()];
int triesCount = 0;
boolean wordIsGuessed = false;
do {
// infinitely iterate through cycle as long as enterLetter returns true
// if enterLetter returns false that means user guessed all the letters
// in the word e. g. no asterisks were printed by printWord
switch (enterLetter(words[randomWordNumber], enteredLetters)) {
case 0:
triesCount++;
break;
case 1:
triesCount++;
break;
case 2:
break;
case 3:
wordIsGuessed = true;
break;
}
} while (! wordIsGuessed);
System.out.println("\nThe word is " + words[randomWordNumber] +
" You missed " + (triesCount -findEmptyPosition(enteredLetters)) +
" time(s)");
}
public static int enterLetter(String word, char[] enteredLetters) {
System.out.print("(Guess) Enter a letter in word ");
// If-clause is true if no asterisks were printed so
// word is successfully guessed
if (! printWord(word, enteredLetters))
return 3;
System.out.print(" > ");
Scanner input = new Scanner(System.in);
int emptyPosition = findEmptyPosition(enteredLetters);
char userInput = input.nextLine().charAt(0);
if (inEnteredLetters(userInput, enteredLetters)) {
System.out.println(userInput + " is already in the word");
return 2;
}
else if (word.contains(String.valueOf(userInput))) {
enteredLetters[emptyPosition] = userInput;
return 1;
}
else {
System.out.println(userInput + " is not in the word");
return 0;
}
}
asterisks were printed, otherwise return false */
public static boolean printWord(String word, char[] enteredLetters) {
// Iterate through all letters in word
boolean asteriskPrinted = false;
for (int i = 0; i < word.length(); i++) {
char letter = word.charAt(i);
// Check if letter already have been entered bu user before
if (inEnteredLetters(letter, enteredLetters))
System.out.print(letter); // If yes - print it
else {
System.out.print('*');
asteriskPrinted = true;
}
}
return asteriskPrinted;
}
public static boolean inEnteredLetters(char letter, char[] enteredLetters) {
return new String(enteredLetters).contains(String.valueOf(letter));
}
public static int findEmptyPosition(char[] enteredLetters) {
int i = 0;
while (enteredLetters[i] != '\u0000') i++;
return i;
}
}
can anyone show me how to write this code to client server program, with 2 player waiting turn for each guess? and the game is finished when one of them guess the last letter ?

Hangman if comparison running all branches

I'm working on a hangman assignment, but I am stuck in one part of it;
A player (user) is playing a game of words with the computer.
The users plays the game couple of times. When they stop the overall score of the user is displayed .
Each play the user sees a menu.
String S;
int s2;
System.out.println("WELCOME TO WORD GAME V.12.01.16");
System.out.println("****MENU****");
System.out.println("FIRST YOUR NUMBER AND PRESS 'ENTER' ");
System.out.printf("0:Stop \n 1:Name \n 2:City \n 3:Animal \n 4:Thing ");
s=input.nextInt();
if(s==0) {
System.out.println("GOODBYE");
}
for(int i=0;i<category.length;i++) {
if(s==i){
System.out.println("GUESS FOR 1,CHARACTER FOR 2");
s2=input.nextInt();
if(s2==1){
System.out.println("ENTER YOUR GUESS");
S=input.nextLine();
boolean result=correct(S);
if(result==true) {
System.out.println("Congrats");
}
}
}
}
}
public static boolean correct(String X) {
for(int i=1;i<5;i++){
for(int j=0;j<10;j++){
if (category[i][j].equals(X)) {
}
}
}
return true;
}
}
Your if statement if(category[s][j]==S); is done the wrong way
Also noted by #resueman in his comment that comparing strings was done the wrong way as well. You want to use .equals() to compare strings.
S=input.nextLine();
System.out.println("Please Enter : ")
for(int j=0;j<11;j++){
if (category[s][j].equals(S)){
System.out.println("CONGRATS");
}else {
System.out.println("FAIL");
}
}
Edit - New code from OPs edit
public static void main(String args[]) {
String string;
Scanner input = new Scanner(System.in);
int s, s2;
System.out.println("WELCOME TO WORD GAME V.12.01.16");
System.out.println(
"****MENU****");
System.out.println(
"FIRST YOUR NUMBER AND PRESS 'ENTER' ");
System.out.printf(
"0:Stop \n 1:Name \n 2:City \n 3:Animal \n 4:Thing ");
s = input.nextInt();
if (s == 0) {
System.out.println("GOODBYE");
}
for (int i = 0; i < category.length; i++) {
if (s == i) {
System.out.println("GUESS FOR 1,CHARACTER FOR 2");
s2 = input.nextInt();
if (s2 == 1) {
System.out.println("ENTER YOUR GUESS");
string = input.nextLine();
// Dont need to assign the boolean to a value
// if(booleanVariable == true) is the same thing as writing if(boolean)
// If it is true, it will execute, if false it will not
if (correct(string)) {
System.out.println("Congrats");
}
} // if(s2==1)
}// if (s == i)
}// for
}// run
public static boolean correct(String X) {
for (int i = 1; i < 5; i++) {
for (int j = 0; j < 10; j++) {
if (category[i][j].equals(X)) {
// the guess was right
return true;
}
}
}
// Nothing equaled the guess
return false;
}

Hangman, exits the game without getting the user response (loop)

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;

Java: Accept input as string or int

I am trying to make a simple even or odd program. I want it to keep running until the user enters in 'q'. But I am having trouble accepting 'q' as a String.
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
int number;
String quit;
try {
number = myScanner.nextInt();
} finally {
quit = myScanner.nextLine();
}
if (quit.equals("q")) {
break;
} else if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
}
The program works fine when I enter numbers, but when I enter 'q', the console throws an error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at EvenOrOdd.main(EvenOrOdd.java:19)
I know this may be easy for many of you, but I have just picked up a java book and am trying to finish the task. Any help would be greatly appreciated!
You can make something like this and i found that a boolean is better for a loop in this case instead of while(true) and break:
public class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out
.println("Welcome to my program that checks if a number is even or odd.");
boolean enterLoop = true;
while (enterLoop) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
String scannerinput = myScanner.nextLine();
if (scannerinput.equals("q")) {
enterLoop = false;
} else {
checkNumber(scannerinput);
}
}
}
private static void checkNumber(String scannerinput) {
try {
int number = Integer.parseInt(scannerinput);
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
} catch (Exception e) {
System.out.println("No Number!");
}
}
}
Take a String from Scanner, check if is 'q' and if not, convert it to int and then check even or odd.
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
String inText = myScanner.next();
if (inText.equals("q")){
break;
}
int number = Integer.valueOf(inText);
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.print("\nPlease type number in a number ['q' to quit]: ");
String input = scanner.next();
if (input.equals("q")) {
break;
} else {
int number = Integer.parseInt(input);
System.out.print(number + " is ");
System.out.print(number%2 == 0 ? "Even." : "Odd.");
}
}
}
}
That'll do it. :)
Instead of using myScanner.nextInt(), just use myScanner.next() to get a String. Then if it is not "q", use Integer.valueOf(inputString) to get the int and check it for even/odd.
while (true) {
String input = myScanner.next();
if ("q".equals(input)) {
break;
} else {
int number = Integer.valueOf(input);
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
Try this approach. Check code note for more details.
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
String input=null;
int number;
boolean flag=true; // loop flag
do {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
// Take user input as String
input=myScanner.nextLine();
try
{
// convert the string value to integer value
number = Integer.parseInt(input);
if (number % 2 == 0)
{
System.out.println(number + " is Even.");
}
else
{
System.out.println(number + " is Odd.");
}
}
catch (NumberFormatException nfe)
{
// control goes here if input is not integer value
if(input.equals("q")) // exist option
flag=false;
else // invalid input
System.out.println("Invalid input, Please enter integer value or (q) to exist");
}
} while (flag);
}
}
You should update your method flow, you are actually trying to pass and intger validation for a string so first take the input as String and check whether it is your quit character q then if it is not try to parse the string to and int primitive with Integer.parseInt(input) and test if it is Odd or Even.
If the process fails assuming it is neither a q nor a number (any other character), then a message will be prompted for user telling him to use a valid number or "q" to quit:
import java.util.Scanner;
class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
int number;
String input = myScanner.next();
if (input.equals("q")) {
break;
} else {
try {
number = Integer.parseInt(input);
if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
} catch (NumberFormatException nfe) {
System.out.println("Enter valid number or \"q\" to quit!");
}
}
}
}
}
It is because the program is expecting a input of int-type, basically the program outputs: Please type number in a number ['q' to quit], and after that it will reach the myScanner.nextInt(); line and will be waiting for a input, and since "q" is not a integer it will throw an exception.
A quick solution would be to use myScanner.nextLine() and then convert the string into a integer unless it is equal to 'q'. Something like this:
import java.util.Scanner;
public class EvenOrOdd {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to my program that checks if a number is even or odd.");
while (true) {
System.out.println();
System.out.print("Please type number in a number ['q' to quit]: ");
String string = myScanner.nextLine();
int number = 0;
if (string.equals("q")) {
myScanner.close(); // Close the scanner.
break;
} else if ((number = toInteger(string)) == -1){ // Is the string a number, less than Integer.MAX_VALUE and greater than Integer.MIN_VALUE?
System.out.printf("%s is not a valid integer!%n",string);
} else if (number % 2 == 0) {
System.out.println(number + " is Even.");
} else {
System.out.println(number + " is Odd.");
}
}
}
private static int toInteger(String str){
try{
return Math.abs(Integer.parseInt(str));
}catch(NumberFormatException e){
return -1;
}
}
}
By the way, always close the scanner, otherwise a resource leak may occur.

Categories

Resources