How to search for strings using method indexOf - java

14.11 (Searching Strings) Write an application that inputs a line of text and a search character and uses String method indexOf to determine the number of occurrences of the character in the text.
14.12 (Searching Strings) Write an application based on the application in Exercise 14.11 that inputs a line of text and uses String method indexOf to determine the total number of occurrences of each letter of the alphabet in the text. Uppercase and lowercase letters should be counted together. Store the totals for each letter in an array, and print the values in tabular format after the totals have been determined.
My problem now is that how can I determine occurrence of each letter in a word. For example, the word "occurrence", how many times each letter occurred in this word.
I've written my code to the best of my understanding, and my code can display the characters and returns their indexes in a tabular form. But that is not exactly what the questions required.
import java.util.*;
public class Searching
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Text: ");
String text1 = input.nextLine();
char[] text2 = text1.toCharArray();
System.out.println("Character Index");
for(int i = 0; i < text2.length; i++)
{
System.out.printf("%s%12d%n", text2[i],text1.indexOf(text2[i], i));
}
}
}
I want the actual output to be in a tabular format. The word "occurrence", my code should display each letter and how many times it occurred.
LETTER FREQUENCY
o 1
c 3
u 1
r 2
e 2
n 1

Is it ok if you used a HashMap? Here's the solution for 14.12:
Scanner in = new Scanner(System.in);
System.out.print("Enter text: ");
//So we only have to find lower case chars
String input = in.nextLine().toLowerCase();
//Add every single character in the word
//We use a LinkedHashMap instead of a HashMap to retain character order during printing.
LinkedHashMap<Character, Integer> characterCount = new LinkedHashMap<>();
for(int i = 0; i < input.length(); i++) {
characterCount.put(input.charAt(i), 0);
}
//Iterate from every character ranging from a - z
//It would be more ideal to iterate only over the characters
//in the word. But your requirement asked to iterate over the alphabet.
for(int i = 'a'; i <= 'z'; i++) {
//This is the character we are currently searching for
Character searchingFor = (char)i;
int startingIndex = 0; int foundIndex = 0;
//Search for the character in the string FROM a specfic index (startingIndex in this case)
//We update startingIndex to a bigger index in the string everytime we find the character.
while((foundIndex = input.indexOf(searchingFor, startingIndex)) != -1) {
//it must be the index+1 so the next time it checks after the found character.
//without the +1, it's an infinite loop.
startingIndex = foundIndex + 1;
//Update count to the current value + 1
characterCount.put(searchingFor, characterCount.get(searchingFor) + 1);
}
}
//Print the results
for(Character c : characterCount.keySet()) {
System.out.printf("%s%12d%n", c, characterCount.get(c));
}
in.close();
Console output for the word "occurence":
Enter text: occurence
o 1
c 3
u 1
r 1
e 2
n 1

Related

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");
}
}

Is there a Way I can rearrange characters in a given string using a modified set of index values?

Say I have the string: "Polish". which is indexed as: P=0,O=1, L=2, I=3, S=4, H=5
I want to be able to type something like
" word1.arrangebyindex(051423) "
and have word2 equal PHOSLI
I want to be able to type in any combination of index values and have it rearranged to a new word.
I'm trying to write a program that will rearrange a given word in the following way:
The first character of the word is followed by the last character of the word which is followed by the second character and then the second last character of the word and so on. If the given word has an odd number of characters, then the middle character is repeated again. For example, given the word "mouse" it should be encoded as "meosuu"
I suggest making a hashmap, which allows the user to enter in a letter, which would be the key and a number, which would be the value.
Once you associate all the letters with the number as a key and a value (such as P: 0 and H:5), then you can use your hashmap to create a string based on the numbers given to you.
Break each number down by digits (note that it will be more difficult to implement if a word is associated with a multiple digit number) and add to the string depending on what number you have called.
Here's the hashmap api: https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
Just look at the method summary and try those. I doubt you'll need much else out of the rest of the api.
If you use HashMap then key as integer and value should be character because if string = APPLE then 0-A 1-P 2-P 3-L 4-E.
or you should go through this way:
public class ModifiedIndex {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
char [] ch = str.toCharArray();
String s ="";
int i=0;
int j = str.length()-1;
if(str.length()%2 == 0)
{
for(int k = 0; k < str.length()/2; k++)
{
s = s+ch[i] +ch[j];
i++;
j--;
}
}
else
{
for(int k = 0; k < str.length(); k++)
{ if(i<=j)
{
s = s+ch[i] +ch[j];
i++;
j--;
}
}
}
}
}

Input/comparing strings, Returning number, Java

Recently, I've been trying to build a program that does 4 things:
1) Enter a word from the keyboard.
2) Check the context of this word with the context of a string that contains the letters of the alphabet.
3) Compare the letters of the given word with the letters of the alphabet string and whenever there is match, it will return the position of that letter in the alphabet string +1. (ex. word='a' position=1 since 'a' is the first letter)
4) Get the total of all of these positions.(ex. word='abc' total=6)
Now let me show you what I've written in terms of code.
//Part 1 Entering word from keyboard
package IntroductionJava;
import java.util.Scanner;
public class Numerology
{
public static void main(String[] args)
{
int m=0,n=0,sum=0;
int j,k;
Scanner user_input=new Scanner(System.in);
String word;
System.out.print("Give a word: ");
word=user_input.next();
String word1 = "\u03b1\u03b2\u03b3\u03b4\u03b5\u03b6\u03b7\u03b8\u03b9\u03ba\u03bb\u03bc\u03bd\u03be\u03bf\u03c0\u03c1\u03c3\u03c2\u03c4\u03c5\u03c6\u03c7\u03c8\u03c9";
//Part 2 check word
for(int i=0; i<word.length(); i++)
{
if(word.charAt(i)>=word1.charAt(0) && word.charAt(i)<=word1.charAt(word1.length()-1))
{
System.out.println("Your word '"+word+"' is valid.");
break;
}
else
{
System.out.println("Your word '"+word+"' is invalid.");
}
break;
//show System.out.print(word.charAt(i));
}
//Part 3 Compare letters
for(j=0; j<word.length(); j++)
{
for(k=0; k<word1.length(); k++)
{
if(word.charAt(j)==word1.charAt(k))//???
{
m=k+1;
}
}
}
}
Now, Part 1 and 2 are working fine.
My problem lies when I try to compare the letters of the word that I'm entering with the String of letters in unicode format(the letters in unicode format are from the Greek alphabet). I've tried many variations, I've also consulted some of the articles here but I couldn't find a solution.
To make things a bit more clear let's say that I'm entering the word: "hello". I want to check whether 'h' is inside the alphabet string, and if it is I want to get it's position as an integer which in our case it's the number '8' (position in the string +1) and so on.
And the last part of my program is to get all those numbers from the given word and get it's total ('hello'=8+5+12+12+20=57).
Thank you very much in advance.
How about this:
String alphabet = "abcdefgh";
String input = "abc";
int value = input.chars()
.map(alphabet::indexOf)
.map(i -> i + 1)
.sum()
System.out.println(value);

Count and display the occurrences of each of the letters of the alphabet, in alphabetical order using Java

Good Afternoon I've a piece of code that will count and display the occurrences of each of the letters of the alphabet from user input. But I need to put it in alphabetical order and display the most frequently occurring letter and the number of occurrences for that letter:
package Assessment2;
import java.util.Scanner;
public class test2 {
String str = "Hello World", s = str;
int count = 0;
public void show() {
Scanner input = new Scanner(System.in);
System.out.print("Enter String: ");
String s = input.nextLine();
System.out.println("****************************");
while (s.length() > 0) {
count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(0))
count++;
}
System.out.println(s.charAt(0) + ": " + count);
s = s.replace(String.valueOf(s.charAt(0)), "");
}
}
public static void main(String[] ar) {
new test2().show();
}
}
For the part ,you are trying to Sort them by alphabetic order:
us the following
--for currentChar in a--z
--for(loop) each char in inputString
--if you encounter any char = currentChar then
--append that character to finalstring
nd if
end loop
end for
I have to mention that if you know any sorting algorithms it is better to use that ex: bubble
In order to put the letters in alphabetical order, you need to sort it. You can write your own code to sort the characters of the string or you could use Arrays.sort() to sort an array of characters.
Use char[] charArray = s.toCharArray() to convert the string to a char array and then use Arrays.sort(charArray) to sort the array in alphabetical order.
You can then just loop through the array to find the number of occurrences of each character in the array and then print them.

Counting characters in a Character array - JAVA

First off i am pretty fresh when it comes to java. My program is supposed to ask the user for strings and print what they just put in. It is then supposed to change all characters to lowercase and remove all spaces from the strings and print this. After this, it is supposed to print a character array of the alphabet and use an asterisk (*) to show each time a character occurs in the string (I dont even know where to start here). Right now it just prints the String in an array(not correct). This is what I have so far. It will print either the string with no spaces or the original but not both. My object/array naming is atrocious and i apologize in advance. Any guidance would be greatly appreciated
EDIT: here is the question
In this assignment you are to write a program that will do the following:
Ask the user to input a positive integer m, and then read that integer. Use a
Scanner object declared in main to read this integer.
Call a method that will ask the user to input m strings. As the strings are
read, they should be concatenated into a single string st. After reading the m strings and forming the single string st, the method should return st. NOTE: This method will have two parameters, an int to receive m and a Scanner object to receive the Scanner object declared in main.
In main print the concatenated string received from the method.
In main convert the String object to lower case.
In main convert the lower case String object to an array of char. (All letters
will be lower case.)
In main print the character array just created. (Requires a looping structure.)
Call a method that will compress the character array in the following way.
The method will count the letters of the alphabet in the array, create a new array whose size is equal to that count, and copy only the letters of the original array into the new array. Return the new array.
In main declare an integer array of size 26. Call a method with two parameters, a character array x (which will contain only lower case letters, and an integer array z that will receive the one declared in main). The method will set all entries in the integer array to zero. It will then process through the lower case letter array and count the number of times each letter occurs. HINT: z[x[i]-97]++ can do the counting. The ASCII code for a is 97, so if x[i] is ‘a’, then z[0] will be incremented. ‘b’ would cause z[1] to be incremented, etc. The integer array now contains a frequency distribution for the letters in the array of lowercase letters.
Call a method with one integer array parameter (which will receive the frequency distribution array) and print each letter on a new line followed by the number of stars equal to the integer value in that array element. This must be neatly aligned. Hint: if i is an index with 0 ≤ 𝑖 ≤ 25, then (char)(i+97) is a lower case letter of the alphabet.
package lab6;
import java.util.Scanner;
public class Lab6 {
public char sent[];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter the number of strings you want: ");
int m = input.nextInt();
Lab6 loo = new Lab6();
loo.print(loo.loop(m));
}
public String loop(int m) { //print the string that was entered
String total = " ";
for (int i = 1; i <= m; i++) {
Scanner input = new Scanner(System.in);
System.out.println("enter string: " + i);
String st = input.nextLine();
total += st + "";
}
System.out.println(total);
return total;
}
public void print(String ht) { //print array
String st = ht.toLowerCase().replaceAll("\\s", "");
sent = st.toCharArray();
for (int i = 0; i < sent.length; i++) {
System.out.println(sent[i]);
}
}
}
Sounds like computer science is not your cup of tea. I Strongly recommend you refactor this code and try to figure out why it does what it does.
public void print(String ht) { // print array
String st = ht.toLowerCase().replaceAll("\\s", "");
sent = st.toCharArray();
int[] alphabet = new int[26];
//set all values to 0
for(int i = 0 ; i < alphabet.length ; i++){
alphabet[i] = 0;
}
//Loop through all characters and increment corresponding value
for(int i = 0 ; i < sent.length ; i++){
alphabet[sent[i] - 97]++;
}
//Print character + asterisk for each time the character is used
for(int i = 0 ; i < alphabet.length ; i++){
System.out.print((char)(i + 97) + ": ");
for(int nChars = 0 ; nChars < alphabet[i] ; nChars++){
System.out.print("*");
}
System.out.println();
}
}

Categories