writes out the number of uppercase characters in the user's input - java

cant get it to print out number uppercases in the program only starting out. really struggling with the concept of how strings work.
public static void main(String[] args)
{
//inputs
String Fullname;
int index;
// count starts
int count = 0;
// process
System.out.print(" Please Enter your Name ");
Fullname = EasyIn.getString();
for (int i = 0; i < String.length(); i++)
{
if(Character.isUpperCase(Fullname.charAt(index)));
count++;
}
System.out.print(" Number of Characters entered: " );
}
}

You can't do String.length; you have to calculate the length of Fullname
change with Fullname.length()

Related

Problem with how to print "ALL" the longest string which have SAME longest length() that stored in array(JAVA)

Write a program where the user types in a number of Strings which are stored in an array of Strings and then the program prints out all the longest Strings entered by the user.
HAVE A PROBLEM HOW TO PRINT ALL SAME LONGEST LENGTH() According to this sentence that required "the program prints out all the longest Strings"
PS. My code can only print out ONE longest length string NOT ALL longest String. How to fixed it.
public static void method4(){
Scanner console = new Scanner(System.in);
String[] list = new String[5];
int maxLength = 0;
String longestString = null;
String longestString1 = null;
for (int i = 0; i < list.length; i++) {
System.out.println("Enter a string 5 times: ");
list[i] = console.next();
if (list[i].length() > maxLength){
maxLength = list[i].length();
longestString = list[i];
}
}
System.out.println("Longest string: "+longestString+ "\n\t\t"+longestString1);
}
The problem with your code is: inside the loop that you are getting the user's input, you print the "longest string" at that moment.
This means that the 1st string that the user enters will be a "longest string" and will be printed because its length is compared to 0 and of course it is longer.
You must separate the input of the strings and the output (printing of the longest strings) in 2 separate loops. The 1st loop gets the strings and by comparing calculates the length of the longest string and the 2nd iterates through all the string and prints it only if its length is equal to the maximum length that was calculated in the 1st loop:
String[] list = new String[5];
int maxLength = 0;
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < list.length; i++) {
System.out.println("(" + (i + 1) + ") Enter a string: ");
list[i] = scanner.nextLine();
if (list[i].length() > maxLength){
maxLength = list[i].length();
}
}
scanner.close();
int counter = 0;
for (String s : list) {
if (s.length() == maxLength){
counter++;
System.out.println("(" + counter + ") Longest string: " + s + "\n");
}
}
You have to do it in two pass. First loop finds the max length of string. Then second loop can iterate and print only strings that have max length,
public static void method4(Scanner console){
String[] list = new String[5];
int maxLength = 0;
System.out.println("Enter a string 5 times: ");
for (int i = 0; i < list.length; i++) {
list[i] = console.next();
if (list[i].length() > maxLength){
maxLength = list[i].length();
}
}
for (int i = 0; i < list.length; i++) {
if (list[i].length() == maxLength) {
System.out.println("Longest string: "+list[i]);
}
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
method4(sc);
sc.close();
}
There are other approaches too where you can store the longest strings in a set as you encounter them and reset the set the moment you find a new longer string and finally print all the strings in the Set.

Take a quote, and show how many characters, words, and average of each word

I am kinda new to Java, please do not tell me to use methods, etc. because I do not know how to do them. But I do know some charAt things, so can anyone help me find the amount of words, and avg of each word, i did the first part. Here is my code.
import java.util.Scanner;
public class FavouriteQuote {
public static void main(String[] args) {
// TODO Auto-generated method stub
String sQuote;
int counter = 0;
Scanner input = new Scanner (System.in);
System.out.print("Enter one of your favourite quotes: ");
sQuote = input.nextLine();
input.close();
for (int i = 0; i < sQuote.length(); i ++) {
counter ++;
}
System.out.println(counter);
}
}
But what average do you need? average word length in quote?
then your code may look like:
...
input.close();
System.out.println("Characters in quote:" + sQuote.length());
String[] words = sQuote.split("\\s");
// or
// String[] words = sQuote.split(" ");
System.out.println("words in quote:" + words.length);
int totalWordsLength =0;
for (String word: words)
{
totalWordsLength = totalWordsLength + word.length();
}
//or with loop counter
// for (int i=0; i < words.length; i++)
// {
// totalWordsLength += words[i].length();
// }
System.out.println("average word length in quote:" + (totalWordsLength/ words.length));
Keep in mind: here average is int so it will be only integer portion of divide result. i.e. 11/3 = 3
BTW (aside of question) - You do not need your for loop. It does not make any sense.
counter = sQuote.length() does the same.

String index out of range inside of a method: Java

I was writing some code for my class and I ran into this error, String index out of range. I checked to see if it might be the string = null but that's not the case. I'm guessing it has to do with my if statement in the method but I couldn't find how to fix it anywhere. Any help is appreciated, thank you very much!
import java.util.*;
public class Occurences {
public static void main(String[] args) {
int check = 0;
char characterInput = ' ';
do {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a string: ");
String input = scan.next();
System.out.println("Enter a character to find it's occurence in the string: ");
characterInput = scan.next().charAt(0);
int i = count(input, characterInput);
System.out.println(characterInput + ", is in " + input + ", " + i + " times.");
System.out.println("To continue enter any number, to exit enter -1: ");
check = scan.nextInt();
} while (check != -1);
}
public static int count(String input, char characterInput) {
int cnt = 0;
int j = input.length();
while (j > 0) {
if (input.charAt(j) == characterInput) {
cnt += 1;
}
j--;
}
return cnt;
}
}
The error happens on line 21: int j = input.length(), as others mentioned in the comments, java, and most programming languages, index strings and array types by zero-indexing - starting from zero. So you have to either 1) start counting at 0 or 2) stop counting at one-less-than the length of the string(array), which is why line 21 needs to be either:
int j = input.length()-1;
or as you solved it using method 1:
setting int j=0;

Hangman code stuck on three different problems

I'm trying to make a hangman game. On each turn, the user guesses a letter. If they guessed correctly, they can guess again. Otherwise, their remaining available guesses drops by one, and the guessed letter is put into an array.
When the user hits zero remaining guesses, the program is supposed to ask if they want to play again. If they answer yes, it is supposed to restart the game, and if they answer no, the program ends.
The problem I'm having is with the array that holds the guesses, and with restarting the game.
Also, the program will error every once in a while when starting. The error is
Exception in thread "main" java.lang.NullPointerException at Hangman1.main(Hangman1.java:27)
The error when trying to restart the game is
Exception in thread "main" java.lang.NullPointerException at Hangman1.main(Hangman1.java:101)
searchArray is the method that is supposed to take the position of the char array and copy that in asterisk array and return asterisk array, that doesn't seem to work. Running debug it seems the problem that causes the program to crash is that word will sometimes end up null, but only sometimes and I don't really know why
import java.util.*;
import java.io.*;
public class Hangman1 {
static Scanner keyboard = new Scanner(System.in);
public static final int MAXSIZE = 15000;
public static final int NUM_GUESS = 8;
public static final int WORD_LENGTH = 20;
public static void main(String[] args) {
int random = pickrandom(MAXSIZE);
try {
// Set up connection to the input file
Scanner input = new Scanner(new FileReader("dictionary.txt"));
instructions();
keyboard.nextLine();
clearScreen();
String word = randomWord(input, random);
System.out.println(word);
String[] charArray = word.split("");
System.out.print("\n");
String[] asterisk = asteriskLine(word);
String decision = "Y";
//decision = keyboard.nextLine().toUpperCase();
System.out.println("Word to guess :");
for (int count = 0; count < word.length(); count++) {
System.out.print(asterisk[count]);
}
System.out.print("\n");
int tries = NUM_GUESS;
System.out.println("Enter a letter to guess or 9 to quit");
String guess = keyboard.next();
String[] wrongGuesses = new String [NUM_GUESS];
int guessMade = 0;
do {
//System.out.println(tries);
while (!(guess.equals("9")) && !(guess.equals(word)) && (tries > 0))
{
String letter = guess.substring(0,1);
if (word.indexOf(letter) < 0) {
clearScreen();
tries--;
wrongGuesses = wrongGuesses(guessMade, wrongGuesses, letter);
printArray(asterisk, charArray, word, tries, wrongGuesses, guessMade);
guessMade++;
guess = keyboard.next();
}
else {
clearScreen();
asterisk = searchArray(charArray, asterisk, guessMade, letter, word);
printArray(asterisk, charArray, word, tries, wrongGuesses, guessMade);
guess = keyboard.next();
}
if (charArray == asterisk) {
System.out.println("You won!");
}
if (tries == 0) {
System.out.println("You have no more guesses left");
}
}
if (guess.equals("9")) {
System.out.println("Thanks for playing");
}
System.out.println("Play again? Y/N");
decision = keyboard.next().toUpperCase();
if (decision.equals("Y")) {
random = pickrandom(MAXSIZE);
word = randomWord(input, random);
charArray = word.split("");
System.out.print("\n");
asterisk = asteriskLine(word);
guess = keyboard.next();
}
} while (decision.equals("Y"));
//System.out.println("Play again? Y/N");
//decision = keyboard.nextLine().toUpperCase();
}
catch (FileNotFoundException e) {
System.out.println("There was an error opening one of the files.");
}
}
//Clears screen after introduction
private static void clearScreen() {
for (int blanks = 0; blanks < 80; blanks++) {
System.out.println();
}
}
// This method returns a randomly selected integer
// between 0 and count-1
public static int pickrandom(int count) {
Random generator = new Random();
return generator.nextInt(count);
}
// Places asterisks in place of the letters in the word
// Parameter is the string word. it holds mystery word
public static String[] asteriskLine(String word) {
int i;
String[] asteriskArray = new String [word.length()];
for (i = 0; i < word.length(); i++) {
asteriskArray[i] = "* ";
}
return asteriskArray;
}
public static void instructions() {
System.out.println(" H A N G M A N. "
+ "\n This is a word guessing game. "
+ "\n A word will be selected at random and kept hidden. You will try to figure out the secret word by"
+ "\n guessing letters which you think are in the word. "
+ "\n You will guess one letter at a time. "
+ "\n If the letter you guess is correct, the position(s) of the letter in the secret word will be shown. "
+ "\n You will be allowed "
+ NUM_GUESS
+ " wrong guesses If you guess incorrectly "
+ NUM_GUESS
+ " times, you lose the game. "
+ "\n If you guess all of the letters in the word, you win."
+ "\n\n Press enter to continue ");
}
public static String randomWord(Scanner input, int random) {
String[] dictionaryWords = new String [MAXSIZE];
int usedsize = 0;
while (usedsize < MAXSIZE && input.hasNextLine()) {
dictionaryWords[usedsize] = input.nextLine();
usedsize++;
}
String word = dictionaryWords[random];
return word;
}
//Replaces correct guess in blanks
public static String correctWord(String guess, String word, String asterisk, char letter) {
return null;
}
public static void printArray(String[] asterisk, String[] charArray, String word, int tries, String[] wrongGuesses, int guessMade) {
System.out.println("Word to guess");
for (int count = 0; count < word.length(); count++) {
System.out.print(asterisk[count]);
}
System.out.println("\nGuesses remaining: " + tries);
System.out.print("Incorrect letters tried: ");
for (int count = 0; count <= guessMade; count++) {
System.out.print(wrongGuesses[count] + " ");
}
System.out.println("\nEnter a letter to guess or 9 to quit");
}
public static String[] wrongGuesses(int guessMade, String [] wrongGuesses, String letter) {
wrongGuesses[guessMade] = letter;
return wrongGuesses;
}
public static String[] searchArray(String[] charArray, String[] asterisk, int guessMade, String letter, String word) {
int[] a = new int[word.length()];
for (int count = 0; count < word.length(); count++) {
if (letter == charArray[count]) {
asterisk[count] = charArray[count];
}
}
return asterisk;
}
}
One thing that you need to do is to read all of your words in once and only once, and store them all into an ArrayList. Your current code tries to re-use a Scanner object that is already spent, and that will fail. Instead get your random word from the ArrayList<String>.
Running debug it seems the problem that causes the program to crash is
that word will sometimes end up null, but only sometimes and I don't
really know why
public static String randomWord(Scanner input, int random) {
String[] dictionaryWords = new String [MAXSIZE];
int usedsize = 0;
while (usedsize < MAXSIZE && input.hasNextLine()) {
dictionaryWords[usedsize] = input.nextLine();
usedsize++;
}
String word = dictionaryWords[random];
return word;
}
Sometimes random will be bigger than usedsize.
So you need to move this line from outside the loop
int random = pickrandom(MAXSIZE);
into this function, and have the maximum be usedsize (or usedsize-1).
You can protect yourself against this error, and work out whether you should be using usedsize or usedsize-1, by writing a unit test. Look into a Junit tutorial.
In your junit test, call randomword and pass it a very high value for random. Then
assert(word!= null)
Word is null when random is longer than the length of your dictionary.

Input sentence and print out number of words that are above min length requirement in java

My goal is to create a code that accepts a string, and the minimum number of characters allowed for each word. The output will be an int that tells the users the number of words in their sentence that was above or equal to the min they entered.
Now, my approach to this was to break the sentence up into individual word in the main method, then send each of those words into another method that will count the number of characters.
I am having difficulties in my main method, specifically splitting the sentence into individual words. I want to achieve this without using an array, only loops, substring and indexOf, etc. I commented the section of code that I am having issues with. I tested the rest of my code using a string with only one word, and my letterCounter method seems to be working fine. I know the answer is probably simple, but I am still having trouble figuring it out.
Any help would be wonderful! Thank you!
Here is my code:
public class Counter
{
public static void main(String [] args)
{
int finalcount = 0;
System.out.print("Enter your string: ");
String userSentence = IO.readString();
System.out.print("Enter the minimum word length: ");
int min = IO.readInt();
//Error checking for a min less than 1
while(min < 0)
{
IO.reportBadInput();
System.out.print("Enter the minimum word length: ");
min = IO.readInt();
}
int length = userSentence.length(); // this will get the length of the string
for(int i = 0; i < length; i ++)
{
if (userSentence.charAt(i) == ' ')
{
/* I dont know what to put here to split the words!
once I split the userSentence and store the split word into
a variable called word, i would continue with this code: */
if((letterCounter(word)) >= min)
finalcount++;
else
finalcount = finalcount;
}
}
IO.outputIntAnswer(finalcount);
}
//this method counts the number of letters in each word
public static int letterCounter (String n)
int length = n.length();
int lettercount= 0;
for(int i = 0; i < length; i ++)
{
boolean isLetter = Character.isLetter(n.charAt(i));
if (isLetter)
{
if ((n.length()) >= length)
{
lettercount++;
}
}
}
return lettercount;
}
}
Have a a look at String.split()
You could use string.split() like this to accomplish this:
String [] splittedString = inputString.split(" ");
for(int i = 0;i< splittedString.length; i++){
String currentWord = splittedString[i];
if(currentWord.length() >= min){
finalcount++;
}
}

Categories