count words of sentences? - java

i want to count number of words per sentences i write code but count character for each word in sentences this my code
public static void main(String [] args){
Scanner sca = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
String sentences= sca.nextLine();
String []count_words= sentences.split(" ");
for(String count : count_words){
System.out.println("number of word is "+count.length());}
}

String[] count_words= sentences.split(" "); is splitting the input argument by " " that means that length of this array is the number of words. simply print the length out.
public static void main(String[] args) {
Scanner sca = new Scanner(System.in);
System.out.println("Please type some words, then press enter: ");
String sentences= sca.nextLine();
String[] count_words= sentences.split(" ");
System.out.println("number of word is "+ count_words.length);
}
example:
oliverkoo#olivers-MacBook-Pro ~/Desktop/untitled folder $ java Main
Please type some words, then press enter:
my name is oliver
number of word is 4

The method call count.length() is returning the length of each word because the loop is assigning each word to variable count. (This variable name is very confusing.)
If you want the number of words in the sentence, you need the size of the count_words array, which is count_words.length.

Related

For loop skipping index 0 when user's input and print in Java

For example, I entered a size of 3 Students. It skips index 0 in the console also in printing.
Please refer to this image, I have a sample size of 3 students and its output.
I don't have the slightest idea of why it skips index 0? Thanks for the help!
import java.util.Arrays;
import java.util.Scanner;
class string{
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.print("Enter Student Size: ");
int studentSize = console.nextInt();
String [] arrName = new String[studentSize];
for (int i=0; i<arrName.length; i++){
System.out.print("Enter student name: ");
String nameString = console.nextLine();
arrName[i] = nameString;
}
System.out.print(Arrays.toString(arrName));
//Closing Braces for Class and Main
}
}
The problem is with the console.nextInt(), this function only reads the int value.So In your code inside the loop console.nextLine() first time skip the getting input.just puting console.nextLine()afterconsole.nextInt()
you can solve the problem.
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.print("Enter Student Size: ");
int studentSize = console.nextInt();
console.nextLine();
String [] arrName = new String[studentSize];
for (int i=0; i<arrName.length; i++){
System.out.print("Enter student name: ");
String nameString = console.nextLine();
arrName[i] = nameString;
}
System.out.print(Arrays.toString(arrName));
//Closing Braces for Class and Main
}
The reason for this skip is due to the different behavior of the console.nextInt() and console.nextLine() as:
console.nextInt() reads the integer value entered, regardless of whether you hit the enter for new-line or not.
console.nextLine() reads the whole line, but as you previously hit thee enter when you give the size of Array.
3 was accepted as the size of the Array and when you hit enter it was accepted as the first value for you array which is a blank space or I can say it is referred as "".
Following are the two resolution for this:
Either put a console.nextLine() call after each console.nextInt() to consume rest of that line including newline
Or, even better, read the input through Scanner.nextLine and convert your input to the proper format you need. you may convert to an integer using int studentSize = Integer.parseInt(console.nextLine()) method. (Surround it with try-catch)

split(" ") user text string and printing the first letter in each approved word

The user is supposed to enter multiple words (without regards to lower/uppercase) with space inbetween, this text will then be translated into initials without any spaces included. However, I only want the initials of the words that I approve of, if anything but those words, the printout will instead say "?" instead of printing the first alphabet of a word. E.q: "hello hello hello" will come out as: "HHH", but "hello hi hello" or "hello . hello" will instead result in "H?H".
I've managed to make it print out the initials without the spaces. But I can't figure out how to add a condition where the program would first check whether the input contains unapproved words or signs/symbol or not in order to replace that unapproved or non-word with a question mark instead of just going ahead and printing the initial/sign. I've tried placing the for-loop inside an if-else-loop and using a switch()-loop but they won't interact with the for-loop correctly.
public static void main (String []args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter your words: ");
String input = keyboard.nextLine().toUpperCase();
String str = input;
String[] parts = str.split(" ");
System.out.print("The initials: ");
for (String i : parts) {
System.out.print(i.charAt(0));
}
}
So what happens right now is that regardless what words the user enter, the initials of each word or symbol/sign will be printed regardless.
You should create a set of approved words and then check whether each word, entered by the user, makes part of this set.
Something like this:
...
Set<String> approved_words = new TreeSet<>();
approved_words.add("HELLO");
approved_words.add("GOODBYE");
...
for (String i : parts) {
if (approved_words.contains(i))
System.out.print(i.charAt(0));
else
System.out.print('?');
}
System.out.println();
Small suggestion:
You may want to allow the user to enter multiple spaces between the words.
In that case, split the words like this: str.split(" +")
If you want to filter against words you dislike, you will have to code it.
Like the example with "hi":
public static void main (String []args) {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter your words: ");
String input = keyboard.nextLine().toUpperCase();
String str = input;
String[] parts = str.split(" ");
System.out.print("The initials: ");
for (String i : parts) {
if(!"HI".equals(i))
System.out.print(i.charAt(0));
else
System.out.print("?");
}
}
Of course in real life you want such comparison on a collection, preferably something fast, like a HashSet:
public static void main (String []args) {
Set<String> bannedWords=new HashSet<String>(Arrays.asList("HI","."));
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter your words: ");
String input = keyboard.nextLine().toUpperCase();
String str = input;
String[] parts = str.split(" ");
System.out.print("The initials: ");
for (String i : parts) {
if(!bannerWords.contains(i))
System.out.print(i.charAt(0));
else
System.out.print("?");
}
}
(this one bans 'hi' and '.')
You could create a simple Set containing all the words that you accept. Then in your for loop, for every String i you check if the set contains ``i```. If this is true, you print out i.charAt(0). Otherwise you print out "?".
I could provide code for this if necessary, but it's always good to figure it out yourself ;)
Supposed you provide unapproved words as input arguments
public static void main (String []args) {
Set<String> unapprovedSet = new HashSet<>(Arrays.asList(args));
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your words: ");
String input = keyboard.nextLine().toUpperCase();
String[] parts = input.split(" ");
System.out.print("The initials: ");
for (String i : parts) {
if (unapprovedSet.contains(i)) {
System.out.print("?");
} else {
System.out.print(i.charAt(0));
}
}
}

How to declare string array of unknown size as input then tokenize

I am trying to declare an array of String which will consist of the input, that is unknown (it depends what text user inputs). I set up a Scanner to read the input then declared a String[] to store the input, and a while loop to go through each line of text and delimit on " ". My question is: How do I set up the array of String to contain the input so I can break it apart into words in the while loop (I can't use ArrayList)
public class Scramble {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] words;
String line;
while (in.hasNext()) {
words.add(line.trim());
}
}
}
read the whole sentence and do it like this
Scanner in = new Scanner(System.in);
String sentence = in.nextLine ();
String[] words = sentence.split(" ");
System.out.println(Arrays.toString(words));
Input
this is a test
Output
[this, is, a, test]

Initialize String array with Scanner [duplicate]

What is the main difference between next() and nextLine()?
My main goal is to read the all text using a Scanner which may be "connected" to any source (file for example).
Which one should I choose and why?
I always prefer to read input using nextLine() and then parse the string.
Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line.
A useful tool for parsing data from nextLine() would be str.split("\\s+").
String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces
For more information regarding the Scanner class or String class refer to the following links.
Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
next() can read the input only till the space. It can't read two words separated by a space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
For reading the entire line you can use nextLine().
From JavaDoc:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
next(): Finds and returns the next complete token from this scanner.
nextLine(): Advances this scanner past the current line and returns the input that was skipped.
So in case of "small example<eol>text" next() should return "small" and nextLine() should return "small example"
The key point is to find where the method will stop and where the cursor will be after calling the methods.
All methods will read information which does not include whitespace between the cursor position and the next default delimiters(whitespace, tab, \n--created by pressing Enter). The cursor stops before the delimiters except for nextLine(), which reads information (including whitespace created by delimiters) between the cursor position and \n, and the cursor stops behind \n.
For example, consider the following illustration:
|23_24_25_26_27\n
| -> the current cursor position
_ -> whitespace
stream -> Bold (the information got by the calling method)
See what happens when you call these methods:
nextInt()
read 23|_24_25_26_27\n
nextDouble()
read 23_24|_25_26_27\n
next()
read 23_24_25|_26_27\n
nextLine()
read 23_24_25_26_27\n|
After this, the method should be called depending on your requirement.
What I have noticed apart from next() scans only upto space where as nextLine() scans the entire line is that next waits till it gets a complete token where as nextLine() does not wait for complete token, when ever '\n' is obtained(i.e when you press enter key) the scanner cursor moves to the next line and returns the previous line skipped. It does not check for the whether you have given complete input or not, even it will take an empty string where as next() does not take empty string
public class ScannerTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cases = sc.nextInt();
String []str = new String[cases];
for(int i=0;i<cases;i++){
str[i]=sc.next();
}
}
}
Try this program by changing the next() and nextLine() in for loop, go on pressing '\n' that is enter key without any input, you can find that using nextLine() method it terminates after pressing given number of cases where as next() doesnot terminate untill you provide and input to it for the given number of cases.
next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
import java.util.Scanner;
public class temp
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter string for c");
String c=sc.next();
System.out.println("c is "+c);
System.out.println("enter string for d");
String d=sc.next();
System.out.println("d is "+d);
}
}
Output:
enter string for c
abc def
c is abc
enter string for d
d is def
If you use nextLine() instead of next() then
Output:
enter string for c
ABC DEF
c is ABC DEF
enter string for d
GHI
d is GHI
In short: if you are inputting a string array of length t, then Scanner#nextLine() expects t lines, each entry in the string array is differentiated from the other by enter key.And Scanner#next() will keep taking inputs till you press enter but stores string(word) inside the array, which is separated by whitespace.
Lets have a look at following snippet of code
Scanner in = new Scanner(System.in);
int t = in.nextInt();
String[] s = new String[t];
for (int i = 0; i < t; i++) {
s[i] = in.next();
}
when I run above snippet of code in my IDE (lets say for string length 2),it does not matter whether I enter my string as
Input as :- abcd abcd or
Input as :-
abcd
abcd
Output will be like
abcd
abcd
But if in same code we replace next() method by nextLine()
Scanner in = new Scanner(System.in);
int t = in.nextInt();
String[] s = new String[t];
for (int i = 0; i < t; i++) {
s[i] = in.nextLine();
}
Then if you enter input on prompt as -
abcd abcd
Output is :-
abcd abcd
and if you enter the input on prompt as
abcd (and if you press enter to enter next abcd in another line, the input prompt will just exit and you will get the output)
Output is:-
abcd
From javadocs
next() Returns the next token if it matches the pattern constructed from the specified string.
nextLine() Advances this scanner past the current line and returns the input that was skipped.
Which one you choose depends which suits your needs best. If it were me reading a whole file I would go for nextLine until I had all the file.
From the documentation for Scanner:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
From the documentation for next():
A complete token is preceded and followed by input that matches the delimiter pattern.
Just for another example of Scanner.next() and nextLine() is that like below :
nextLine() does not let user type while next() makes Scanner wait and read the input.
Scanner sc = new Scanner(System.in);
do {
System.out.println("The values on dice are :");
for(int i = 0; i < n; i++) {
System.out.println(ran.nextInt(6) + 1);
}
System.out.println("Continue : yes or no");
} while(sc.next().equals("yes"));
// while(sc.nextLine().equals("yes"));
Both functions are used to move to the next Scanner token.
The difference lies in how the scanner token is generated
next() generates scanner tokens using delimiter as White Space
nextLine() generates scanner tokens using delimiter as '\n' (i.e Enter
key presses)
A scanner breaks its input into tokens using a delimiter pattern, which is by default known the Whitespaces.
Next() uses to read a single word and when it gets a white space,it stops reading and the cursor back to its original position.
NextLine() while this one reads a whole word even when it meets a whitespace.the cursor stops when it finished reading and cursor backs to the end of the line.
so u don't need to use a delimeter when you want to read a full word as a sentence.you just need to use NextLine().
public static void main(String[] args) {
// TODO code application logic here
String str;
Scanner input = new Scanner( System.in );
str=input.nextLine();
System.out.println(str);
}
I also got a problem concerning a delimiter.
the question was all about inputs of
enter your name.
enter your age.
enter your email.
enter your address.
The problem
I finished successfully with name, age, and email.
When I came up with the address of two words having a whitespace (Harnet street) I just got the first one "harnet".
The solution
I used the delimiter for my scanner and went out successful.
Example
public static void main (String args[]){
//Initialize the Scanner this way so that it delimits input using a new line character.
Scanner s = new Scanner(System.in).useDelimiter("\n");
System.out.println("Enter Your Name: ");
String name = s.next();
System.out.println("Enter Your Age: ");
int age = s.nextInt();
System.out.println("Enter Your E-mail: ");
String email = s.next();
System.out.println("Enter Your Address: ");
String address = s.next();
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.println("E-mail: "+email);
System.out.println("Address: "+address);
}
The basic difference is next() is used for gettting the input till the delimiter is encountered(By default it is whitespace,but you can also change it) and return the token which you have entered.The cursor then remains on the Same line.Whereas in nextLine() it scans the input till we hit enter button and return the whole thing and places the cursor in the next line.
**
Scanner sc=new Scanner(System.in);
String s[]=new String[2];
for(int i=0;i<2;i++){
s[i]=sc.next();
}
for(int j=0;j<2;j++)
{
System.out.println("The string at position "+j+ " is "+s[j]);
}
**
Try running this code by giving Input as "Hello World".The scanner reads the input till 'o' and then a delimiter occurs.so s[0] will be "Hello" and cursor will be pointing to the next position after delimiter(that is 'W' in our case),and when s[1] is read it scans the "World" and return it to s[1] as the next complete token(by definition of Scanner).If we use nextLine() instead,it will read the "Hello World" fully and also more till we hit the enter button and store it in s[0].
We may give another string also by using nextLine(). I recommend you to try using this example and more and ask for any clarification.
The difference can be very clear with the code below and its output.
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
List<String> arrayList2 = new ArrayList<>();
Scanner input = new Scanner(System.in);
String product = input.next();
while(!product.equalsIgnoreCase("q")) {
arrayList.add(product);
product = input.next();
}
System.out.println("You wrote the following products \n");
for (String naam : arrayList) {
System.out.println(naam);
}
product = input.nextLine();
System.out.println("Enter a product");
while (!product.equalsIgnoreCase("q")) {
arrayList2.add(product);
System.out.println("Enter a product");
product = input.nextLine();
}
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println("You wrote the following products \n");
for (String naam : arrayList2) {
System.out.println(naam);
}
}
Output:
Enter a product
aaa aaa
Enter a product
Enter a product
bb
Enter a product
ccc cccc ccccc
Enter a product
Enter a product
Enter a product
q
You wrote the following products
aaa
aaa
bb
ccc
cccc
ccccc
Enter a product
Enter a product
aaaa aaaa aaaa
Enter a product
bb
Enter a product
q
You wrote the following products
aaaa aaaa aaaa
bb
Quite clear that the default delimiter space is adding the products separated by space to the list when next is used, so each time space separated strings are entered on a line, they are different strings.
With nextLine, space has no significance and the whole line is one string.

Prompt user for inputs and then sort alphabetically?

I'm currently in my first semester. I have a project requiring me to build a program having a user input 3 words, sort them alphabetically and output the middle word. I have done some searching and seem to only come back with results for sorting 2 words. I so far have code to get the user input but I am completely lost as to how to sort them alphabetically and how to prompt the user to enter the three strings. Please be patient with me as I am very new to programming. If anyone can provide me with any advice or the best or easiest way to go about sorting these I would greatly appreciate it
import java.util.Scanner; //The Scanner is in the java.util package.
public class MiddleString {
public static void main(String [] args){
Scanner input = new Scanner(System.in); //Create a Scanner object.
String str1, str2, str3;
System.out.println("Please enter one word words : "); //Prompt user to enter one word
str1=input.next(); //Sets "str1" = to first word.
str2=input.next(); //Sets "str2" = to second word.
str3=input.next(); //Sets "str3" = to third word.
System.out.println("The middle word is " ); // Outputs the middle word in alphabetical order.
}
}
Please help!
Try something like this:
String [] strings;
int i = 0;
System.out.println("Please enter one word words : "); //Prompt user to enter one word
strings[i++] = input.next(); //Sets "str1" = to first word.
strings[i++] = input.next(); //Sets "str2" = to second word.
strings[i++] = input.next(); //Sets "str3" = to third word.
Arrays.sort(strings);
System.out.println("The middle word is " + strings[strings.length / 2]);
You can sort (compare) only two words at a time, yes, but that is the basis for the whole sorting algorithm. You'll need to loop through your array of words and compare each word with each other word.
String[2] words = new String[2];
words[0] = input.next();
words[1] = input.next();
words[2] = input.next();
String[2] sortedWords = new String[2];
for (String word: words){ // outer loop
for (String word: words){ // inner loop to compare each word with each other
// logic to do the comparisons and sorting goes here
}
}
System.out.println(sortedWords[1]);
Of course I've left out the fun part for you, but that should get you started.

Categories

Resources