I am practising with algorithms, and I have this problem where I have to state how many of each of the letters in the word appear. e.g. input = floor , output = f1l1o2r1. I have the following code:
public static void main(String[] args) {// TODO code application logic here
Scanner inword = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("Enter word");
String word = inword.nextLine();
int length = word.length();
char[] wordArray = word.toCharArray();
for(int i = 0; i<length; i++){
int count = StringUtils.countMatches(word, String.valueOf(wordArray[i]));
System.out.print(wordArray[i] + count);
}
}
but instead I get this as output: 103109113113115 , when I enter floor as input
Your problem is that you print out the ascii-code value of the char. Try
System.out.print(wordArray[i]+"" + count);
instead of
System.out.print(wordArray[i] + count);
First, you should use countMatches(word, wordArray[i]); But that will not solve the entire problem. For example, your approach would lead to an output of "f1l1o2o2r1", and for the word "boohoo", you would get "b1o4o4h1o4o4".
You need to rethink how to do it if you want the output to show the number of consecutive same letters ("b1o2h1o2"), or if you want the number of each letter, specified only once, in order of first appearance ("b1o4h1"), or the number of appearances of letters alphabetically ("b1h1o4").
Considering the implementation of StringUtils.countMatches() is correct, the problem lies in the line
System.out.print(wordArray[i] + count);
Here, when you do wordArray[i], it returns a char. However, doing +count, converts that char into its ASCII value, and adds up count to it.
To fix it, try doing:-
System.out.print(wordArray[i] + " " + count);
Related
I have large text files and they each contain strings of words and numbers.
I need to increase those numbers by a fixed value and write them right back to where they were before within that string.
The value that I want to add depends on the word that came before the number, and every number that has none of these keywords must not be increased.
My approach would be to split at space characters, check for the words and handle the digit after, whenever I find the keyword. However, this leaves me with the requirement of having space characters between word and number and that is not ensured.
Furthermore, when reassembling the string from the split array, this might break the layout from before.
An example could be
"Mark is quite large, 189cm, and was born in the year 1978. However, he has only 1 question concerning parsing, that he really can't get his head around."
After large, the height should be increased by 5 and after year, the number subtracted by 19. The number 1 should stay untouched, as only is not a keyword.
I can work with both, java or python, as these are the languages I know.
I think i got something:
public class Start {
public static void main(String[] args){
//Test String
String s = "not4inc6desc3inc14";
StringBuffer sb = new StringBuffer(s);
//keep track where new word begins
int newWord = 0;
for(int i = 0; i < sb.length(); i++){
//chekc if the new Character is a number
if(checkNumber(sb.substring(i, i+1))){
//if the old word ends with "inc"
//maybe try out .contains()
if(sb.substring(newWord, i).endsWith("inc")){
//replace number
StringBuffer temp = new StringBuffer();
int j = 0;
//get full number
for(j = i; j < sb.length() && checkNumber(sb.substring(j, j+1)); j++){
temp.append(sb.substring(j, j+1));
}
//modify number
int number = Integer.parseInt(temp.toString()) + 1;
//replace number
sb.replace(i, i + temp.length(), Integer.toString(number));
//number no longer needs to be checked for being a word
i=j;
}
}
}
//print test String
System.out.println(sb.toString());
}
// Check if String is numeric
private static boolean checkNumber(String s){
try{
Integer.parseInt(s);
}catch(NumberFormatException e ){
return false;
}
return true;
}
}
I'm sorry it's a bit hard to understand... feel free to ask...
So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.
I am a very new to Java, so my knowledge is very limited. I have been trying to find the problem in this block of code.
import java.util.Scanner;
public class avgFinder {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input numbers to average. Separate by a space.");
String nums = scan.next();
String[] parseNums = nums.split("[ ]");
double sum = 0;
int cnt = 0;
for (int a=0; a<=parseNums.length-1; a++) {
sum += Double.parseDouble(parseNums[a]);
cnt++;
}
double mean = sum/cnt;
System.out.println("Mean: " + mean);
}
}
But when I input a a set of numbers, only the first number gets printed instead of the actual mean. Example:
Input numbers to average. Separate by a space.
1 2 3
Mean: 1.0
Another thing is if I replace nums.split("[ ]") with nums.split("[,]") and put commas instead of spaces between the numbers in the output, it actually outputs the mean. I like spaces better though, it looks cleaner. Why is this happening?
Try this
use nextLine() instead of next()
nextLine returns complete line of text while next returns only one word
Also use nums.split(" ");
import java.util.Scanner;
public class avgFinder {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Input numbers to average. Separate by a space.");
String nums = scan.nextLine();
String[] parseNums = nums.split(" ");
double sum = 0;
int cnt = 0;
for (int a=0; a<=parseNums.length-1; a++) {
sum += Double.parseDouble(parseNums[a]);
cnt++;
}
double mean = sum/cnt;
System.out.println("Mean: " + mean);
}
}
Calling Scanner.next() will return the next element in a line before a space, so you only getting the first number in your input. Use Scanner.nextLine() which will return all the values on that line.
Scanner.next() returns the next word. By default, words are separated by whitespace. So when you call Scanner.next(), your scanner reads the digits of the first number, hits a space, and says "ok, that's the end of the word. Time to return the result" and you end up with just the first number.
That's why it works when you replace the spaces with commas: Without any spaces, the scanner doesn't find whitespace until it reaches the line break, so it returns the whole line.
Scanner.nextLine() returns the entire line instead of just one word (it reads until it hits a line break), so I'd suggest using that instead.
I made a program that lets a user enter in a word or a phrase or a sentence and reverse it and display the result.
My issue is that when I run it it does reverse it but it reverses the words when all I want to do is keep the words as they were inputted and just reverse them.
Here is what I have currently
//import statements
import java.util.*; //for scanner class
// class beginning
class WordReverser {
public static void main(String[] args ) {
//Declare variables area
String original, reverse = "";
Scanner in = new Scanner(System.in);
boolean blankString = false;
public StringBuilder reverse();
// beginning message to user to explain the program
System.out.println("Welcome to my reverse word program!");
System.out.println("Please enter in a word or a phrase and see it reversed: ");
//main code and calculations to do
while (!blankString){
System.out.println("Enter a string to reverse");//Collect inputs from user.
original = in.nextLine();
if (original.equals(""))
{
blankString = true ;
}
else {
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: "+reverse);//Output results here
}
}
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
}// end class
Clearly a homework question, so I'll give you a shove in the right direction, but I won't give the full answer. You need to reverse one word at a time and not the whole string.
You need something that implements this pseudo code:
original = getStringFromUser();
words[] = breakIntoWords(original);
foreach word in words {
reversed = reverse(word);
print reversed;
}
reverse(string word)
{
return reversed version of the input
}
breakIntoWords(sting sentence)
{
return array with each word as a sep.element
}
If you read the docs, you may find reverse and breakIntoWords are already there for you, so you just need to call the right methods.
The key to solving problems is learning how to break them down into smaller pieces that are easier to solve. This is a good problem solving technique and is at the heart of programming.
You know how to reverse the letters in a sentence. You want to reverse the letters in each word, but leave the words in their original order. Or, to say it another way, you want to:
Split the sentence into separate words.
Reverse each word one by one.
Combine the words back together into a sentence.
Hopefully each of these steps is more manageable. If not, think about how you can break them into even smaller steps. For instance, for #2 maybe you need a loop and then something inside that loop.
Do you want to reverse the word order? In this case you'll have to split the input string at " ".
To do this, your else-block should be
String[] words = original.split(" ");
for(int i = words.length-1; i>=0; i--)
reverse += words[i] + " ";
System.out.println("Reverse of entered string is: "+reverse);
I see 2 ways of dealing with this quickly if not too elegantly
easiest thing to do would be to create a 3rd variable called something like String originalWords that gets appended to from stdin in the loop.
Reuse the existing 'original' String to do the same as above and then loop it in reverse in a second loop.
You can split the input string into separate array of words and then reverse each word in the array separately.
Refer this for code.
I have refactored your code a little bit to solve your issue. First I put your reverse logic in a separate method
public static String reverse(String strToReverse) {
String original = strToReverse, reverse = "";
boolean blankString = false;
if (original.equals(""))
{
blankString = true ;
}
else {
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
}
return reverse;
}
Second I splitted your string into words (assuming the words are separated by simple spaces)
public static void main(String[] args ) {
//Declare variables area
String original, reverse = "";
Scanner in = new Scanner(System.in);
boolean blankString = false;
//public StringBuilder reverse();
// beginning message to user to explain the program
System.out.println("Welcome to my reverse word program!");
System.out.println("Please enter in a word or a phrase and see it reversed: ");
//main code and calculations to do
while (!blankString){
System.out.println("Enter a string to reverse");//Collect inputs from user.
original = in.nextLine();
if (original.equals(""))
{
blankString = true ;
}
else {
String[] words = original.split(" ");
String[] reversedWords = new String[words.length];
StringBuilder reverseBuilder = new StringBuilder();
for (int index = 0; index < words.length; index++) {
reversedWords[index] = reverse(words[index]);
reverseBuilder.append(reversedWords[index] + " ");
}
System.out.println("Reverse of entered string is: "+reverseBuilder.toString());//Output results here
}
}
//End program message
System.out.println();
System.out.println("Hope you enjoyed using this program!");
}// end main method
Here is an execution example:
The goal of this code was to create a program using main method java to analysis a piece text which has been entered from a user.
They do this by entering the text into a scanner which is then analysed by the program. The analysis is to produce word frequency, for example " This is a test" produces this results:
This is a test
1 letter words: 1
2 letter words: 1
3 letter words: 0
4 letter words: 2
5 letter words: 0
The bit that I'm stuck on is producing a mean/average, My guts telling to divide
counts.length by str.length but I'm not the Best at java and I've tried to implement this but all I get are errors. I'm not expecting anyone to just hand me code, but if someone could give me a hint in what I should do or just point me the right direction it would be greatly appreciated.
Code:
import java.util.Scanner;
public class Text_AD {
public static void main (String[] args) {
while(true){
Scanner input = new Scanner(System.in);
System.out.println("Enter text: ");
String s;
s = input.nextLine();
System.out.println("" + s);
String[] strings = s.split(" ");
int[] counts = new int[6];
for(String str : strings)
if(str.length() < counts.length) counts[str.length()] += 1;
for(int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
}}}
By average, I am assuming that you mean the mean length. I am also assuming you want to get a floating point mean. In which case you just need to divide the total of all the lengths in strings by the length of the array itself.
You could do something like the following;
int total = 0;
for(String s : strings) total += s.length();
System.out.println((double)total/strings.length);
I hope this helps.
Without breaking up your code much, you could run a for loop through your counts[] array, adding up all the values, and then dividing by counts.length to get the average.
Be aware of type casting though. You may want to do Double division instead of integer.
It this what you are looking for?
import java.util.Scanner;
public class While_Loop {
public static void main (String[] args) {
int lengthSum, wordCount;
lengthSum = wordCount = 0;
while(true){
Scanner input = new Scanner(System.in);
System.out.println("Enter text: ");
String s;
s = input.nextLine();
System.out.println("" + s);
String[] strings = s.split(" ");
int[] counts = new int[6];
for(String str : strings)
if(str.length() < counts.length) counts[str.length()] += 1;
wordCount++;
lengthSum += str.length();
for(int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
System.out.println("Average: " + lengthSum/wordCount);
}}}
NOTE: I only added stuff to your code. The way it is written is pretty messy. I'd clean up some of the for loops and the brackets at the end for practice making the code more readable.
When I understand you correct you should have one variable int totalCount = 0; where you add
totalCount += i*counts[i]; in your last for loop.
After the loop you can simply divide through the size-1 (because 0 does not count)
double average = totalCount/(counts.length-1);
Alternative way
You take the inputstring length without the spaces and divide it by the number of spaces + 1 (which is equal to the number of words)
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
System.out.println("Enter text: ");
String s = "This is a sample text";
System.out.println("" + s);
String[] strings = s.split(" ");
for(String str : strings) {
Integer counter = map.get(str.length())==null?0:map.get(str.length());
map.put(str.length(),counter++);
}
Integer sum=0;
Integer counter=0;
for(Integer len : map.keySet()) {
sum+=len*map.get(len);
counter+=map.get(len);
}
Double average = Double.valueOf(sum/counter);
Or you can combine the loops
Few suggestions which might help you (not related to the specific question).
Choose a meaningful class name rather than While_Loop .
Do, Scanner input = new Scanner(System.in); before the start of the loop.
As soon as you read each line, do the following.
Split the line using "\\s+" .
Create a HashMap with Key as Count (Integer) and Value as a list of Words with that count. Create this outside the loop.
For each split word,,get the length . and check if the map already contains the count, get the list (value), add he current word to it. else, add a new entry with the word as the single entry in the list.
Get the keySet of the map, add values of all keys i.e, *count * number of elements in the list*. then divide by total number of elements.
And yes, I know this is a very big change (something you might as well ignore..). But this is the right way to go.