error in my Java - java

So currently im trying to do a java project and have seen a few answers on this on other websites but im having trouble understandign them. i need to do this:
"Write a program that prompts the user to input a string of words, then counts and displays the number of times each letter in the alphabet appears in the string. It is not necessary to distinguish between uppercase and lowercase letters. Your output should be formatted as follows:
Letter A count = xx
Letter B count = xx
....
Letter Z count = xx"
and this is what I have so far:
import java.util.Scanner;
public class Unit9 {
public static void main(String [] args )
{
int array[] = new int[26];
for (int i = 0; i < array.length; i++)
{
array[i] = 0;
}
Scanner Keyboard = new Scanner(System.in);
String userInput;
System.out.println("Please enter a string.");
userInput = Keyboard.next().toLowerCase();
for (int i = 0; i < userInput.length(); i++)
{
char ch = userInput.charAt(i);
if (ch >= 'a' && ch <= 'z') {
array[ch - 'a'] ++;
}
}
for (char ch='a'; ch<='z'; ++ch) {
System.out.print(ch + array[ch-'a']);
}
}
}
but when i enter "hello" (without the quotes) i end up getting this:
Please enter a string.
hello
979899100102102103105105106107110109110112112113114115116117118119120121122
what is happening? what am i doing wrong?
EDIT: actually, i just realized something else... it stops detecting when there is a space in the user input meaning that it only detects the first word. how would I add detection for a space as well?

The reason why it only detected the first word is because you entered:
userInput = Keyboard.next().toLowerCase();
instead of
userInput = Keyboard.nextLine().toLowerCase();
nextLine() reads the whole line entered while next() only reads the first word.

You are using the + operator between a char and an int on this line:
System.out.print(ch + array[ch-'a']);
This gives you a number as a result, which is then inputted into System.out.print taking int as input, therefor printing the number itself. You also have no spacing (or use println), so it appears to be one long line of numbers.
Try this for your last loop:
for (char ch='a'; ch<='z'; ++ch) {
System.out.print(ch + ": "+ array[ch-'a']+" ");
}
It will now no longer be seen as addition, but rather concatination and show as a string of "letter: amount", one after another for the entire alphabet.

Related

How do I print a letter based on the index of the string?

I want to print a letter instead of the index position using the indexOf(); method.
The requirement is that: Inputs a second string from the user. Outputs the character after the first instance of the string in the phrase. If the string is not in the phrase, outputs a statement to that effect. For example, the input is 3, upside down, d. The output should be "e", I got part of it working where it inputs an integer rather than a string of that particular position. How would I output a string?
else if (option == 3){
int first = 0;
String letter = keyboard.next();
first = phrase.indexOf(letter,1);
if (first == -1){
System.out.print("'"+letter+"' is not in '"+phrase+"'");
}
else {
System.out.print(first + 1);
}
}
String.charAt(index)
You can access a single character, or a letter, by caling método charAt() from String class
Example
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = keyboard.nextLine();
char firstLetter = phrase.charAt(0);
System.out.println("First Letter : " + firstLetter);
}
So, running this code, assuming the input is StackOverFlow, the output will be S
In your code I think doing the follow will work:
Your Code
String letter = keyboard.next();
first = letter.charAt(0);
That might help!
Based on those comments
So, what you want is print the first letter based on a letter the user
has input? For example, for the word Keyboard, and user inputs letter
'a' the first letter might be 'R'. Is that it? – Guerino Rodella
Yes, I have to combine both the indexOf(): method and the charAt():
method – Hussain123
The idea is get next letter based on user input letter.
I'm not sure I wunderstood it, but this is my shot
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String phrase = "keyboard";
String userInput = keyboard.nextLine();
boolean notContainsInputValue = !phrase.contains(userInput);
if (notContainsInputValue) {
System.out.println("The input value doesn't exists");
return;
}
char firstLetter = userInput.charAt(0);
int desiredIndex = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == firstLetter) {
desiredIndex = i;
break;
}
}
System.out.println("The index for your input letter is: " + desiredIndex);
System.out.println("Next letter based on input value is: " + phrase.charAt(desiredIndex + 1));
}
The Output
The index for your input letter is: 5
Next letter based on input value is: r
Hope that helps you.

replace dashes with guessed letter in java

really beginner javascript user here, creating a hangman game. i am having the world of difficulty in trying to show a users correct guess.
from my understanding i have only masked the secret word with dashes so therefor am trying to make it become unmasked when a correct letter is guessed.
i imagine i need to use charAt somewhere, somehow but to be honest i just cant figure it out.
My code is still very basic and i havent done much else as there isnt much point writing out the rest of the game if you cant see the guess but here is the code i have so far... please remember this is still a very unfinished project.
package hangmangame;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
/**
*
* #author Matt
*/
public class HangmanGame {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
char letter = 0; //declares and initailise letter
String marks = ""; //declares and initailise string for dashes
String [] words = { "gluttony", "lust", "greed", "pride", "despair", "wrath", "vainglory", "rhythm", "delicious", "better", "jacuzzi" , "ironman", "captainamerica", "thor", "hulk", "spiderman", "antman", "batman"}; //declares and initailise array of words to guess
String word = words[(int) (Math.random() * words.length)]; //chooses random word from the word array
for (int i=1;i<=word.length(); i++) // for method for displaying the correct word as dashes
{
marks += "-"; //dashes to represent the correct word.
}
System.out.println("lets play hangman, your word is " + marks + "\n" + "enter a letter to guess the word");
Scanner input = new Scanner(System.in);
letter = input.next(".").charAt(0); //assign inputted letter to letter variable
if ((word).contains(""+letter)) //if statement to excute if guessed letter is in word
// i imagine this is where i put some sort of code to show that guessed letter?
System.out.println("You guessed a letter!" + marks); //display for correct letter
Here is some code to get you started. It's important to grab the entire line from the user instead of using next()... Unless you are an experienced coder and understand the way in which the next() iterates over the input I'd highly suggest using nextLine() as it's much easier to use.
char letter = 0; //declares and initailise letter
String [] words = { "gluttony", "lust", "greed", "pride", "despair", "wrath", "vainglory", "rhythm", "delicious", "better", "jacuzzi" , "ironman", "captainamerica", "thor", "hulk", "spiderman", "antman", "batman"}; //declares and initailise array of words to guess
String word = words[(int) (Math.random() * words.length)]; //chooses random word from the word array
String [] marks = new String[word.length()];
for (int i=0;i<word.length(); i++) // for method for displaying the correct word as dashes
{
marks[i] = "-"; //dashes to represent the correct word.
}
HashSet<Character> lettersGuessed = new HashSet<>(); //keep track of letters guessed
Scanner input = new Scanner(System.in);
String userInput = "";
String currentWord = "";
while(true)
{
System.out.print("Word is - ");
currentWord = "";
for(int i = 0; i < marks.length; i++)
{
System.out.print(marks[i]);
}
System.out.print("\nGuess a letter - ");
userInput = input.nextLine(); //always grab lines
if(userInput.length() != 1)
{
System.out.println("Invalid guess - " + userInput);
}
else if(lettersGuessed.contains(userInput.charAt(0)))
{
System.out.println("You already guess that character - " + userInput);
}
else if(word.contains(userInput))
{
lettersGuessed.add(userInput.charAt(0));
currentWord = "";
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == userInput.charAt(0))
{
marks[i] = "" + userInput.charAt(0);
}
currentWord += marks[i];
}
}
if(currentWord.equals(word))
break;
}
System.out.println("You guessed it! The word was " + word + "!");
Output
Word is - ----
Guess a letter - l
Word is - --l-
Guess a letter - h
Word is - h-l-
Guess a letter - l
You already guess that character - l
Word is - h-l-
Guess a letter - u
Word is - hul-
Guess a letter - tg
Invalid guess - tg
Word is - hul-
Guess a letter - k
You guessed it! The word was hulk!
the String class contains an indexOf(String c) method which returns the index of the first occurrence of a substring. For example, if word was delicious then word.indexOf("i") would return 3, the first index of the substring "i".
But what about all other occurences of the substring "i"? Well, the indexOf method is handily overwritten to help with that. There is another version of it, indexOf(String ch, int fromIndex) that takes in a starting index. Continuing our earlier example, if you asked for word.indexOf("i", 4) this time you would get back 5, the first index of the substring "i" in the string "delicious" if we are discounting every index before the fourth one.
Think of it this way, indexOf is kind of the opposite of charAt. charAt takes in an index and gives you a character, indexOf takes in a character or string and gives you its first index.
I think this would all be a lot easier if you stored the word and the marks as character arrays like this:
char letter = 0; //declares and initailise letter
String [] words = { "gluttony", "lust", "greed", "pride", "despair", "wrath", "vainglory", "rhythm", "delicious", "better", "jacuzzi" , "ironman", "captainamerica", "thor", "hulk", "spiderman", "antman", "batman"}; //declares and initailise array of words to guess
String word = words[(int) (Math.random() * words.length)]; //chooses random word from the word array
char[] chosenWord = new char[word.length()];
char[] marks = new char[word.length];
for (int i=0;i< word.length(); i++) // for method for displaying the correct word as dashes
{
chosenWord[i] = word.charAt(i);
marks[i] = '-';
}
System.out.println("lets play hangman, your word is " + new String(marks) + "\n" + "enter a letter to guess the word");
Scanner input = new Scanner(System.in);
letter = input.next(".").charAt(0); //assign inputted letter to letter variable
if ((word).contains(""+letter)){ //if statement to excute if guessed letter is in word
for(int i =0; i < chosenWord.length; i++){
if(chosenWord[i] == letter){
marks[i] = chosenWord[i]
}
}
// i imagine this is where i put some sort of code to show that guessed letter?
System.out.println("You guessed a letter!" + new String(marks));
}
I didn't syntax check this, but you should get the idea of what I'm working at.
This is what i made.
I think its much better to use arrays here.
public static void main(String[] args) {
String[] words = {"gluttony", "lust", "greed", "pride", "despair", "wrath", "vainglory", "rhythm", "delicious", "better", "jacuzzi", "ironman", "captainamerica", "thor", "hulk", "spiderman", "antman", "batman"}; //declares and initailise array of words to guess
String word[] = (words[(int) (Math.random() * words.length)]).split(""); //chooses random word from the word array and creates a array of letters
String[] marks = new String[word.length];
Arrays.fill(marks,"-"); // creates and fills an array with dashes
Scanner in = new Scanner(System.in);
String letter = "";
int counter = 0;
while(Arrays.toString(marks).contains("-")) {
counter++;
System.out.println("This is your word!: " + String.join("", marks));
System.out.print("Guess a letter ");
letter = String.valueOf(in.next(".").charAt(0));
for (int i = 0; i < word.length; i++) {
if(word[i].equals(letter)){
marks[i] = word[i];
}
}
}
System.out.println("Congratulations your word is " + String.join("",marks) + "You did it in " + counter + "trials");
}
}

Using java, how do count the occurrences of a character in a string, and then format an output with text listing the locations using loops

I understand how to count the occurrences of specific characters in a string. What I am struggling is printing "The specific character is at location x, y, z". If I place the text within the loop that tests for location, the text is printed multiple times. I do not want that to happen.
There are other constraints as well. I must keep the program basic, and I am limited to using the charAt() and string.lenghth() functions. The program should only exit when the user enters "-1". When the user enters the string, the program should read through the characters, output the location of the specific characters, and then prompt the user to enter a new string. I am also struggling with allowing the user to enter a new string and running the loop again.
Here is the code I have so far
import java.util.Scanner;
public class GimmeAW {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the Line\nEntering -1 exits the program")
String aLine;
aLine = input.nextLine();
char one = aLine.charAt(0);
char two = aLine.charAt(1);
if (one == '-' && two == '1') {
System.out.println("System Exit");
System.exit(1);
}
for (int i = 0; i < aLine.length(); i++) {
if (aLine.charAt(i) == 'w' || aLine.charAt(i) == 't') {
int location = i;
System.out.print(" " + i);
}
}
}
To avoid printing the msg multiple times, just keep the msg outside of the counting loop and print it once for each character ...
char[] ch = {'w', 't'}; // characters to count
int l = aLine.length();
for(int i = 0; i < ch.length; i++) {
System.out.print("The character " + ch[i] + " is at locations ");
// searching
for(int j = 0; j < l; j++) {
if(aLine.charAt(j) == ch[i]) {
System.out.print(j + " ");
}
}
System.out.println();
}
And you can put all the code you want to repeat inside a do-while loop and run it until the user wants to.
String choice = "yes";
do {
// code
// want to repeat ??
choice = in.nextLine();
} while(choice.equals("yes"));

Write a program that will read a line of text, and will display all letters in the text along with the number of times the letter appears in the text

I have the basics, but I need to make it so that my program will work without printing the unused letters of the alphabet at the end, say my sentence is "dog" I would want the output to be: D-1
O-1
G-1, instead of A-0 B-0 D-1, and so on. Thanks for any help provided, it is greatly appreciated.
what I have so far is:
package as10;
import java.util.*;
public class as
{
private static void countLetters(String sentenceString)
{
int[] array = new int[26];
sentenceString = sentenceString.toUpperCase();
for (int i = 0; i < sentenceString.length(); ++i)
{
if (sentenceString.charAt(i) >= 'A' && sentenceString.charAt(i) <= 'Z')
{
++array[sentenceString.charAt(i) - 'A'];
}
}
for (int i = 0; i < 26; ++i)
{
System.out.println((char) ('A' + i) + " - " + array[i]);
}
}
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
String letterString;
while (true)
{
System.out.println("Enter a line of text: ");
letterString = kbd.nextLine();
System.out.println("Letter Frequencies: ");
countLetters(letterString);
break;
}
kbd.close();
}
}
so, basically, you want to opt out all chars if counter is 0.
In other words, you will need an if statement around print line and only perform system output if relevant array value is non-zero.
Above statement is in pure English. It is again your assignment to convert that sentence into java, as I refuse to do your homework on your behalf.
Does it sound fair ? :)

Can't figure out what is wrong with my code

This is the instructions i got from my teacher:
Write your code in the file WordCount.java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method:
public static int countWords(String original, int minLength){}
Your method should count the number of words in the sentence that meet or exceed minLength (in letters). For example, if the minimum length given is 4, your program should only count words that are at least 4 letters long.
Words will be separated by one or more spaces. Non-letter characters (spaces, punctuation, digits, etc.) may be present, but should not count towards the length of words.
Hint: write a method that counts the number of letters (and ignores punctuation) in a string that holds a single word without spaces. In your countWords method, break the input string up into words and send each one to your method.
This is my code:
public class WordCount {
public static void main(String[] args)
{
System.out.print("Enter string: ");
String input = IO.readString();
System.out.print("Enter minimum length for letter: ");
int length = IO.readInt();
IO.outputIntAnswer(countWords(input, length));
}
public static int countWords(String original, int minLegth)
{
int count = 0;
int letterCount = 0;
for(int i = 0; i < original.length(); i++)
{
char temp = original.charAt(i);
if(temp >= 'A' && temp <= 'Z' || temp >= 'a' && temp <= 'z')
{
letterCount++;
}
else if(temp == ' '|| i == original.length()-1)
{
if(letterCount >= minLegth)
{
count++;
}
letterCount = 0;
}
}
return count;
}
}
My college uses an autograder to grade project and i am keep getting one of the test case wrong. Can someone help me figure out what the problem is?
I figured the problem that your code is not able to compare the last character.It expects a space after the last character so that it can compare the last character since java doesn't use null character terminator for string termination.I have emulated the same code using Scanner class as I was having some trouble with io.So I have done the following change:
Scanner sc1,sc2;
sc1=new Scanner(System.in);
String input = sc1.nextLine()+" ";
I don't know if its possible to do:
String input = IO.readString()+" ";
but i think you should try appending blank space " " at the end of the string

Categories