Hello there

I have a small question.
I've been looking on the web for it but didn';t come down with an answer.

As far as i've read we can get user input from the console via Scanner

Scanner asdf = new Scanner(System.in);

What if we wanted to analyze this asdf ?

Practially i want to tokenize it.
1) Find out how many words does it have
2) Search into the word nr2 like it was an array { If asdf[2] = "AND" ]

Any help ?

thanks in adnvance

A Scanner can be used to get keyboard input from the user. I think you want to analyze, tokenize, etc. the user input, not the Scanner object itself. Try this:

Scanner in = new Scanner(System.in);     // better name than asdf
System.out.println("Enter some text.");  // good idea to prompt for input before reading from keyboard
String text = in.next();  // this line will cause your program to wait until the user enters something
// now you can analyze or tokenize the String text entered by the user

Edited 6 Years Ago by kramerd: n/a

The following code demonstrates how to analyze a keyboard input in terms of tokens. The client may input no more than 100 words with the final string “end” (excluded). These words are simultaneously stored in the String array s, through which one may do search for a specific word.

import java.util.*;
public class Tokenizer0 {	
	public static void main(String args[]){
		Scanner asdf = new Scanner(System.in); // obtain an instance of Scanner
		String s []= new String[100]; // declare a string array with the size of 100 to accommodate the input words via asdf
		int counter = 0; // counter counts the number of input words
		
		while(asdf.hasNext()){ //returns true if asdf has next token
		s[counter++]=asdf.next(); // assign the next token to the string array
		if (s[counter-1].compareTo("end")==0) break; // check the input word. if the input is "end", then stop the while loop
		}
		System.out.println("Number of Words:" + (counter-1)); // print out the total number of input words
		for (int i=0; i<counter-1; i++) // print out the input words
		System.out.println(s[i]);
	}
}

Edited 6 Years Ago by tong1: n/a

Comments
You are counting the number of lines, not words

Great.

Problem Solved.
Another question is :

If i want to use as last input the character (")
How could i write this ?
I am facing some errors when entering compareTo(" " ")

Edited 6 Years Ago by hatux: n/a

When you want to refer to a special character in Java (one that has some other meaning) you need to use an escape character to tell Java not to interpret its usual other meaning. The escape character is a backslash. \" tells Java not to interpret the quote character in the usual way. So the string "\"" is interpreted as the character " inside a string.

This article has been dead for over six months. Start a new discussion instead.