Problems with charAt() method in Java - java

I am trying to make a text-based Hangman in Java.
This is my Java code:
package hangman;
import java.util.Random;
import java.util.Scanner;
import java.lang.String;
public class Hangman {
public static void main(String[] args) {
// TODO code application logic here
Scanner chez = new Scanner(System.in);
Scanner waffle = new Scanner(System.in);
Random randomGenerator = new Random();
StringBuilder displayWord = new StringBuilder("______________________________");
String theWord = null;
String preLetter;
//String sbDisplayWord;
char letter = 0;
int randomNumber;
int lengthOfWord;
int numberOfLetterInWord = 0;
int gDisplay;
int guessWordNumber = 0;
String guessWord;
RandomWord troll = new RandomWord();
randomNumber = randomGenerator.nextInt(12);
//Fill var with the word.
theWord = troll.wordDecide(randomNumber);
System.out.println ("Welcome to Hangman!");
lengthOfWord=theWord.length( );
System.out.println("This word has " + lengthOfWord + " letters.");
System.out.println("You have 20 guesses.");
for (int g =19; g >= 0; g--) {
System.out.println("If you want to guess the word, type 0. If you want to guess a letter, type 1.");
guessWordNumber=chez.nextInt();
if (guessWordNumber==0) {
System.out.println("Enter the word now. Remember, don't capitalize it.");
guessWord=waffle.nextLine();
if (guessWord.equals(theWord)) {
System.out.println("YOU WIN");
System.exit(0);
} else {
System.out.println("Sorry, this wasn't the correct word.");
}
} else if (guessWordNumber==1) {
System.out.println("Please enter the letter you wish to guess with.");
//System.out.println("It will tell you if you have guessed right for any of the letters. If it is blank, that means none of the letters match.");
preLetter=chez.nextLine();
letter=preLetter.charAt(0);
System.out.println("");
for(int i = 0; i <= lengthOfWord -1; i++ ) { //-Eshan
if (letter == theWord.charAt( i )) {
numberOfLetterInWord=i+1;
System.out.println("This letter matches with letter number " + numberOfLetterInWord + " in the word.");
displayWord.setCharAt(i, letter);
} else {
numberOfLetterInWord=i+1;
System.out.println("This letter doesn't match with letter number " + numberOfLetterInWord + " in the word.");
}
}
System.out.println("");
System.out.println("The word so far is " + displayWord);
System.out.println("");
gDisplay = g + 1;
System.out.println("You have " + gDisplay + " guesses left.");
} else {
System.exit(0);
}
}
System.out.println("GAME OVER");
System.exit(0);
}
}
package hangman;
public class RandomWord {
private static String[] wordArray = {
"psychology",
"keratin",
"nostalgia",
"pyromaniac",
"chlorophyl",
"derivative",
"unitard",
"pterodactyl",
"xylophone",
"excommunicate",
"obituary",
"infinitesimal",
"concupiscent",
};
public String wordDecide(int randomNumber) {
String theWord;
theWord = wordArray[randomNumber];
return theWord;
}
}
Netbeans is giving me this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at hangman.Hangman.main(Hangman.java:56)
Java Result: 1

This is probably happening when you call charAt(0) on a string of length 0. You should check to see that the string is not empty before calling the method.

You are getting a StringIndexOutOfBoundsException due to the fact the line
guessWordNumber = chez.nextInt();
does not consume newline characters and passes the character through to the line
preLetter = chez.nextLine();
which then doesn't block as it will have already received input. This assigns an empty String to preLetter resulting in the exception. You can use Scanner#nextLine to consume this character:
guessWordNumber = Integer.parseInt(chez.nextLine());

Related

Guessing letter without having to capitalize input

I am new to this and I am having hard time with this code. I made a hangman game but I am having issues with the words that have a capital letter. If I don't input a capital letter the letter will not appear.
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Hangman {
static ArrayList<String> words = new ArrayList<>();
static boolean isCorrect;
private static Scanner input;
private static Scanner input2;
public static void main(String[] args) {
File filename = new File("hangman.txt");
if (!filename.exists()) {
System.out.println(filename.getAbsolutePath());
System.out.println(filename + " does not exist.");
System.exit(1);
}
try {
input2 = new Scanner(filename);
while (input2.hasNext()) {
words.add(input2.next());
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
input2.close();
input = new Scanner(System.in);
String playStarts = "y";
int wins = 0;
int loses = 0;
final int MAX_GUESSES = 11;
List<String> usedWords = new ArrayList<>();
while (playStarts.equals("y")) {
String word = getWord();
usedWords.add(word);
String secretWord = getSecretWord(word);
int missCount = 0;
while (!word.equals(secretWord)) {
System.out.print("(Guess) Enter a letter in word " + secretWord + " > ");
char ch = input.next().charAt(0);
if (!isAlreadyInWord(secretWord, ch)) {
secretWord = getGuess(word, secretWord, ch);
if (!isCorrect) {
System.out.print(ch + " is not in the word.");
missCount++;
System.out.println(" You missed "+ missCount + " times");
}
} else {
System.out.println(ch + " is already in word.");
}
if (missCount == MAX_GUESSES) {
System.out.println("You reached max number of guesses.");break;
}
}
if (missCount == MAX_GUESSES) {
loses++;
} else {
wins++;
}
System.out.println("The word is " + word + ". You missed " + missCount + " times");
System.out.println("Do you want to guess another word? Enter y or n >");
playStarts = input.next();
}
System.out.println("Number of wins is " + wins + ".");
System.out.println("Number of loses is " + loses + ".");
System.out.println("Used words:");
for (String word : usedWords) {
System.out.println(word);
}
input.close();
}
public static String getWord() {
return words.get((int) (Math.random() * words.size()));
}
public static String getSecretWord(String word) {
String hidden = "";
for (int i = 0; i < word.length(); i++) {
hidden += "*";
}
return hidden;
}
static public String getGuess(String word, String secretWord, char ch) {
isCorrect = false;
StringBuilder s = new StringBuilder(secretWord);
for (int i = 0; i < word.length(); i++) {
//I think the issue is in this section of the code:
if (ch == word.charAt(i) && s.charAt(i) == '*') {
isCorrect = true;
s = s.deleteCharAt(i);
s = s.insert(i, ch);
}
}
return s.toString();
}
public static boolean isAlreadyInWord(String secretWord, char ch) {
for (int i = 0; i < secretWord.length(); i++) {
if (ch == secretWord.charAt(i)) {
return true;
}
}
return false;
}
}
The code works fine but I just have an issue with the capitalization.
If your speculation be correct, the comparing the lowercase of both sides of the equation should fix the problem:
if (Character.toLowerCase(ch) == Character.toLowerCase(secretWord.charAt(i)) {
return true;
}
Better yet, you can lowercase the user character input when it actually happens:
System.out.print("(Guess) Enter a letter in word " + secretWord + " > ");
char ch = input.next().toLowerCase().charAt(0);
There are some handy functions in the Character class that you can use (Character.toUpperCase() and toLowerCase()) that can help you compare whether the characters match.
if (Character.toLowerCase(ch) == Character.toLowerCase(word.charAt(i)) && s.charAt(i) == '*') will always be checking two lowercase letters, so the case of neither ch or word.charAt(i) will matter.

Letter guessing game Java

I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!
I want the user to try and guess the letter and not the number, but i cannot workout how to do this!
(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)
Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');
Any help would be greatly appreciated! And i can display my code if it is needed
public class Stack {
public static void main(String[] args) {
Random rand = new Random(); //This is were the computer selects the Target
int guess;
int numGuesses = 0;
int Target;
String userName;
String playagain;
boolean play = true;
int session = 0;
int sessions = 0;
int bestScore = 0;
Scanner consoleIn = new Scanner(System.in);
Scanner name = new Scanner(System.in);
System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
userName = name.nextLine();
System.out.println("Hello " + userName + " :) Welcome to the game!\n");
while (play = true) {
session++;
Target = rand.nextInt(26) + 1;
System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have
do {
guess = consoleIn.nextInt();
numGuesses++;
if (guess > 26)
System.out.println("Error! Above MAXIMUM range");
else if (guess <= 0)
System.out.println("Error! Below MINIMUM range");
else if (guess > Target)
System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
else if (guess < Target)
System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
} while (guess != Target && numGuesses < 5);
if (guess == Target) {
System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
sessions++;
} else {
System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!"); //This tells the player that they failed to find the number and then tells them what the correct answer
}
{
Scanner answer = new Scanner(System.in);
System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
playagain = answer.nextLine();
if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
play = true;
numGuesses = 0;
} else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
play = false;
System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
System.out.println("You had " + session + " Goes");
System.out.println("The number of times you guessed correctly: " + sessions + "");
break;
}
}
}
}
}
use arrays of characters
char[] chars = ['A','B','C'...];
and use the random numbers to map to each character
char targetLetter = chars[r.nextInt(26)];
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Guess the Letter");
String myLetter=scan.nextLine();
//get the letter of myLetter variable then convert to Uppercase
char enteredLetter=Character.toUpperCase(myLetter.charAt(0));
//26 only because the characters array starts with index 0
char[] characters ={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
//I had created a parrallel array symbolizing int value of each letter
int[] range={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26};
//this variable convert user input to one of the array element of range
int userInputToInt=0;
//this variable is for knowing what int[] range array element must the value of userInputToInt fall
int userInputControlLoop=0;
char randomLetter=characters[(int)(Math.random()*26)];
// get the random input of computer convert it to int
int computerInputToInt=0;
//this loop is for getting the int value of randomLetter input by the computer
for(int i=0;i<characters.length;++i)
{
if(randomLetter==characters[i])
{
computerInputToInt=range[i];
}
}
//this loop is for getting the int value of user inputted letter
for(char i:characters)
{
if(enteredLetter==i)
{
userInputToInt=range[userInputControlLoop];
}
++userInputControlLoop;
}
//test the entered letter of user
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
}
//test the entered letter of user if greater than computer input
else if(userInputToInt>computerInputToInt)
{
System.out.println("Incorrect Guess");
System.out.println("The letter is too high");
System.out.println("The letter is:"+randomLetter);
}
//test the entered letter of user if lesser than computer input
else if(userInputToInt<computerInputToInt)
{
System.out.println("Incorrect Guess");
System.out.println("The letter is too low");
System.out.println("The letter is:"+randomLetter);
}
}
Use the same method that you do for your random characters. Assuming you have your guessed character as an int variable called "guess", and it has value 1-26 corresponding A-Z:
Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');
...
int guess = ...
char guessChar = (char)guess + 'a';
if (guessChar == targetLetter) {
System.out.println("Correct!");
} else {
System.out.println("Guess again!")
}
You can implement it in this approach :
1- Create a String alphabet with the characters that you want.
2- declare the size of alphabet as n variable which will control the random generator range.
3- alphabet.charAt(random.nextInt(n)) is a random char from the alphabet.
program code will be :
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int n = alphabet.length();
Random r = new Random();
System.out.println(alphabet.charAt(r.nextInt(n)));
hope will help solve your problem.
public class Picnic1 {
// RULE 0: This code is provided as a working example.
// This rule tests for whether a word starts with the letter 'b' (allowed to the picnic).
public static boolean rule0(char[] array) {
if (array[0] == 'b') {
return true;
}
else {
return false;
}
// itemMessage:
// Return message about whether a particular item is allowed to the picnic.
public static String item ( double[] a){
// This code works, providing output like these examples:
// "banana: true"
// "collie: false"
// It needs to be replaced with a more suitable output.
// Instead it should return, for example:
// "Yes, you can bring a banana to the picnic."
// "No, you cannot bring a collie to the picnic."
if (a[0] == 'b') {
System.out.println("Yes, you can bring a" + 'a' + "to the picnic");
}
else if (a[0] != 'b') {
System.out.print("No, you can not bring a " + 'a' + "to the picnic");
}
}
}
}

Loop issue with use of if statement

I have this hangman program but have an issue with asking the user if they want to play again, it always just ends the program. How can i fix this issue. Thanks for future reply's.
package hangman. I hope editing is okay with this
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Hangman {
static Scanner keyboard = new Scanner(System.in);
static int size, size2;
static boolean play = false;
static String word;
static String[] ARRAY = new String[0];
static String ANSI_RESET = "\u001B[0m";
static String ANSI_BLUE = "\u001B[34m";
static String ANSI_GREEN = "\u001B[32m";
static String ANSI_RED = "\u001B[31m";
static String ANSI_LIGHTBLUE = "\u001B[36m";
//^declarations for variables and colors for display^
public static void main(String[] args) {
randomWordPicking();
//^calls method^
}
public static void setUpGame() {
System.err.printf("Welcome to hangman.\n");
try {
Scanner scFile = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
String line;
while (scFile.hasNext()) {
line = scFile.nextLine();
Scanner scLine = new Scanner(line);
size++;
}
ARRAY = new String[size];
Scanner scFile1 = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
while (scFile1.hasNext()) {
String getWord;
line = scFile1.nextLine();
Scanner scLine = new Scanner(line);
word = scLine.next();
ARRAY[size2] = word;
size2++;
//calls method for picking word^
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
public static void randomWordPicking() {
setUpGame();
int LEFT = 6;
do {
int random = (int) (Math.random() * ARRAY.length);
//^genertates a random number^
String randomWord = ARRAY[random];
String word = randomWord;
//^chosses a random word and asgins it to a variable^
char[] ranWord = randomWord.toCharArray();
char[] dash = word.toCharArray();
//^Creates a char array for the random word chosen and for the dashs which are displayed^
for (int i = 0; i < dash.length; i++) {
dash[i] = '-';
System.out.print(dash[i]);
//^displays dashs to the user^
}
for (int A = 1; A <= dash.length;) {
System.out.print(ANSI_BLUE + "\nGuess a Letter: " + ANSI_RESET);
String userletters = keyboard.next();
//^gets user input^
if (!userletters.equalsIgnoreCase(randomWord)) {
//^allows program to enter loop if user has entered a letter^
for (int i = 0; i < userletters.length(); i++) {
char userLetter = userletters.charAt(i);
String T = Character.toString(userLetter);
for (int B = 0; B < ranWord.length; B++) {
//^converts users input to a char and to a string^
if (userLetter == dash[B]) {
System.err.println("This " + userLetter + "' letter already exist");
B++;
//^tells user if the letter they entered already exists^
if (userLetter == dash[B - 1]) {
break;
}
} else if (userLetter == ranWord[B]) {
dash[B] = userLetter;
A--;
}
}
if (!(new String(ranWord).contains(T))) {
LEFT--;
System.out.println("You did not guess a correct letter, you have " + LEFT + " OF "
+ dash.length + " trys left to guess correctly");
}
//^shows how many trys the user has left to get the word right before game ends^
System.out.println(dash);
if (LEFT == 0) {
System.out.println("The word you had to guess was " + word);
break;
}
//^shows the user the word if they didnt guess correctly^
}
} else {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
if (LEFT == 0) {
break;
}
if ((new String(word)).equals(new String(dash))) {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
}
//^if user enters the word it will check and then display that they got the word correct^
System.out.println("Play agian? (y/n)");
String name = keyboard.next();
//^asks user if they want to play again^
if (name.equalsIgnoreCase("n")) {
play = true;
return;
}
//^stops program if user enters n to stop game^
} while (play = false);
}
}
If you want to compare two variables, do not use = operator, which means assignment. Use == instead. Additionally, in your case it should be !=:
while (play != false)
You should use
while (!play)
instead of
while (play = false)

Java word shuffle game [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm having tons of issues with this program. I can't get my string comparisons to work and I have several infinite loops that I'm not sure how to fix. I would appreciate a fresh set of eyes to show me what I'm missing, I've been staring at this for 3 days and I keep skipping over my errors. The program needs to pick a random word from the given text file, scramble up that word, then have the user guess what the original word was. Hints should display what letter is at a given random position within the word.
import java.util.Scanner;
import java.util.Random;
import java.io.*;
import java.util.*;
public class Proj4 {
public static void main (String[] args) throws IOException{
int wordScore = 10;
int score = 0;
boolean game = true;
int i = 0;
Scanner in = new Scanner(System.in);
char responseLetter = 'n';
boolean allTrue = false;
boolean scramble = true;
StringBuilder sb = new StringBuilder ();
int counter = 0;
int position = 0;
System.out.println("Enter in a file containing words (Ex: words.txt) : ");
String filename = in.nextLine();
Scanner inFile = new Scanner(new File(filename));
String size = inFile.nextLine();
System.out.println(size);
int arrayLength = Integer.parseInt(size);
String[] wordList = new String[arrayLength];
Random rndm = new Random();
while (inFile.hasNext()) {
// this section puts the contents of the text file into the array
wordList[i] = inFile.nextLine();
i++;
}
while (game == true) {
// System.out.println("Current puzzle: " + scrambledWord);
// System.out.println("Current points for word " + wordScore);
// System.out.println("Enter (g)uess, (n)ew word, (h)int, or (q)uit: ");
// responseLetter = in.next().charAt(0);
if (responseLetter == 'n') {
// goes back to the beginning but does not change word. I cant move the picker down becauase it throws off g
String pickedWord = wordList[rndm.nextInt(arrayLength )];
boolean [] used = new boolean[pickedWord.length()] ; // the random word gets picked here
String [] letters = pickedWord.split("");
while (allTrue == false) {
int randomLetter = rndm.nextInt(pickedWord.length());
if (used[randomLetter] != true) {
sb.append(letters[randomLetter].charAt(0)); // does this line work?
used[randomLetter] = true;
} else if (used[randomLetter]== true) {
scramble = true;
counter++;
}
if (counter > (2 * pickedWord.length())) {
allTrue = true;
}
}
String scrambledWord = sb.toString();
if (scrambledWord.equals(pickedWord)) {
System.out.println("The words match");
allTrue = false;
}
System.out.println("Current puzzle: " + scrambledWord);
System.out.println("Current points for word " + wordScore);
System.out.println("Enter (g)uess, (n)ew word, (h)int, or (q)uit: ");
responseLetter = in.next().charAt(0);
} else if (responseLetter == 'g') {
// automatically says guess is wrong. something wrong with equals()?
System.out.println("Enter your guess: ");
in.nextLine();
String guess = in.nextLine();
if (guess.equals(pickedWord)) {
System.out.println("You guessed it!");
score += wordScore;
game = true;
} else if (!guess.equals(pickedWord)) {
System.out.println("Oops! Try again.");
wordScore--;
System.out.println("Current points for word " + wordScore);
System.out.println("Enter (g)uess, (n)ew word, (h)int, or (q)uit: ");
responseLetter = in.next().charAt(0);
}
} else if (responseLetter == 'h') {
//THIS BLOCK WORKS. DONT EVEN LOOK AT IT
Random r = new Random();
int hint = r.nextInt(pickedWord.length());
System.out.println(hint);
char letterAtSpot = pickedWord.charAt(hint);
System.out.println("The letter at spot " + hint + " is " + letterAtSpot);
wordScore--;
} else if (responseLetter == 'q') {
game = false;
} else {
System.out.println("Invalid Choice - 'g', 'n', 'h', 'q' only.");
responseLetter = 'n';
}
}
System.out.println("Goodbye!");
System.out.println("Total score: " + score);
}
}
Right out of the gate, I had a compilation error because pickedWord is being referenced outisde of the if statement in which it was declared. So, by the time it got to if (guess.equals(pickedWord)), the compiler doesn't know what pickedWord is.
The first thing that popped out at me was the if/else ladder.
String scrambledWord = sb.toString();
if (scrambledWord.equals(pickedWord)) {
System.out.println("The words match");
allTrue = false;
}
System.out.println("Current puzzle: " + scrambledWord);
System.out.println("Current points for word " + wordScore);
System.out.println("Enter (g)uess, (n)ew word, (h)int, or (q)uit: ");
responseLetter = in.next().charAt(0);
}
Notice how you close your if statement before getting a response for responseLetter. This means, your loop condition: "while game == true" isn't properly being evaluated.

Count and Display UpperCase, LowerCase and Numbers

I'm tasked to do this one in my java class. And I don't know what to do.
Use Scanner or JOptionPane, it will ask the user to input a word. Then it will validate if the word is composed of capital letters, numbers, Whitespaces, then it will count the total number of characters.
Enter a word: _____
Entered Word: "Display word here"
Characters found:
Uppercase:
total number of uppercase letters:
Lowercase:
total number of lowercase letters:
Numbers:
total number of Numbers:
Number of Whitespaces:
Total number of characters found:
Should probably be something covered in a basic course... Edited to include a counter for numbers and relevant code for both a Scanner and a JOptionPane.
public static void main(String[] args) {
String input = (String) JOptionPane.showInputDialog(null, "Input a sentence.", "Dialogue", JOptionPane.PLAIN_MESSAGE, null, null, null);
// System.out.println("Input a word.");
// #SuppressWarnings("resource") Scanner scan = new Scanner(System.in);
// String input = scan.nextLine();
System.out.println("Input word was: " + input);
int length = input.length();
char[] charAnalysis = input.toCharArray();
int whitespace = 0;
int lowercase = 0;
int uppercase = 0;
int numberCount = 0;
for (char element : charAnalysis) {
if (Character.isWhitespace(element)) {
whitespace++;
} else if (Character.isUpperCase(element)) {
uppercase++;
} else if (Character.isLowerCase(element)) {
lowercase++;
} else if (Character.isDigit(element)) {
numberCount++;
}
}
System.out.println("Length: " + length);
System.out.println("Uppercase letters: " + uppercase);
System.out.println("Lowercase letters: " + lowercase);
System.out.println("Digit count: " + numberCount);
System.out.println("Whitespaces: " + whitespace);
}
String word = JOptionPane.showInputDialog(frame, "enter word");
for(int i =0;i<word.length();i++)
{
if (Character.isUpperCase(word.charAt(i))){ upperCase++; }
else if (Character.isLowerCase(word.charAt(i))){ lowerCase++; }
else if (Character.isDigit(word.charAt(i))) { numberCount++;}
else if(charAt(i)=' ') {spaceCount++}
}
//to display word count
System.out.println(word.length);
//to display uppercase count
System.out.println(upperCase);
//to disply digits count
System.out.println(numberCount);
//to display space count
System.out.println(spaceCount);
Try this and do read class Character to understand clearly.
import java.util.*;
import java.lang.*;
import java.io.*;
public class HelloWorld{
public static void main(String[] args) {
System.out.println("Input a word.");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
System.out.println("Entered Word: " + input);
int length = input.length();
char[] chars = input.toCharArray();
int whitespaceLength = 0;
String upercase = "";
String lowercase = "";
String numbers = "";
for (char element : chars) {
if (Character.isWhitespace(element)) {
whitespaceLength++;
} else if (Character.isUpperCase(element)) {
upercase+=element;
} else if (Character.isLowerCase(element)) {
lowercase+=element;
}else if (Character.isDigit(element)) {
numbers+=element;
}
}
System.out.println("Uppercase: " + upercase );
System.out.println("total number of uppercase letters: " + upercase.length());
System.out.println("Lowercase: " + lowercase);
System.out.println("total number of lowercase letters: " + lowercase.length());
System.out.println("Numbers: " + numbers);
System.out.println("total number of Numbers: " + numbers.length());
System.out.println("Number of Whitespaces: " + whitespaceLength);
System.out.println("Total number of characters found: " + input.length());
}
}
public class Count {
public static void main(String[] args) {
int upperCase = 0;
int lowerCase = 0;
int spaceCount = 0;
int numberCount = 0;
Scanner sc = new Scanner(System.in);
System.out.println("enter a string ");
String word = sc.nextLine();
sc.close();
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
upperCase++;
} else if (Character.isLowerCase(word.charAt(i))) {
lowerCase++;
} else if (Character.isDigit(word.charAt(i))) {
numberCount++;
} else if (word.charAt(i) == ' ') {
spaceCount++;
}
}
System.out.println("total number of uppercase letters :"+upperCase);
System.out.println("total number of lowerCase letters :"+lowerCase);
System.out.println("total number of Numbers :"+numberCount);
System.out.println("Total number of whitSpaces :"+spaceCount);
}
}

Categories