I'm trying to write a code that uses a scanner to input a list of words, all in one string, then alphabetizer each individual word. What I'm getting is just the first word alphabetized by letter, how can i fix this?
the code:
else if(answer.equals("new"))
{
System.out.println("Enter words, separated by commas and spaces.");
String input= scanner.next();
char[] words= input.toCharArray();
Arrays.sort(words);
String sorted= new String(words);
System.out.println(sorted);
}
Result: " ,ahy "
You're reading in a String via scanner.next() and then breaking that String up into characters. So, as you said, it's sorting the single-string by characters via input.toCharArray(). What you need to do is read in all of the words and add them to a String []. After all of the words have been added, use Arrays.sort(yourStringArray) to sort them. See comments for answers to your following questions.
You'll need to split your string into words instead of characters. One option is using String.split. Afterwards, you can join those words back into a single string:
System.out.println("Enter words, separated by commas and spaces.");
String input = scanner.nextLine();
String[] words = input.split(",| ");
Arrays.sort(words);
StringBuilder sb = new StringBuilder();
sb.append(words[0]);
for (int i = 1; i < words.length; i++) {
sb.append(" ");
sb.append(words[i]);
}
String sorted = sb.toString();
System.out.println(sorted);
Note that by default, capital letters are sorted before lowercase. If that's a problem, see this question.
Related
Enter two words: computer program
result: cute
the character of the second word of the users input is deleted on the first word of the input in java. Leaving "cute"
thought of using replaceAll but could not make it work.
String sentence;
Scanner input = new Scanner(System.in);
System.out.println("Enter 2 words: ");
sentence = input.nextLine();
String[] arrWrd = sentence.split(" ");
String scdWrd = arrWrd[1];
String fnl = arrWrd[0].replaceAll(scdWrd, "");
System.out.println(fnl);
.replaceAll takes a regex, so basically what you are doing here is you're searching for the whole "program" word and replacing it and not its characters, so you just need to add brackets to your scdWrd to let it know that you want to replace the chars:
String scdWrd = "[" + arrWrd[1] + "]";
Just to add to the elegant solution by #B.Mik, you should also check for things like
If multiple spaces are entered between the words.
If the user enters a blank line or just one word e.g. execute your program and enter a blank line or just one word e.g. computer and you will be welcomed with java.lang.ArrayIndexOutOfBoundsException.
The program given below addresses these points:
import java.util.Scanner;
public class LettersFromSecondReplacement {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean valid;
String input;
String words[];
do {
valid = true;
System.out.print("Enter two words separated with space: ");
input = in.nextLine();
words = input.split("\\s+"); //Split on one or more spaces
if (words.length != 2) {
System.out.println("Error: wrong input. Try again");
valid = false;
}
} while (!valid);
for (String s : words[1].split("")) { //Split the 2nd word into strings of one character
words[0] = words[0].replaceAll(s, "");
}
System.out.println(words[0]);
}
}
A sample run:
Enter two words separated with space:
Error: wrong input. Try again
Enter two words separated with space: computer
Error: wrong input. Try again
Enter two words separated with space: computer program
cute
Note that I have used a different algorithm (which you can replace with the one provided by #B.Mik) for replacement. Feel free to comment in case of any doubt/issue
replace line with replaceAll by
String fnl = arrWrd[0];
for (byte c : scdWrd.getBytes()) {
fnl = fnl.replace("" + (char)c, "");
}
I am trying to make a word counter in java. I'm trying to count words by separating them with spaces.
I've managed to get rid of the spaces before or after a sentence with the trim function. However, I haven't been able to adjust for the case that the user types more than one space in between two words. For example, so far the string "hello world" with multiple spaces between hello and world, would output a word count greater than two. This is the code that I have tried so far to fix this problem.
public void countWord(){
String tokens[] = userInput.trim().split(" ");
int counter = tokens.length;
for(int i = 0; i < tokens.length; ++i) {
if(Objects.equals(" ", tokens[i])) {
--counter;
}
}
System.out.printf("Total word count is: %d", counter);
}
As you can see I create a word counting integer that holds the number of tokens created. Then I try and look for a token that only contains " " then decrement the word count by the amount of those strings. However this is not solving my problem.
Try regex to split
userInput.split("\\s+");
You've already split() on spaces, so there will be no more spaces in any of the tokens as split() returns:
the array of strings computed by splitting this string around matches of the given regular expression
(Emphasis mine)
However if there are extra spaces in your String there will be extra tokens, which will throw off the length. Instead use split("\\s+"). Then just return the length of the Array, as split() already will return all the tokens separated by spaces, which will be all the words:
System.out.printf("Total word count is: %d", tokens.length);
Which will print 5 for the test String
"Hello this is a String"
If you are intended to count the words, give a try to one of the followings:
Among those that others mentioned.
Here, this solution uses StringTokenizer.
String words = "The Hello World word counter by using StringTokenizer";
StringTokenizer st = new StringTokenizer(words);
System.out.println(st.countTokens()); // => 8
This way you can take an advantage of regexp by using it to split the string by words
String words = "The Hello World word counter by using regex";
int counter = words.split("\\w+").length;
System.out.println(counter); // => 8
Use Scanner for your own counter method:
public static int counter(String words) {
Scanner scanner = new Scanner(words);
int count = 0;
while(scanner.hasNext()) {
count += 1;
scanner.next();
}
return count;
}
If you want to count the spaces as you said in the title, you can use StringUtils from Commons
int count = StringUtils.countMatches("The Hello World space counter by using StringUtils", " ");
System.out.println(count);
Or if you use Spring the SpringUtils is also available for you.
int count = StringUtils.countOccurrencesOf("The Hello World space counter by using Spring-StringUtils", " ");
System.out.println(count);
I think you can easily fix it by checking if a tokens[i].equals(""). Thus checking if a word is an empty string. Since splitting on a space when using multiple spaces creates empty string objects in the array, this should work.
Why don't you get rid of all occurrences of 2 or more adjacent spaces and then split:
String tokens[] = userInput.trim().replaceAll("\\s+", " ").split(" ");
I have a problem. I want to type in a string (with Java.util.scanner) with two words. Then I want the program to split my entered string at the whitespace, save both substrings in a seperate variable and make a output in the end.
I know that you can split strings with
String s = "Hello World";
String[] = s.split(" ");
But it doesnt seem to work when your String is
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
Any help?
Thank you very much
s.split("\\s+"); will split your string, even if you have multiple whitespace characters (also tab, newline..)
You can also use from java.util package
StringTokenizer tokens = new StringTokenizer(s.trim());
String word;
while (tokens.hasMoreTokens()) {
word = tokens.nextToken();
}
Or from Apache Commons Lang
StringUtils.split(s)
Your code works for me:
String s;
s=sc.nextLine();
String[] words=s.split(" ");
for(String w:words){
System.out.print(w+" ");
}
input: "Hello world"
output: "Hello world"
You may also want to try this way of splitting String that you get from user input:
Scanner sc = new Scanner(System.in);
String[] strings = sc.nextLine().split("\\s+");
If you simply want to print array containing these separated strings, you can do it without using any loop, simply by using:
Arrays.toString(strings);
If you want to have your printed strings to look other way, you can use for it simple loop printing each element or by using StringBuilder class and its append() method - this way may be faster than looping over longer arrays of strings.
I am new to Java and looking for some help with Java's Scanner class. Below is the problem.
I have a text file with multiple lines and each line having multiple pairs of digit.Such that each pair of digit is represented as ( digit,digit ). For example 3,3 6,4 7,9. All these multiple pairs of digits are seperated from each other by a whitespace. Below is an exampel from the text file.
1 2,3 3,2 4,5
2 1,3 4,2 6,13
3 1,2 4,2 5,5
What i want is that i can retrieve each digit seperately. So that i can create an array of linkedlist out it. Below is what i have acheived so far.
Scanner sc = new Scanner(new File("a.txt"));
Scanner lineSc;
String line;
Integer vertix = 0;
Integer length = 0;
sc.useDelimiter("\\n"); // For line feeds
while (sc.hasNextLine()) {
line = sc.nextLine();
lineSc = new Scanner(line);
lineSc.useDelimiter("\\s"); // For Whitespace
// What should i do here. How should i scan through considering the whitespace and comma
}
Thanks
Consider using a regular expression, and data that doesn't conform to your expectation will be easily identified and dealt with.
CharSequence inputStr = "2 1,3 4,2 6,13";
String patternStr = "(\\d)\\s+(\\d),";
// Compile and use regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
while (matcher.find()) {
// Get all groups for this match
for (int i=0; i<=matcher.groupCount(); i++) {
String groupStr = matcher.group(i);
}
}
Group one and group two will correspond to the first and second digit in each pairing, respectively.
1. use nextLine() method of Scanner to get the each Entire line of text from the File.
2. Then use BreakIterator class with its static method getCharacterInstance(), to get the individual character, it will automatically handle commas, spaces, etc.
3. BreakIterator also give you many flexible methods to separate out the sentences, words etc.
For more details see this:
http://docs.oracle.com/javase/6/docs/api/java/text/BreakIterator.html
Use the StringTokenizer class. http://docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html
//this is in the while loop
//read each line
String line=sc.nextLine();
//create StringTokenizer, parsing with space and comma
StringTokenizer st1 = new StringTokenizer(line," ,");
Then each digit is read as a string when you call nextToken() like this, if you wanted all digits in the line
while(st1.hasMoreTokens())
{
String temp=st1.nextToken();
//now if you want it as an integer
int digit=Integer.parseInt(temp);
//now you have the digit! insert it into the linkedlist or wherever you want
}
Hope this helps!
Use split(regex), more simple :
while (sc.hasNextLine()) {
final String[] line = sc.nextLine().split(" |,");
// What should i do here. How should i scan through considering the whitespace and comma
for(int num : line) {
// Do your job
}
}
Pls I want to keep a count of every word from a file, and this count should not include non letters like the apostrophe, comma, fullstop, question mark, exclamation mark, e.t.c. i.e just letters of the alphabet.
I tried to use a delimiter like this, but it didn't include the apostrophe.
Scanner fileScanner = new Scanner("C:\\MyJavaFolder\\JavaAssignment1\\TestFile.txt");
int totalWordCount = 0;
//Firstly to count all the words in the file without the restricted characters
while (fileScanner.hasNext()) {
fileScanner.useDelimiter(("[.,:;()?!\" \t\n\r]+")).next();
totalWordCount++;
}
System.out.println("There are " + totalWordCount + " word(s)");
//Then later I create an array to store each individual word in the file for counting their lengths.
Scanner fileScanner2 = new Scanner("C:\\MyJavaFolder\\JavaAssignment1\\TestFile.txt");
String[] words = new String[totalWordCount];
for (int i = 0; i < totalWordCount; ++i) {
words[i] = fileScanner2.useDelimiter(("[.,:;()?!\" \t\n\r]+")).next();
}
This doesn't seem to work !
Please how can I go about this ?
Seems to me that you don't want to filter using anything but spaces and end lines. For example the word "they're" would return as two words if you're using a ' to filter your number of words. Here's how you could change your original code to make it work.
Scanner fileScanner = new Scanner(new File("C:\\MyJavaFolder\\JavaAssignment1\\TestFile.txt"));
int totalWordCount = 0;
ArrayList<String> words = new ArrayList<String>();
//Firstly to count all the words in the file without the restricted characters
while (fileScanner.hasNext()) {
//Add words to an array list so you only have to go through the scanner once
words.add(fileScanner.next());//This defaults to whitespace
totalWordCount++;
}
System.out.println("There are " + totalWordCount + " word(s)");
fileScanner.close();
Using the Pattern.compile() turns your string into a regular expression. The '\s' character is predefined in the Pattern class to match all white space characters.
There is more information at
Pattern Documentation
Also, make sure to close your Scanner classes when you're done. This could prevent your second scanner from opening.
Edit
If you want to count the letters per word you can add the following code to the above code
int totalLetters = 0;
int[] lettersPerWord = new int[words.size()];
for (int wordNum = 0; wordNum < words.size(); wordNum++)
{
String word = words.get(wordNum);
word = word.replaceAll("[.,:;()?!\" \t\n\r\']+", "");
lettersPerWord[wordNum] = word.length();
totalLetters = word.length();
}
I have tested this code and it appears to work for me. The replaceAll, according to the JavaDoc uses a regular expression to match so it should match any of those characters and essentially remove it.
The Delimiter is not a regular expression, so with your example it is looking for things split between "[.,:;()?!\" \t\n\r]+"
You can either use regexp instead of the Delimiter
using the regexp class with the group method may be what your looking for.
String pattern = "(.*)[.,:;()?!\" \t\n\r]+(.*)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(test);
if (m.find( )) {
System.out.println("Found value: " + m.group(1) );
}
Play with those classes and you will see it is much more similar to what you need
You could try this regex in your delimiter:
fileScanner.useDelimiter(("[^a-zA-Z]|[^\']")).next();
This will use any non-letter character OR non apostrophe as a delimiter. That way your words will include the apostrophe but not any other non-letter character.
Then you'll have to loop through each word and check for apostrophe's and account for them if you want the length to be accurate. You could just remove each apostrophe and the length will match the number of letters in the word, or you could create word objects with their own length fields, so that you can print the word as is, and know the number of letter characters in that word.