I want to replace from String and print how many times it replaced.
for examples)
Input : aabba
from : aa
to : bb
ddbba
replaced : 1
Input : AAccaabbaaaaatt
from : aa
to : bb
ddccddbbddddatt
replaced : 4
I have a problem here:
for (int i = 0; i < input.length(); i++) {
if (inputL.indexOf(curStrL, i) > -1) {
cnt++;
i = (inputL.indexOf(curStrL, i))+1; // this part!
} else
continue;
} // for
My teacher said just use .indexOf and .replace, and .toLowerCase.
She gave some examples and they always replace two letters to two letters.
That's the reason why I put '+1' to find another letter.
If I remove that '+1', it counts 'aaa' twice.(aa a and a aa. And it replaced to 'dda', so it's wrong.)
But this time when I replace only one letter(ex.a), it counts less numbers than actually it has to be.(ex.'aaa' counts just two times.)
With the examples from teacher, it works well cuz all of them replace two letters.
But I want to improve this.
Here is all of my code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.print("Input : ");
String input = scan.next();
System.out.print("from : ");
String curStr = scan.next();
System.out.print("to : ");
String chStr = scan.next();
String inputL = input.toLowerCase();
String curStrL = curStr.toLowerCase();
String chStrL = chStr.toLowerCase();
String output = inputL.replace(curStrL, chStrL);
int cnt = 0;
if (inputL.indexOf(curStrL) == -1) {
System.out.println("Do it again");
} else
System.out.println(output);
for (int i = 0; i < input.length(); i++) {
if (inputL.indexOf(curStrL, i) > -1) {
cnt++;
i = (inputL.indexOf(curStrL, i))+1;
// *** to make the code find from the next letter! ***
} else
continue;
} // for
if (cnt > 0)
System.out.println("replaced : " + cnt);
else
{System.out.println("can't replace. Do it again");
break;}
System.out.println("----------------");
} // while
} // main
Just increase the counter variable of your loop with the lenght of the string to be replaced.
for (int i = 0; i < input.length(); i++) {
if (inputL.indexOf(curStrL, i) > -1) {
cnt++;
i = (inputL.indexOf(curStrL, i)); // EDIT by Shraft
i = i + curStr.length() - 1; // EDIT
// *** to make the code find from the next letter! ***
} else
continue;
} // for
Related
Write a program that will read a line of text String and display all the letters that occur in the text, one per line and in alphabetical order, along with the number of times each letter occurs in the text.
For this purpose, you must use an array of type int of length 26, so that the element at index 0 contains the number of a’s, the element at index 1 contains the number of b’s, and so forth.
Allow both uppercase and lowercase letters as input, but treat uppercase and lowercase versions of the same letter as being equal.
Hint: Use the method chatAt(int index) in the String class to get the individual character in a string at the specified index.
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] letters = new int[26];
char choice;
while (true) {
// taking user input
System.out.println("Please enter text ending with period:");
String text = sc.nextLine();
// converting it lowercase
text = getActualText(text).toLowerCase();
char c = 'a';
for (int i = 0; i < letters.length; i++)
// increasing character by 1
letters[i] = countLetters(text, c++);
System.out.println("\nThe frequency of the letters");
c = 'a';
for (int i = 0; i < letters.length; i++) {
// showing only those letters whose frequnecy is greater than 0
if (letters[i] != 0)
System.out.println(c + ": " + letters[i]);
c++;
}
System.out.print("Would you like to try another text?(Y/N) ");
choice = sc.nextLine().charAt(0);
if (choice == 'n' || choice == 'N')
break;
}
}
private static int countLetters(String text, char c) {
int count = 0;
for (int i = 0; i < text.length(); i++)
// counting the frequency
if (text.charAt(i) == c)
count++;
return count;
}
/**
* This method will extract the first sentence from a text ending with full stop(.)
*/
private static String getActualText(String text) {
String newText = "";
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '.')
// breaking out of the loop if the full stop is found
break;
// adding it to the text
newText += text.charAt(i) + "";
}
return newText;
}
}
Try to change existing condition to below new condition:
Existing Condition: (Allowing frequencies which are not equal to 0):
if(letters[i] != 0) {//showing only those letters whose frequency is greater than 0
New Condition: (Allowing frequencies which are greater than or equal to 0):
if(letters[i] >= 0) {
It's enough to go through the text one time and count the occurrence of each letter. And then just show only letters with count >0.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
do {
System.out.print("\nEnter the text: ");
String str = scan.nextLine();
print(histogram(str));
} while (shouldContinue(scan));
}
private static int[] histogram(String str) {
int[] letters = new int[26];
for (int i = 0; i < str.length(); i++)
if (Character.isLetter(str.charAt(i)))
letters[Character.toLowerCase(str.charAt(i)) - 'a']++;
return letters;
}
private static void print(int[] letters) {
System.out.println("The frequency of the letters:");
for (int i = 0; i < letters.length; i++)
if (letters[i] > 0)
System.out.println((char)('a' + i) + ": " + letters[i]);
}
private static boolean shouldContinue(Scanner scan) {
while (true) {
System.out.print("Would you like to try another text (Y/N)? ");
String str = scan.nextLine();
if (str.length() != 1)
continue;
if ("Y".equalsIgnoreCase(str))
return true;
if ("N".equalsIgnoreCase(str))
return false;
}
}
I am stuck. I have my array with data the user inputs. After their information is entered the program asks if they want to see items with characters above 10 or below. I can't seem to figure out this section. Below is where I am currently with the code.
import java.util.*;
import java.util.Scanner;
public class CategorizeStrings {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String[] array = new String[20];
System.out.println("Please enter anything..., or press 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 above 10 charaters (Above) or below 10 characters (Below)? Type Above or Below:");
String answer = s.nextLine();
if(answer == "Above"){
for (int i = 0; i < array.length; i++) {
if (array[i] != null)
len ++;
if(array[i].charAt(i)>10)
for (int x = 0; x < len; x++) {
if(array[x] == str )
System.out.print(len);
System.out.print(array[x] + " ");
}
}
}
else
{
}
System.out.println();
}
}
The block of code I'm struggling with is:
for (int i = 0; i < array.length; i++) {
if (array[i] != null)
len ++;
if(array[i].charAt(i)>10)
for (int x = 0; x < len; x++) {
if(array[x] == str )
System.out.print(len);
System.out.print(array[x] + " ");
}
Any help is appreciated.
If you just want to print the words that have above 10 characters
for (String value : array) {
if (value != null) {
if (value.length() > 10) {
System.out.print(value + " ");
}
}
}
This is how I would do it
Also note that Strings can't be compared using '=='
You should use equal or contentEquals
For example:
if (string1.equals(string2)) {
// Insert code here
}
or
if (string1.contentEquals(string2)) {
// Insert code here
}
Please Help!
If the user enters more than one word, output an error message to the user and repeat to allow them to enter the word again.
This is the code I have:
public void computeLetters(){
for(int i = 0; i < term.length()-1; i++){
if(term.charAt(i)==' ' && term.charAt(i+1)!=' ')
numberWords = 1;
}
for(int numberWords = 1; numberWords > 0;){
JOptionPane.showMessageDialog(null,"Please try again");
JOptionPane.showInputDialog(null,"Enter a word");
numberWords = 0;
}
for(int numberWords = 0; numberWords < 1;){
for(int j = 0; j < term.length()-1; j++){
numberLetters++;
}
}
}
A loop should work...
public void computeLetters()
{
while (true) {
// Get user input
String term = JOptionPane.showInputDialog("Enter a word");
if (null == term) return;
// Check if more than 1 word (has a space)
String [] words = term.split(" ");
// Single word?
if (words.length == 1) {
// Get letter count
int numberLetters = words[0].length();
// Do something else here???
// Done
return;
}
// Show error message
JOptionPane.showMessageDialog(null, "Please try again");
// And try again...
}
}
Edit based on comment using only if statements, loops or chars & strings (and ints).
public void computeLetters()
{
int numberLetters = 0;
while (numberLetters == 0) {
// Get user input
String term = JOptionPane.showInputDialog("Enter a word");
if (null != term) {
// Check if more than 1 word (has a space)
for (int i = 0; i < term.length(); i++) {
if (' ' == term.charAt(i)) {
numberLetters = 0;
break;
}
numberLetters += 1;
}
}
if (numberLetters == 0) {
JOptionPane.showMessageDialog(null, "Please try again");
}
}
// Do something with numberLetters here....
}
public void computeLetters(){
numberWords = term.trim().split("\\s+").length;
if(numberWords > 0 ){
JOptionPane.showMessageDialog(null,"Please try again");
term = JOptionPane.showInputDialog(null,"Enter a word");
computeLetters();
}
}
Number of words check, changed to a single line of code.
Next, the for loop in your code can be replaced by a simple 'if' as shown.
Then the next loop would have been an infinite loop. Just calling the function again after getting value from the user will do!
If this method is trying to get a single word from the user, validate it is one word, then count the number of letters in that word. This is how I would do it.
public int computeLetters()
{
String myWord = JOptionPane.showInputDialog("enter a single word.");
while(myWord.contains(" "))
{
JOptionPane.showMessageDialog("Cannot be more than one word.");
myWord = JOptionPane.showInputDialog("enter a single word.");
}
return myWord.toCharArray().length;
}
I am trying to create a Hangman and I have 2 problems.
1) The first problem is when the user finds the word, the loop does not stop.
2) I have a variable attempts which allows to know the number of attempts. Even if the user finds the letter, the number of attempts decrease.
The word to find is no
Here is a demonstration:
1) I enter the letter n
You have 5 attempts.
--
Enter your letter : n
2) I enter the letter o
The letter is good.
You have 4 attempts.
n-
Enter your letter : o
3) Normally the loop should stop.
The letter is good.
You have 3 attempts.
no
Enter your letter :
If you have an idea thank you in advance.
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = {/*"yes",*/ "no"};
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word_random.length(); i++) {
if ( word_found[i] ) {
System.out.print(word_random.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
for(int i=0; i<word_random.length();i++){
if(word_random.charAt(i) == letter){
System.out.println("The letter is good. ");
word_found[i] = true;
}
}
attempts--;
}
}
}
You are just missing a checking loop or method. Check the solution below.
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = {/*"yes",*/ "no"};
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while(attempts > 0){
System.out.println("You have " + attempts + " attempts.");
for(int i=0; i<word_random.length(); i++) {
if ( word_found[i] ) {
System.out.print(word_random.charAt(i));
}
else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
for(int i=0; i<word_random.length();i++){
if(word_random.charAt(i) == letter){
System.out.println("The letter is good. ");
word_found[i] = true;
}
}
boolean done = true;
for(boolean b : word_found)
done = done && b;
if(done) break;
else attempts--;
}
I will follow to your solution, not suggest a better one.
Ad 1. Add a check if the array word found contains only true after your first for cycle and if there are only true values in the array, print "you won" and set attempts to 0
Ad 2. Move attempts-- to the else case of your first for cycle OR add attempts++ in the true case of your first for cycle
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char letter = 0;
String[] words = { /* "yes", */ "no" };
String word_random = words[(int) (Math.random() * words.length)];
boolean[] word_found = new boolean[word_random.length()];
int attempts = 5;
while (attempts > 0) {
System.out.println("You have " + attempts + " attempts.");
for (int i = 0; i < word_random.length(); i++) {
if (word_found[i]) {
System.out.print(word_random.charAt(i));
} else {
System.out.print('-');
}
}
System.out.println("");
System.out.print("Enter your letter : ");
letter = input.next().charAt(0);
boolean match = false;
for (int i = 0; i < word_random.length(); i++) {
if (word_random.charAt(i) == letter) {
System.out.println("The letter is good. ");
word_found[i] = true;
match = true;
if (i == word_found.length - 1) {
System.out.println("THE END: attempts: " + attempts);
return;
}
}
}
if (!match) {
attempts--;
}
}
System.out.println("THE END");
}
I suggest you to modify the last part of your code like I did, and it should work.
I have this bit of code that is meant to alphabetize three words. I'm trying to remove the method at the bottom, and simply add it to the code above. However, I can't figure out a working way to do so. Any guidance or help would be appreciated, thank you!
System.out.print("Please enter three words: ");
final String words = keyboard.nextLine();
final String[] parts = words.split(" ");
if (parts[0].equals(parts[1]) && parts[1].equals(parts[2])) {
System.out.println("All three of those words are the same!");
} else {
System.out.print("In alphabetical order those are: ");
alphabetizing (parts);
final int three = 3;
for (int limit = 0; limit < three; limit++) {
System.out.print(parts[limit] + " ");
}
}
}
public static void alphabetizing (final String[] parts) {
int word;
boolean check = true;
String temp;
for (word = 0; word < parts.length - 1; word++) {
if (parts[ word ].compareToIgnoreCase(parts[word + 1]) > 0) {
temp = parts[word];
parts[word] = parts[word + 1];
parts[word + 1] = temp;
check = true;
}
}
}
}
Since you want to do it anyway. I don't see any problem why it will not work. Just add it into the else statement where you are calling the method and it should work.
System.out.print("Please enter three words: ");
Scanner keyboard = new Scanner(System.in);
final String words = keyboard.nextLine();
final String[] parts = words.split(" ");
if (parts[0].equals(parts[1]) && parts[1].equals(parts[2])) {
System.out.println("All three of those words are the same!");
} else {
System.out.print("In alphabetical order those are: ");
//boolean check = true; you don't neeed this.
String temp = "";
for (int word = 0; word < parts.length - 1; word++) {
if (parts[word].compareToIgnoreCase(parts[word + 1]) > 0) {
temp = parts[word];
parts[word] = parts[word + 1];
parts[word + 1] = temp;
}
}
final int three = 3;
for (int limit = 0; limit < three; limit++) {
System.out.print(parts[limit] + " ");
}
}
Output :
Please enter three words: a b c
In alphabetical order those are: a b c
Please enter three words: a a a
All three of those words are the same!