I am having trouble with my hangman programm in java class I don't seem to get the lost lives counter to work properly and also displaying the already guessed letters that are right don't display in the sequence when you make the next correct guess.
import java.util.Scanner; //imports scanner so I could use user input
import java.util.Random; // imports random picker for words, to pick a random word
public class javaxx {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
StringBuffer sb = new StringBuffer();
StringBuffer buffer = new StringBuffer();
String wordToGuess;
int wordLength;
int wordToGuessLength;
int position;
int livesLost = 0;
int totalLives = 7;
int lettersRemaining;
boolean guessInWord;
char guess;
StringBuffer prevGuessedLetters;
//declare variable
//String wordToGuess[] = new String[29];
//insert array for words and their values
String[] myStringArray = new String[]{"programming","exhaustive","violin","selection","repetition","serendipity","watermelon","football","mobilephone","handbag","teddybear","cardigan","waterfall","cupcake","pineapple","strawberry","collection","chicken","tablecloth","candlestick","notebook","radiator","champagne","wineyard","parent","circus","snowbell","clocktower","mermaid","cardigan"};
//Display the rules of the game
System.out.println("You are playing the game Hang Man. You have to guess the letters in the word. You will see how many letters are in the word and you have 7 changes to be wrong. ");
//choose a random word from the array
wordToGuess = myStringArray[(int) (Math.random() * myStringArray.length)];
//determine the length of the word
wordLength = wordToGuess.length();
//show the player how many letters are in the word
System.out.println("The word you are quessing has " + wordLength + " letters in it");
lettersRemaining = wordLength;
for (position = 0; position < wordLength; position++) {
sb.append("_ ");
}
System.out.println(sb.toString());
//loop starts
while (lettersRemaining > 0 && livesLost < 7) {
//prompt user to guess a letter
System.out.println("Guess a letter:");
guess = myScanner.findWithinHorizon(".", 0).charAt(0);
//check if the letter guessed is in the secretWord
guessInWord = (wordToGuess.indexOf(guess)) != -1;
if (guessInWord == false) {
livesLost++;
System.out.print("Sorry, you have lost a life. You still have ");
System.out.print(totalLives -= livesLost);
System.out.println(" life/lives left. Keep trying.");
} else {
System.out.println("That was a good guess, well done!");
for (position = 0; position < wordLength; position++) {
if (wordToGuess.charAt(position) == guess) {
System.out.print(guess);
lettersRemaining--;
} else {
System.out.print("_ ");
}
}
}
System.out.println();
prevGuessedLetters = buffer.append(guess);
System.out.print("Previously guessed letters: ");
System.out.println(prevGuessedLetters);
System.out.print("Letters remaining: ");
System.out.println(lettersRemaining);
}
if (livesLost == totalLives) {
System.out.println("Sorry, you lose!");
} else {
System.out.print("Well done, you win! The word was ");
System.out.println(wordToGuess);
}
}
}
change this line
System.out.print(totalLives -= livesLost);
to
System.out.print(totalLives - livesLost);
this was the problem with liveslost counter.
Related
I am trying to create a Hangman and I have 2 problems.
1) The first problem is when the user finds the word, the loop does not stop.
2) I have a variable attempts which allows to know the number of attempts. Even if the user finds the letter, the number of attempts decrease.
The word to find is no
Here is a demonstration:
1) I enter the letter n
You have 5 attempts.
--
Enter your letter : n
2) I enter the letter o
The letter is good.
You have 4 attempts.
n-
Enter your letter : o
3) Normally the loop should stop.
The letter is good.
You have 3 attempts.
no
Enter your letter :
If you have an idea thank you in advance.
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = {/*"yes",*/ "no"};
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word_random.length(); i++) {
if ( word_found[i] ) {
System.out.print(word_random.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
for(int i=0; i<word_random.length();i++){
if(word_random.charAt(i) == letter){
System.out.println("The letter is good. ");
word_found[i] = true;
}
}
attempts--;
}
}
}
You are just missing a checking loop or method. Check the solution below.
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = {/*"yes",*/ "no"};
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word_random.length(); i++) {
if ( word_found[i] ) {
System.out.print(word_random.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
for(int i=0; i<word_random.length();i++){
if(word_random.charAt(i) == letter){
System.out.println("The letter is good. ");
word_found[i] = true;
}
}
boolean done = true;
for(boolean b : word_found)
done = done && b;
if(done) break;
else attempts--;
}
I will follow to your solution, not suggest a better one.
Ad 1. Add a check if the array word found contains only true after your first for cycle and if there are only true values in the array, print "you won" and set attempts to 0
Ad 2. Move attempts-- to the else case of your first for cycle OR add attempts++ in the true case of your first for cycle
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = { /* "yes", */ "no" };
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while (attempts > 0) {
System.out.println("You have " + attempts + " attempts.");
for (int i = 0; i < word_random.length(); i++) {
if (word_found[i]) {
System.out.print(word_random.charAt(i));
} else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
boolean match = false;
for (int i = 0; i < word_random.length(); i++) {
if (word_random.charAt(i) == letter) {
System.out.println("The letter is good. ");
word_found[i] = true;
match = true;
if (i == word_found.length - 1) {
System.out.println("THE END: attempts: " + attempts);
return;
}
}
}
if (!match) {
attempts--;
}
}
System.out.println("THE END");
}
I suggest you to modify the last part of your code like I did, and it should work.
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 3 years ago.
I am creating a random number generator multiplayer game (LAN).
I need help on how to create a code to make each player receive their own random number, and whenever one player guesses a code, the next turn would be a new player. Similar to where the output would show the following,
Fred, Please Guess the random number (integers only!!): 5
TOO LOW
Tom, Please Guess the random number (integers only!!): 95
TOO HIGH
John, Please Guess the random number (integers only!!): 50
TOO LOW
Then when a player guesses correctly, their turn is skipped and the game will end when all players have guessed their numbers, showing the number to guesses each person had, as well as the numbers they guessed previously.
This is what I have so far:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
Random myRand = new Random();
ArrayList<Integer> guessedNumbers = new ArrayList();
int x = 0;
int players = 0;
System.out.println("how many players are there?:");
players = checkint(players);
int arraySize = guessedNumbers.size();
int[] numPlayers = new int [players];
boolean play = true;
boolean validGuess = true;
String [] pNames = new String[players];
for (int i = 0; i<players; i++) {
System.out.println("New player, what is your name?:");
pNames[i] = keyboard.nextLine();
}
while(play) {
int randNum = myRand.nextInt(100) + 1;
int numOfGuesses = 0;
do {
System.out.println("Enter what you think the number is between 0 and 100!:");
x= checkint(x);
guessedNumbers.add(x);
if (x < 0) {
System.out.println("we don't accept negative numbers");
if (x > 100) {
System.out.println("that number is above the random number generator range");
}
}
numOfGuesses++;
if (x == randNum) {
System.out.println("that's correct!");
System.out.println("It took you " + numOfGuesses + " tries!");
System.out.print("these are all the numbers you guessed:");
for(int count=0; count<guessedNumbers.size(); count++){
System.out.print(guessedNumbers.get(count) + ",");}
System.out.println("");
boolean playError = true;
//if ("Yes".equals(answer)) {
do {
System.out.println("Would you like to play again: Yes or No");
String answer = keyboard.nextLine();
if (answer.compareToIgnoreCase("yes") == 0) {
play = true;
playError = false;
} else if (answer.compareToIgnoreCase("no") == 0) {
play =false;
playError = false;
System.out.println("Thank you for playing");
} else {
//you messed up
System.out.println("You answer was invalid");
playError = true;
}
} while (playError == true);
}
else if
(x>randNum)
System.out.println("Lower than that!");
else if
(x<randNum)
System.out.println("Higher than that!");
} while (x != randNum);
}}
}
static int checkint(int a) {
int enteredNumber = 0;
Scanner myScanner = new Scanner(System.in);
boolean numberError = false;
String enteredString = "";
do {
try {
enteredString = myScanner.next(); //Read into a string
enteredNumber = Integer.parseInt(enteredString.trim()); //then cast as a integer
numberError = false; //if we haven't bailed out, then the number must be valid.
} catch(Exception e) {
System.out.println("Your entry: \"" + enteredString + "\" is invalid...Please try again");
numberError = true; //Uh-Oh...We have a problem.
}
} while (numberError == true ); //Keep asking the user until the correct number is entered.
return enteredNumber;
}
}
You are doing simple things in a complex way, however, my code can still be replaced by a compressed version but you can understand this better. Following code is doing exactly what you want it to do. I've:
Created Player class, so each player will keep record of guessedNumbers, Number of Guesses and it's name.
You don't have to make tons of variables like pName[], play, validGuesses etc...
I have changed some of the If-Conditions and removed the outer while-loop
Added new round concept, so whenever a player guessed the number, the number got changed.
and much more ....
UPDATED Code: Now each Player has a different random number to guess.
import java.util.*;
public class GuessNumber
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
Random myRand = new Random();
ArrayList<Player> players = new ArrayList<Player>();
int x = 0;
System.out.println("how many players are there?:");
int noPlayer = checkint();
boolean validGuess = true , playError = true;
for (int i = 0; i<noPlayer; i++)
{
System.out.println("New player, what is your name?:");
players.add(new Player (keyboard.nextLine()));
}
for (int i = 0; i<noPlayer; i++)
{
players.get(i).number = myRand.nextInt(100) + 1;
}
int i =0; // for chossing different player each time
do
{
System.out.printf(players.get(i).name + " enter what you think the number is between 0 and 100!: ");
x= checkint();
players.get(i).guessedNumbers.add(x);
players.get(i).numOfGuesses++;
if (x == players.get(i).number)
{
System.out.println("That's correct!");
System.out.println("It took you " + players.get(i).numOfGuesses + " tries!");
System.out.print("These are all the numbers you guessed: ");
System.out.println(players.get(i).guessedNumbers);
do
{
System.out.println("Would you like to play again: Yes or No");
String answer = keyboard.nextLine();
if (answer.compareToIgnoreCase("yes") == 0)
{
playError = false;
players.get(i).number = myRand.nextInt(100) + 1; // creates a new random number for second round of the game
System.out.println("\n\n************ " +players.get(i).name + " WON ********");
System.out.println("\n************* SECOND ROUND STARTS **********");
}
else if (answer.compareToIgnoreCase("no") == 0)
{
playError = false;
System.out.println("Thank you for playing");
System.out.println("\n\n************ " +players.get(i).name + " WON ********");
System.out.println("\n************* SECOND ROUND STARTS **********");
players.remove(i);
}
else
{
System.out.println("You answer was invalid");
playError = true;
}
} while (playError);
}
else if (x>players.get(i).number)
System.out.println("Lower than that!");
else if (x<players.get(i).number)
System.out.println("Higher than that!");
if(i == noPlayer-1 || !(playError))
i = 0;
else
i++;
}while (players.size() > 0);
System.out.println("\n\n******************** Every Body Guessed Their Numbers ******************");
}
static int checkint()
{
int enteredNumber = 0;
Scanner myScanner = new Scanner(System.in);
boolean numberError = false;
do
{
try
{
enteredNumber = Integer.parseInt(myScanner.next().trim());
if (enteredNumber < 0 || enteredNumber > 100)
{
System.out.println("Either you entered a negative number or number is above the random number generator range");
numberError = true;
}
else
numberError = false; //if we haven't bailed out, then the number must be valid.
} catch(Exception e)
{
System.out.println("Your entry is invalid...Please try again");
numberError = true; //Uh-Oh...We have a problem.
}
} while (numberError); //Keep asking the user until the correct number is entered.
return enteredNumber;
}
}
// now each player would have its own record.
class Player
{
int numOfGuesses= 0;
ArrayList<Integer> guessedNumbers = new ArrayList<Integer>();
String name = "";
int number = 0;
public Player(String nam)
{
name = nam;
}
}
NOTE: I've added some new lines to output on the screen , once a players wins and want to play again or not. I recommend you to compare your code with mine, so that you'll get a better understanding of your approach vs mine. Do let me know if you find something difficult to understand.
Just use the Random class:
Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);
I referenced here.
How do I generate random integers within a specific range in Java?
public class Game {
public static void main(String[] args) {
String secretWord = "frog";
System.out.println("Word has " + secretWord.length() + " letters.");
System.out.println("Guess a letter: ");
int correctGuesses = 0;
int strikes = 5;
Scanner input = new Scanner(System.in);
while (strikes > 0) {
here the loop cycles through the characters in a String, and checks if the user input guessedLetter matches a char in the string. right now the loop cycles through each char starting with the first char in the string through the last, the user must guess the letters in the exact order of they are arranged in the string, how can I fix this so that any character input matching a character in the String will be correct rather than the characters having to be in order?
for (int i = 0; i < secretWord.length(); i++) {
char guessedLetter = input.next().charAt(0);
char currentLetter = secretWord.charAt(i);
if (guessedLetter == currentLetter) {
correctGuesses++;
System.out.printf("Correct Guess! %d Letters Left!\n", secretWord.length() - correctGuesses);
}
else if (guessedLetter != currentLetter) {
strikes--;
System.out.printf("Incorrect: You Have %d Chances Left..\n", strikes);
}
if (strikes == 0) {
System.out.println("You Are Out of Chances! Game over!");
}
else if (correctGuesses == secretWord.length()) {
System.out.println("You Got It! The Word is: " + secretWord);
}
}
}
}
You could try it as follows:
move all the characters of secretWord to a map (key would be the character and the value would be incidences of that character in the string).
read the character from the keyboard and interate (basically, your logic).
Here is the code.
public static void main(String[] args) {
String secretWord = "frog";
Map<Character, Integer> mapOfLetters = new HashMap<>();
for (char c : secretWord.toCharArray()) {
int count = 1;
if (mapOfLetters.containsKey(c)) {
count = mapOfLetters.get(c) + 1;
}
mapOfLetters.put(c, count);
}
System.out.println("Word has " + secretWord.length() + " letters.");
System.out.println("Guess a letter: ");
int correctGuesses = 0;
int strikes = 5;
Scanner input = new Scanner(System.in);
while (strikes > 0 && !mapOfLetters.isEmpty()) {
char guessedLetter = input.next().charAt(0);
if (mapOfLetters.containsKey(guessedLetter)) {
correctGuesses++;
System.out.printf("Correct Guess! %d Letters Left!\n", secretWord.length() - correctGuesses);
int count = mapOfLetters.get(guessedLetter) - 1;
if (count == 0) {
mapOfLetters.remove(guessedLetter);
} else {
mapOfLetters.put(guessedLetter, count);
}
} else {
strikes--;
System.out.printf("Incorrect: You Have %d Chances Left..\n", strikes);
}
}
if (strikes == 0) {
System.out.println("You Are Out of Chances! Game over!");
} else if(mapOfLetters.isEmpty()){
System.out.println("You Got It! The Word is: " + secretWord);
}
}
guessedLetter = input.next().charAt(0);
If you want to match the whole UserInput there should not be charAt(0).
On the other hand, if you just want to match any character, at first time you can test guessedLetter == currentLetter is true, then just exit program.
By the way, if you like, just google "KMP algorithm" to learn how to match String.
I am not sure how to get the program to print out double letters in a word like soccer. Whenever soccer is chosen by the random generator, and I guess the letter "c" the system out prints ••c•••. I would want it to print ••cc••. Any help at all would be appreciated
import TurtleGraphics.*;
import java.util.Scanner;
import java.util.Random;
public class HangmanGame
{
public static void main(String [] args)
{
String repeat = "yes";
while((repeat.equals("yes"))||(repeat.equals ("Yes")))
{
SketchPadWindow pad = new SketchPadWindow(800, 800);
StandardPen pen = new StandardPen(pad);
Scanner scan = new Scanner(System.in);
HangmanTest hang = new HangmanTest();
Random randomGenerator = new Random();
//Ints
int index=0;
int number=0;
int counter=0;
int randomNum = 0;
//Strings
String Secretword = "";
String choose = "";
String guessLetter = "";
String guesses = "";
String diff = "";
String Pokemon [] = {"pikachu", "jigglypuff", "dugtrio", "muk", "ditto", "eevee", "mewtwo", "cyndaquil", "raikou"};
String Sports [] = {"tennis", "rowing", "golf", "lacrosse", "sailing", "soccer", "football", "baseball", "volleyball"};
String Periodic [] = {"iron", "carbon", "radon", "ununcodium", "oxygen", "magnesium", "antimoney", "iodine", "cadmium"};
String Food [] = {"pizza", "spaghetti", "muffin", "bagel", "chicken", "steak", "apple", "chips", "cookies"};
String Boardgames [] = {"life", "monopoly", "battleship", "boggle", "sorry", "operation", "blokus", "cranium", "gab"};
String Planets [] = {"mars", "pluto", "saturn", "earth", "jupiter", "uranus", "neptune", "mercury", "venus"};
String States [] = {"utah", "washington", "colorado", "california", "texas", "wyoming", "missouri", "kentucky", "connecticut"};
String Spanish [] = {"hola", "adios", "feliz", "durante", "conocer", "sobre", "decir", "trabajar", "manzana"};
String ACT [] = {"congregation", "camaraderie", "digression", "emulate", "fortuitous", "frugal", "evanescent", "hypothesis", "extenuating"};
String dashes = "";
hang.drawGallo(pen);
System.out.println("There are three difficulties to chose from with sub categories in each");
System.out.println("They are: Easy, Medium and Hard");
diff = scan.nextLine();
if(diff.equals("Easy")){
System.out.println("Please choose one of the three following categories:");
System.out.println("Sports, Food or Boardgames");
choose = scan.nextLine();
if(choose.equals("Sports")){
randomNum = randomGenerator.nextInt(Sports.length-1);
Secretword = Sports[randomNum];
}else if (choose.equals("Food")){
randomNum = randomGenerator.nextInt(Food.length-1);
Secretword = Food[randomNum];
}else if (choose.equals("Boardgames")){
randomNum = randomGenerator.nextInt(Boardgames.length-1);
Secretword = Boardgames[randomNum];
}
}else if (diff.equals("Medium")){
System.out.println("Please choose one of the three following categories:");
System.out.println("Pokemon, Planets or States");
choose = scan.nextLine();
if(choose.equals("Pokemon")){
randomNum = randomGenerator.nextInt(Pokemon.length-1);
Secretword = Pokemon[randomNum];
}else if(choose.equals("Planets")){
randomNum = randomGenerator.nextInt(Planets.length-1);
Secretword = Planets[randomNum];
}else if(choose.equals("States")){
randomNum = randomGenerator.nextInt(States.length-1);
Secretword = States[randomNum];
}
}else if (diff.equals ("Hard")){
System.out.println("Please choose one of the three following categories:");
System.out.println("Periodic, Spanish or ACT");
choose = scan.nextLine();
if(choose.equals("Periodic")){
randomNum = randomGenerator.nextInt(Periodic.length-1);
Secretword = Periodic[randomNum];
}else if(choose.equals("Spanish")){
randomNum = randomGenerator.nextInt(Spanish.length-1);
Secretword = Periodic[randomNum];
}else if(choose.equals("ACT")){
randomNum = randomGenerator.nextInt(ACT.length-1);
Secretword = ACT[randomNum];
}
}
for(int x = 0; x< Secretword.length(); x++)
dashes += "*";
System.out.println(dashes);
while(number <= 9 && !dashes.equals(Secretword) )
{
String letter = "";
System.out.println("Please enter a letter or the entire word.");
letter = scan.nextLine();
if(letter.equals(Secretword))
{
System.out.println("You correctly guessed the word. Good job!");
break;
}
if(Secretword.indexOf(letter) != -1)
{
index = Secretword.indexOf(letter);
/*for (int x=0; x <Secretword.length() - 1; x++)
{
if (Secretword.charAt(x) == Secretword.charAt(x +1))
{
System.out.println("Word contains double");
}else
{
System.out.println("Normal word found");
}
}
*/
System.out.println("You entered a letter in the word");
dashes = dashes.substring(0, index) + letter + dashes.substring(index +1);
System.out.println(dashes);
}
else
{
System.out.println("You entered an incorrect letter");
number++;
}
if(number == 1)
hang.drawHead(pen);
if(number == 2)
{
hang.drawReye(pen);
hang.drawLeye(pen);
hang.drawPupils(pen);
}
if(number == 3)
{
hang.drawNose(pen);
hang.drawMouth1(pen);
}
if(number == 4)
hang.drawTeeth(pen);
if(number == 5)
hang.drawHair(pen);
if(number == 6)
hang.drawLglasses(pen);
if(number == 7)
hang.drawBody(pen);
if(number == 8)
{
hang.drawRarm(pen);
hang.drawLarm(pen);
}
if(number == 9)
{
hang.drawLleg(pen);
hang.drawRleg(pen);
}
}
if(number == 10){
System.out.println("You lose");
System.out.println("The word was:" + " " + Secretword);
}else
{
System.out.println("You win");
}
System.out.println("Game Over");
System.out.println("Would you like to play again?");
repeat = scan.nextLine();
}//end over all while loop
System.exit(0);
}//close main function
}//close class
I see you tried to fix it so you know where the problem is. The simplest way to get it working would be something like:
if(Secretword.indexOf(letter) != -1)
{
System.out.println("You entered a letter in the word");
while(Secretword.indexOf(letter) != -1)
{
index = Secretword.indexOf(letter);
dashes = dashes.substring(0, index) + letter + dashes.substring(index +1);
}
System.out.println(dashes);
}
else
{
System.out.println("You entered an incorrect letter");
number++;
}
That is until someone enters * and it'll freeze. I'll leave that to you to fix ;)
how do i make the else statement input whether the numbers that i entered are palindrome or not? the first part works nad im just stuck in the else statement trying to figure out how to make it work. heres my code
import java.util.*;
public class Lab6
{
public static void main (String [] args)
{
String pal1, pal2="";
int choice;
Scanner in = new Scanner(System.in);
System.out.println("Word(w) or Number(n)?");
choice = in.nextLine().charAt(0);
if (choice == 'w') {
System.out.println("Enter a word: ");
pal1= in.nextLine();
int length = pal1.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
pal2 = pal2 + pal1.charAt(i);
if (pal1.equals(pal2))
System.out.println("The word you entered is a palindrome.");
else
System.out.println("The word you entered is not a palindrome.");
}
else{
System.out.println("Enter a bunch of numbers: ");
pal1 = in.nextLine();
pal1 = String.valueOf(in.nextInt());
int numLength = pal1.length();
for ( int j = numLength - 1 ; j >= 0 ; j-- )
pal2 = pal2 + pal1.charAt(j);
if (pal1.equals(pal2))
System.out.println("The numbers you entered is a palindrome.");
else
System.out.println("The numbers you entered is not a palindrome.");
}
}
}
Your question is very ambiguous, if you are trying to tell the user that the string entered is NOT a palindrome, then see bellow...
Have you tried putting the if statement in brackets? you have to careful when writing if/for statement without them.
public class Lab6
{
public static void main (String [] args)
{
String pal1, pal2="";
int choice;
Scanner in = new Scanner(System.in);
System.out.println("Word(w) or Number(n)?");
choice = in.nextLine().charAt(0);
if (choice == 'w') {
System.out.println("Enter a word: ");
pal1= in.nextLine();
int length = pal1.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
pal2 = pal2 + pal1.charAt(i);
if (pal1.equals(pal2)){
System.out.println("The word you entered is a palindrome.");
} else{
System.out.println("The word you entered is not a palindrome.");
}
}
else{
System.out.println("Enter a bunch of numbers: ");
pal1 = in.nextLine();
pal1 = String.valueOf(in.nextInt());
int numLength = pal1.length();
for ( int j = numLength - 1 ; j >= 0 ; j-- )
pal2 = pal2 + pal1.charAt(j);
if (pal1.equals(pal2))
System.out.println("The numbers you entered is a palindrome.");
else
System.out.println("The numbers you entered is not a palindrome.");
}
}
}
Good luck with your lab ;)
Also something like this might be more efficient:
boolean isPal(String input) {
// go through half the string length
for (int i = 0; i < input.length() / 2; i++) {
// match first half to second half (regardless if odd or even)
// -1 because strings starta at a 0 index
if (input.charAt(i) != input.charAt(input.length() - 1 - i)) {
return false;
}
}
return true;
}