Java String Array, count number of spaces " " [duplicate] - java

This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 2 years ago.
I am requesting a string from the user. After the user enters their strings a prompt asks if they want to see strings with no, one or more spaces in their strings, then displays the strings.
I am running into issues with counting the spaces in the string. The code provided only counts 1 if there is more than one space in the string. Whole code:
import java.util.*;
import java.util.Scanner;
public class CountSpacesInStrings {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String[] array = new String[20];
System.out.println("Please enter anything..., or type QUIT to quit.");
for (int i = 0; i < array.length; i++) {
array[i] = s.nextLine();
boolean result = Arrays.stream(array).anyMatch("QUIT"::equals);
if(result)
{
break;
}
}
String str = null;
int len = -1;
System.out.println("Would you like to display strings with No Spaces, One Space or More? Type No, One, More to see the results: ");
String answer = s.nextLine();
if(answer.equals("No")){
for (int i = 0; i < array.length;i++) {
int count = 0;
if (array[i] != null) {
if (array[i].charAt(i) != ' ') {
count++;
System.out.println(count);
}
}
}
}
else if(answer.equals("One"))
{
for (int i = 0; i < array.length;i++) {
int count = 0;
if (array[i] != null) {
if (array[i].charAt(i) != ' ') {
count++;
System.out.println(count);
}
//System.out.print(array[i] + " ");
}
}
}
else
System.out.println("No values to show");
System.out.println();
}
}
The section I'm looking at is:
if(answer.equals("No")){
for (int i = 0; i < array.length;i++) {
int count = 0;
if (array[i] != null) {
if (array[i].charAt(i) != ' ') {
count++;
System.out.println(count);
}
}
}

Based on the comment of #Pshemo: You would need to add a nested for loop. The second for loop has to iterate through the contents of array[i] (which makes one sentence) and count the number of ' ' characters in that sentence.

Related

For loop is printing out multiple print statements

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

Palindrome with even numbers

I've been working on a palindrome and it won't support an even number of words. I'm not the best at coding. It supports words like "racecar" or "tacocat", but it won't let me use a word/name like "Hannah". I'm new at this coding stuff so anything would really be appreciated.
import java.util.Scanner;
public class Palindrome
{
public static void main(String args [])
{
System.out.printf("\f");
Scanner input = new Scanner(System.in);
System.out.println("enter a word");
String word = input.nextLine();
int size = word.length();
int correct = 0;
int incorrect = 0;
for (int count = 1; count < size; count++)
{
int start = (word.charAt(count));//starting
int end = (word.charAt(size-count));//ending
if (start == end)
correct++;
else
incorrect++;
}
if (correct == 0)
System.out.printf("%s is a palindrome", word);
else
System.out.printf("%s is not a palindrome", word);
}
}
Your code has many problems:
You are comparing characters of wrong indices. For example, you compare the second character (whose index is 1) to the last character (whose index is size - 1). count should be initialized to 0, and end should be word.charAt(size-count-1).
You report the String to be a palindrome when correct == 0, when it should be incorrect == 0 (BTW you don't need a counter, just a boolean).
If you want the check to be case insensitive, you can convert the String to lower case prior to running your loop.
This should work:
public static void main(String args [])
{
System.out.printf("\f");
Scanner input = new Scanner(System.in);
System.out.println("enter a word");
String word = input.nextLine().toLowerCase();
int size = word.length();
boolean isPalindrome = true;
for (int count = 0; count < size; count++)
{
int start = (word.charAt(count));//starting
int end = (word.charAt(size-count-1));//ending
if (start != end) {
isPalindrome = false;
break;
}
}
if (isPalindrome)
System.out.printf("%s is a palindrome", word);
else
System.out.printf("%s is not a palindrome", word);
}
There are several mistakes in your code
You should convert everything to lowercase if you are planning to ignore capital letter in the checking, since it is identified differently in ASCII
For starting, you should start from index 0 instead of 1, to start from the first letter
For ending, you should start from index size-count-1 instead of size-count, to start from the last letter
You should check for incorrect == 0 instead of correct == 0 to determine if it is a palindrome
public static void main(String args[]) {
System.out.printf("\f");
Scanner input = new Scanner(System.in);
System.out.println("enter a word");
String word = input.nextLine().toLowerCase();
int size = word.length();
int correct = 0;
int incorrect = 0;
for (int count = 0; count < size; count++)
{
int start = (word.charAt(count)); //starting
int end = (word.charAt(size-count-1)); //ending
if (start == end)
correct++;
else
incorrect++;
System.out.println(start + " " + end);
}
if (incorrect == 0)
System.out.printf("%s is a palindrome", word);
else
System.out.printf("%s is not a palindrome", word);
}
Bonus: You could check for just half of the word instead of looping through the whole word
First of all you should know that array in java start at 0, not one. so set your count from 0 not one.
Then, word.charAt(count) is a char so better have char variable instead of int.
It's seem that the algorithm you use to decide whether a word is a palindrome or not is by matching first char with last char, second char with second last char, and so on.
If that the case, you will only need to loop halfway for (int count = 1; count < size / 2; count++).
The last one is, you only need one variable to hold the status of palindrome, if your matching process ever find a false then break the loop and just set the isPalindrome status into false.
public static void main (String args[])
{
Scanner input = new Scanner (System.in);
System.out.println ("enter a word");
String word = input.nextLine ();
int size = word.length ();
boolean isPalindrome = true;
int maxIndex = size - 1;
for (int count = 0; count < size / 2; count++)
{
char start = word.charAt (count);
char end = word.charAt (maxIndex - count);
if (start != end)
{
isPalindrome = false;
break;
}
}
if (isPalindrome)
System.out.printf ("%s is a palindrome", word);
else
System.out.printf ("%s is not a palindrome", word);
}
And bear in mind that java's String is case sensitive, so "Tiger" is different than "tiger". Hence, Hannah will not be treated as palindrome. If you want it to be case insensitive, just lowercase all the char in the word like this word = word.toLowerCase() before doing the macthing process.
Check palindrome function is very simple:
public boolean isPalindrome(String str) {
if(str == null)
return false;
str = str.toLowerCase();
for(int i = 0, j = str.length() - 1; i < j; i++, j--)
if(str.charAt(i) != str.charAt(j))
return false;
return true;
}
you may use Stringbuilder to do palindrome check as below
public class test {
public static void main(String args [])
{
System.out.print("\f");
Scanner input = new Scanner(System.in);
System.out.println("enter a word");
String word = input.nextLine();
StringBuilder originalStr = new StringBuilder(word);
String revString = originalStr.reverse().toString();
if(word.equalsIgnoreCase(revString))
System.out.print( word +" is a palindrome");
else
System.out.print( word +" is not a palindrome");
}
}

Array out of Bounds? with string split

Array out of bounds ? i'm trying to perform the output in the picture:
Using this INPUT
"JAVA IS A PROGRAMMING LANGUAGE"
This is my code so far
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input Phrase:");
String s = in.nextLine();
String[] word=s.split(" ");
String rts=" ";
for(int i=0;i<word.length;i++){
if(word[i].length()>=rts.length()){
rts=word[i];
}
}
int thisislength = rts.length();
for (int a = 0; a < thisislength ;a++ ) {
for (int b = 0; b < word.length ;b++ ) {
System.out.print(word[b].charAt(a)+" ");
}
System.out.println();
}
}
}
When the second word reaches its last letter it doesn't continue the for loop, is there any way to continue the loop even if the second word reaches its max length.
< should have been <=. Reversing left and right hand sides makes it more readably I think.
for (int a = 0; a < thisislength; a++) {
System.out.printf("%3d ", a+1);
for (int b = 0; b < word.length; b++) {
if (a >= word[b].length()) {
System.out.print(' ');
} else {
System.out.print(word[b].charAt(a));
}
System.out.print(' ');
}
System.out.println();
}
Or instead of the if-else statement:
for (String w : word) {
System.out.print(a >= w.length() ? ' ' : w.charAt(a));
}
This gives the result you want:
for (int a = 0; a < thisislength ;a++ ){
for (int b = 0; b < word.length ;b++ ){
if(word[b].length() < a + 1){
System.out.print(" ");
}else{
System.out.print(word[b].charAt(a) + " ");
}
}
System.out.println();
}
This line was changed:
if(word[b].length() < a + 1) and not if(word[b].length() < a)
and 2 spaces print in the if statement
TRY THIS SOLUTION HOPE IT WILL HELP YOU :
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
// GET VALUE FROM THE CONSOLE
Scanner in = new Scanner(System.in);
System.out.print("Input Phrase:");
String s = in.nextLine();
// SPLIT STRING TO WORDS
String[] words = s.split(" ");
// CREATE A LIST OF CHAR_ARRAY CALLED : matrix
List<char[]> matrix = new ArrayList<char[]>();
// REFERENCE THE LARGEST WORD IN WORDS ARRAY EX : PROGRAMMING IS THE LARGEST
int max = 0;
// FILL OUR LIST OF ARRAY OF CHARS
for (int b = 0; b < words.length ;b++ ) {
char[] chars = words[b].toCharArray();
max = (chars.length >= max)? chars.length : max ;
matrix.add( chars );
}
// PRINT OUR CHAR
for (int a = 0; a < max ;a++ ) {
for (int b = 0; b < words.length ;b++ ) {
if(a < matrix.get(b).length) {
System.out.print(matrix.get(b)[a]);
System.out.print(" ");
}else {
System.out.print(" ");
System.out.print(" ");
}
}
System.out.println("");
}
}
}

replace all underscores (if any) with vowels present in the string

You are given a string s consisting of lowercase English letters
and/or '_' (underscore). You have to replace all underscores (if any)
with vowels present in the string.
The rule you follow is: Each underscore can be replaced with any one
of the vowel(s) that came before it.
You have to tell the total number of distinct strings we can generate
following the above rule.
My code is giving wrong output on some input
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
String test = sc.nextLine();
int a=0,e=0,i1=0,o=0,u=0;
int ans = 1;
for(int j=0;j<Integer.parseInt(test);j++){
String s = sc.nextLine();
// System.out.println(s);
for(int i=0;i<s.length();i++){
if( s.charAt(i)=='a' || s.charAt(i)=='o' || s.charAt(i)=='i' || s.charAt(i)=='e' || s.charAt(i)=='u' ) {
if(s.charAt(i)=='a')
a=1;
else if(s.charAt(i)=='e')
e=1;
else if(s.charAt(i)=='i')
i1=1;
else if(s.charAt(i)=='o')
o=1;
else if(s.charAt(i)=='u')
u=1;
}
else if(s.charAt(i)=='_'){
int sum = a + e +i1 +o + u;
if(sum != 0)
ans = ans * sum;
}
}
if(ans!=0)
System.out.println(ans);
else
System.out.println(1);
ans = 1;
a=0;
e=0;
i1=0;
o=0;
u=0;
}
}
}
Iterate over the string and maintain the count of vowels
As soon as you encounter an underscore, multiply count of vowels with the sum.
int sum = 1, noOfVowels = 0;
for(int i=0; i<str.length(); i++) {
if("aeiou".indexOf(str.charAt(i)) >= 0) {
noOfVowels++;
} else if("_".indexOf(str.charAt(i)) >= 0) {
sum = (sum * noOfVowels <= 0) ? 1: sum * noOfVowels;
}
}
return sum;
Input: a_e_i
Output: 2 (aAeAi, aAeEi)
Input: ae_io_
Output: 8
(aeAioA,aeAioE,aeEioA,aeEioE,aeAioI,aeAioO,aeEioI,aeEioO)

Hangman wrong guesses not printing correctly

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.

Categories