For simple words as "madam", "madama" etc., the code is working but for longer Strings like "babzsákfotelben sok a bab" returns wrong answer.
Scanner sc = new Scanner(System.in);
String A = sc.nextLine();
String myString = A.toLowerCase().replaceAll("\\s", "");
int i = 0;
int j = myString.length() - 1;
while (i < j) {
if (myString.charAt(i) != myString.charAt(j)) {
System.out.println("No");
break;
}
i++;
j--;
System.out.println("Yes");
break;
}
}
}
Problem in your current code is that your loop only executes once because after incrementing i and decrementing j, you print "Yes" and break out of the loop.
What you should do is declare a boolean variable that is initialized with the value true. Inside the loop, in any iteration, if the if condition evaluates to true, set that boolean variable's value to false and break out of the loop.
After the loop ends, check if the value of the boolean variable is still true. If it is, then string is a palindrome, otherwise its not.
int i = 0;
int j = myString.length() - 1;
boolean isPalindrome = true;
while (i < j) {
if (myString.charAt(i) != myString.charAt(j)) {
isPalindrome = false;
break;
}
i++;
j--;
}
if (isPalindrome) {
System.out.println("Yes");
} else {
System.out.println("No");
}
**What you can do is instead of using a while loop, you can use for loop, and instead of a string, you can use StringBuilder. Here's how it goes:
**
public class Palindrome {
public static void main(String[] args) {
//Creating an instance of scanner class
Scanner scan = new Scanner(System.in);
//Creating an instance of StringBuilder class
StringBuilder str = new StringBuilder();
//Asking for input
System.out.println("Please Enter the Word: ");
//Getting Input
String word = scan.next();
/*
*
* Palindrome Check
*
*/
for (int i = word.length() - 1; i >= 0; i--) {
str.append(word.charAt(i));
}
if (word.equalsIgnoreCase(String.valueOf(str))) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
I'm making a program for class which prints out the number of vowels in a word and any help would be appreciated. Currently, the program prints out the correct number of vowels but also prints out the print statement, "vowels:" multiple times before. I've tried moving the print statement and the braces around but it says "error: 'else if' without 'if'". I'm completely new to Java so sorry if the solution is in plain sight. Thank you in advance :)
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels= 0;
int l;
l= text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i,i+1);
if (wordPRT.compareToIgnoreCase("a")==0 || wordPRT.compareToIgnoreCase("e")==0||
wordPRT.compareToIgnoreCase("i")==0
|| wordPRT.compareToIgnoreCase("o")==0
|| wordPRT.compareToIgnoreCase("u")==0){
vowels++;
System.out.println("vowels: " + vowels);
}
else if(vowels<1){
System.out.print("no vowels");
}
}
}
}
You are printing everything in a for loop instead of count vowels and print at the end.
try something like:
int vowelsCounter = 0;
for(...) {
... logic to count the vowels
if(isvowel(string.charAt(i)){
vowelsCountr++;
}
}
if(vowelsCounter > 0 ) {
printSomething
}
else {
print something else
}
Also You should not use subString for this kind of a loop but string.charAt(i)
Move the print statements out of the for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels = 0;
int l;
l = text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i, i + 1);
if (wordPRT.compareToIgnoreCase("a") == 0 || wordPRT.compareToIgnoreCase("e") == 0
|| wordPRT.compareToIgnoreCase("i") == 0 || wordPRT.compareToIgnoreCase("o") == 0
|| wordPRT.compareToIgnoreCase("u") == 0) {
vowels++;
}
}
if (vowels >= 1) {
System.out.println("vowels: " + vowels);
} else {
System.out.print("no vowels");
}
}
}
A sample run:
Enter text: Hello
vowels: 2
The problem code is below, if you need the entire main method to help me, please ask. The code complies but does not run as expected. I am trying to make the code report back an exclamation mark if the number is out of bounds/larger than the last position of the source text, which is a string the user inputs, so the length cannot be predefined. Exception is 'StringIndexOutOfBoundsException'
TDLR num is an int, sourcetext is a string, both are inputs. Exception: when code should output an '!' instead.
import java.util.Scanner;
public class Temp {
public static void main(String[] args) {
Scanner sc;
int result, num= 0, end = -2, temp, infolost, count;
String word, sourcetext, answer, space= " ";
String sourcetext2, temp2;
char input, result2, chalost;
sc = new Scanner(System.in);
System.out.println("please enter sourcetext");
sourcetext = sc.nextLine(); // user inputs source text
sourcetext = sourcetext.toLowerCase(); // converts sourcetext into lowercase
System.out.print("Would you like to 1 encrypt, or 2 decrypt?");
answer = sc.next(); // user inputs choice
if (answer.equals("1")||(answer.equals("encrypt"))) {
System.out.println("Please enter at least one word to encrypt");
word = sc.next(); // user inputs one word
for (int i= 0; i < word.length(); i++) {
temp = sourcetext.indexOf(word.charAt(i)); // uses index to convert char positions int num
System.out.print(space + temp + space);
}
System.out.print(space + end);
}
else if (answer.equals("2")||(answer.equals("decrypt"))) {
System.out.println("Please enter digits, with one space between each. End with -2");
while (num > -2) {
num = sc.nextInt(); // num to decrypt
if (num > -2) {
result2 = sourcetext.charAt(num); // num converted into characters
System.out.print(result2);
} else if (num > sourcetext.length()) {
System.out.print("!");
} else if (num<0) {
System.out.print("end");
}
}
}
}
}
Try it like this:
int stringLength = sourcetext.length();
if (num > stringLength) {
System.out.print("!");
}
else if (num<0) {
System.out.print("end");
}
This could lead to an IndexOutOfBoundsException - since -1 is greater than -2 - but still out of bounds...
if (num > -2){
result2 = sourcetext.charAt(num); // num converted into characters
System.out.print(sourcetext.indexOf(num));
}
Edit: Unless the users input is -2 - the first if-Statement will always run... You probably need to re-work the logic there.
Edit2: If num is -1 sourcetext.charAt(num); leads to an IndexOutOfBounds. Do something like
if(num == -2) {
System.out.print("end");
} else if (num >= 0 && num < sourcetext.lenght()) {
// index ok
result2 = sourcetext.charAt(num); // num converted into characters
System.out.print(result2);
} else {
// index out of bounds
System.out.print("!");
}
I mostly have the method done but I am confused when it comes to the If statement concerned with storing a variable with the word with the most amount of vowels, NOTE I am not allowed to use arrays.
below is my code
//method for vowels and consonants
public static int Vowelcount(String sentence)
{
int maxvowelcount =0;
int minvowelcount =0;
String vowel="";
int consonantcount = 0;
int vowelcount = 0;
int index = 0;
String currentword;
int spacePos;
int noOfchars = 0;
int largest = 0 ;
int smallest = 0 ;
//gets rid of leading and trailing spaces so as to get the last word
sentence=sentence.trim() + " ";
//assignments
spacePos=sentence.indexOf(" ");
currentword = sentence.substring(0, spacePos);
while (spacePos >-1)// when no spaces are found
{
noOfchars=0;
currentword = sentence.substring(0, spacePos);
// remove the first word
sentence = sentence.substring(spacePos+1);
spacePos=sentence.indexOf(" ");
// to count the number of vowels in the string
for(index = 0; index<currentword.length(); index++)
{
if(currentword.charAt(index)=='a' || currentword.charAt(index)=='e' ||
currentword.charAt(index)=='i' || currentword.charAt(index)=='o' ||
currentword.charAt(index)=='A' || currentword.charAt(index) == 'E' ||
currentword.charAt(index) == 'I' || currentword.charAt(index) == 'O' )
{
vowelcount++;
}
else
{
consonantcount++;
}
//if statement to overwrite currentword with largest/smallest
if (index == 0)
{
minvowelcount = currentword.length();
maxvowelcount = currentword.length();
}
if (vowelcount < minvowelcount)
{
minvowelcount = vowelcount;
}
if (vowelcount > maxvowelcount)
{
maxvowelcount = vowelcount;
vowel=currentword;
}
}
}
//output to show the word with largest amount of vowels
System.out.println( "word with largest amount of vowels is " + vowel);
return vowelcount;
}
First, many of the variables you use are redundant. All you need is the max number of vowels and the word.
Next point is that all your if statements should be outside the for loop. The general structure must be smth like
wordWithMaxVowels = "";
maxVowels = 0;
while (there is a word) {
fetch the word
vowelCount = 0;
for (every char in the word)
{
if (char is vowel)
vowelCount++;
}
if (vowelCount > maxVowels)
{
vowelCount = maxVowels;
wordWithMaxVowels = word;
}
}
// here maxVowels is the maximal number of vowels in a word, wordWithMaxVowels is the word itself;
Also note, that it's not any optimal to chop off the first word in the sentence. Try the following:
int wordStart = 0;
int wordEnd;
while(true) {
wordEnd = sentence.indexOf(" ", wordStart);
if (wordEnd < 0)
break;
String word = sentence.substring(wordStart, wordEnd);
// process the word
wordStart = wordEnd + 1;
}
I have this Hangman program that i am working on for school and i cant get the number of wrong guesses to print correctly when the user guesses a wrong letter. Here is my code that i got so far, i would appreciate any tips.
import java.util.Scanner;
public class HangmanTest {
public static void main(String[] args) {
String[] wordBank = { "madelynn", "crystal", "mcbride", "daughter",
"adorable", "beautiful", "andrew", "programming", "alyssa",
"computers", "mcbreezy", "maddy", "happy", "vacation", "beach",
"java", "benefical", "military", "veteran", "standale",
"lions", "tigers", "redwings", "pistons", "michigan",
"football", "baseball", "hockey", "basketball", "golf" };
int minimum = 0;
int maximum = wordBank.length - 1;
String again;
do {
int choice = minimum + (int) (Math.random() * maximum);
String word = wordBank[choice];
// Converts the random word to asterix
String userWord = "";
for (int i = 0; i < word.length(); i++) {
userWord += "*";
}
// Breaks into a bunch of characters
char[] userWordCh = userWord.toCharArray();
// Show the random word
System.out.println("The word for you to guess is " + userWord);
// instantiate a scanner object
Scanner input = new Scanner(System.in);
int size = word.length();
int rightGuesses = 0;
int wrongGuesses = 0;
while (size != rightGuesses) {
System.out.println("Enter a character: ");
String response = input.next();
char ch = response.charAt(0);
char[] wordChars = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
System.out.print("The word is: ");
for (int j = 0; j < userWordCh.length; j++)
System.out.print(userWordCh[j]);
System.out.println();
} // end of while loop
System.out.println("You had " + wrongGuesses + " wrong guesses.");
System.out.println("Would you like to play again y/n: ");
again = input.next();
} while (again.equals("y"));
}
}
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
In this loop, you increment rightGuesses by 1 every time the guess matches a letter in the word, and wrongGueeses by 1 every time the guess does not match a letter in the word. As you can imagine, this will lead to the numbers, collectively, being incremented by the same number as the number of letters, when it should only be incremented once.
Try something like:
boolean foundMatch = false;
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
if (!foundMatch)
{
++rightGuesses;
foundMatch = true;
}
}
}
if (!foundMatch)
{
++wrongGuesses;
}
// end of for loop
Now we only increment one of rightGuesses and wrongGuesses once - rightGuesses can only be incremented if we have not found a match (setting found match to true), and wrongGuesses can only be incremented once if we have not found a match.
problem is in your for loop. You are iterating over each letter, and for every letter that doesn't match yours, you mark it as an incorrect guess. It should only be marked incorrect if NONE of the letters are correct. Additionally it should only be marked right if you haven't marked it already.
import java.util.Scanner;
import java.util.ArrayList;
public class HangmanTest {
public static void main(String[] args) {
String[] wordBank = { "madelynn", "crystal", "mcbride", "daughter",
"adorable", "beautiful", "andrew", "programming", "alyssa",
"computers", "mcbreezy", "maddy", "happy", "vacation", "beach",
"java", "benefical", "military", "veteran", "standale",
"lions", "tigers", "redwings", "pistons", "michigan",
"football", "baseball", "hockey", "basketball", "golf" };
int minimum = 0;
int maximum = wordBank.length - 1;
String again;
do {
int choice = minimum + (int) (Math.random() * maximum);
String word = wordBank[choice];
// Converts the random word to asterix
String userWord = "";
for (int i = 0; i < word.length(); i++) {
userWord += "*";
}
String guessedLetters="";
// Breaks into a bunch of characters
char[] userWordCh = userWord.toCharArray();
// Show the random word
System.out.println("The word for you to guess is " + userWord);
// instantiate a scanner object
Scanner input = new Scanner(System.in);
int size = word.length();
int rightGuesses = 0;
int wrongGuesses = 0;
boolean foundLetter;
char[] wordChars = word.toCharArray();
guessLoop:
while (size != rightGuesses) {
System.out.println("Enter a character: ");
String response = input.next();
char ch = response.charAt(0);
foundLetter=false;
for (int i=0;i<guessedLetters.size();i++){
if (ch == guessedLetters.charAt(i)){
System.out.println("Already guessed that letter!");
continue guessLoop;
}
}
guessedLetters+=response;
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
foundLetter=true;
userWordCh[i] = ch;
++rightGuesses;
}
} // end of for loop
if(!foundLetter)
++wrongGuesses;
System.out.print("The word is: ");
for (int j = 0; j < userWordCh.length; j++)
System.out.print(userWordCh[j]);
System.out.println();
} // end of while loop
System.out.println("You had " + wrongGuesses + " wrong guesses.");
System.out.println("Would you like to play again y/n: ");
again = input.next();
} while (again.equals("y"));
}
}
I'm guessing here, but I think this might be wrong:
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
This will increment the rightGuesses and wrongGuesses variables for each character in the word that matches/doesn't match the inputted character. Instead, you need to set a flag when a character "matches", then check that flag at the end to update rightGuesses and wrongGuesses.
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
This for loop is causing your problem with wrong guesses, since it will say that a character is a wrong guess even though it is in the word. An option you can do is have some boolean that is switched to true when it finds the letter. That way, when you leave the for loop, you check to see if that value is true. If it isn't, increment the wrong guesses.