keep getting an error with this code - java

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;
}

Related

Resetting Counter Java

import java.util.Scanner;
public class VowelsAndConsonants {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int ConsonantCount = 0;
int VowelCount = 0;
int num = 0;
int x = 0;
while(true) {
System.out.print("Enter a string: ");
String userInput = input.next();
num = userInput.length();
for(x = 0; x < num ; x++) {
char c = userInput.charAt(x);
if (Character.isLetter(c)){
c = Character.toUpperCase(c);
if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
VowelCount++;
else
ConsonantCount++;
}
}
System.out.println("The number of vowels is: " + VowelCount);
System.out.println("The number of consonants is: " + ConsonantCount);
System.out.println("Do you want to enter another string? ");
String loopAgain = input.next();
if (loopAgain.equalsIgnoreCase("N")) {
break;
}
}
}
}
How do I reset the VowelCount and ConsonantCount after looping again? Currently, it's adding onto the counter without resetting to zero. Please help. My instructor wants me to break out of the loop if I say N or loop again if its any other character
I'm assuming you want to reset it after you print?
All you need to do is assign it like any other variable
System.out.println("The number of vowels is: " + VowelCount);
System.out.println("The number of consonants is: " + ConsonantCount);
ConsonantCount = 0;
VowelCount = 0;
Another route you could take would be to declare your variables at the beginning of the while loop. This way, every time the while loop runs, it re-initializes the variables to zero, so you don't have to even reset it.
while (true) {
int ConsonantCount = 0;
int VowelCount = 0;
....
}

How to break from a loop after finding a word

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.

Counting occurrences

I'm trying to write a code that will count the number of occurrences of 1 string in another string. So for if the user enters "hello" and then enter "e" the code should say "There is 1 occurrence of "e". However, my current executes an infinite loop.
I've tried changing the condition on the for loop to inputEntry.equals(inputCharacter) but also had an infinite loop.
package charcounter;
import java.util.Scanner;
public class CharCounter {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String inputEntry;
String inputCharacter;
System.out.println("Please enter a multi word string: ");
inputEntry = scnr.nextLine();
System.out.println("Enter another string: ");
inputCharacter = scnr.nextLine();
if (inputCharacter.length() == 1){
while (inputEntry.contains(inputCharacter)){
int occurrences = 0;
for(occurrences = 0;inputEntry.contains(inputCharacter); occurrences++ ){
System.out.println("There is " + occurrences + " of " + inputCharacter);
}
}
}
else{
System.out.println("Your string is too long.");
}
}
}
So for if the user enters "hello" and then enter "e" the code should say "There is 1 occurrence of "e".
The inputEntry.contains(inputCharacter) in your code always return true => endless loop
You can change to indexOf for your requirement.
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = inputEntry.indexOf(inputCharacter,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += inputCharacter.length();
}
}
You can change your code to
if (inputCharacter.length() == 1){
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = inputEntry.indexOf(inputCharacter,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += inputCharacter.length();
}
}
System.out.println("There is " + count + " of " + inputCharacter);
}
else{
System.out.println("Your string is too long.");
}

Creating simple hangman program in java, trouble with for loop

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.

java source code hangman

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.

Categories

Resources