Scanner Class to create tokens of an input file - java

I have written the following code in java to open another .java file and create tokens (using scanner class)
import java.io.FileReader;
import java.util.Scanner;
public class scanner1 {
public static void main(String[] arg) throws Exception
{
FileReader fin = new FileReader("mysourcefile.java");
Scanner scan=new Scanner(fin);
scan.useDelimiter(" "); // the delimiter pattern required
while(scan.hasNext()) {
System.out.println(scan.next());
}
}
}
My task is to create the tokens of complete Java file and the delimiters should be treated as the tokens also.
So what should be the delimiter pattern to use here in scan.useDelimiter("")?
UPDATE:
The above task was completed using the stringtokenizer. But I don't know the exact pattern of the delimiter to create tokens for a .java file. Can I have an answer about what the delimiter pattern to use in the given case ?
import java.util.*;
public class sstring2
{
public static void main(String[] args)
{
String s = "a=(b+c); String st='hello! my dear';";
StringTokenizer st = new StringTokenizer(s, "[ =+';().*{}[],!##$%^&/]", true);
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}
This code gives the correct results.

Take a look at the java.lang.instrument packagae. It provides some nice APIs to transform an already loaded class. The retransformation allows to change method bodies as in your case. Here's the link

it may be any character on which you want to terminate the input.

Related

Do I have to assign the data from sc.nextLine() to a variable before I use it?

So far, every time I have used a scanner object I have assigned the input to a new string variable like:
String word = reader.nextLine();
and then if I want to use the input in an if statement I would write:
if(word.isEmpty()){}
but this seems almost like an extra step instead of just doing:
if(reader.nextLine().isEmpty()){}
however, when I try this I usually get some kind of problem in my program function. Is there a way to do this by skipping the String that I will never use again?
This is the code that I am trying to use without the String objects:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class WordsInReverseOrder {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> words = new ArrayList<String>();
while(true){
System.out.println("Type a word: ");
if(reader.nextLine().isEmpty()){
Collections.reverse(words);
for(String word1 : words){
System.out.println(word1);
}
break;
}
else{
words.add(reader.nextLine());
}
}
}
}
If you need to do something with the scanned word and want to check isEmpty() than you need a variable to access the word twice.
So, if you do more than one thing, you need a variable. If you do just one thing, you can 'inline' the variable.
The answer to your question is 'Yes'. When you do not need the content of the first word / line, the you can 'inline' your variable, which means that there is no need for a variable.

Any ways to give string input for the Stanford-parser DocumentPreprocessor class?

I'm trying to use Stanford NLP Parser which
parses document into set of sentences.
It reads filename which contains multiple sentences
as an argument of the class, DocumentPreprocessor
and then outputs parsed sentences.
However, I want to give inputs string by string which contains set of sentences but whole file that contains bunch of sentences.
Any ways I can do that?
Current program looks like below (https://nlp.stanford.edu/software/tokenizer.shtml)
public class TokenizerDemo {
public static void main(String[] args) throws IOException {
for (String arg : args) {
// option #1: By sentence.
DocumentPreprocessor dp = new DocumentPreprocessor(arg);
for (List<HasWord> sentence : dp) {
System.out.println(sentence);
}
}
}
}

Hello, I need help on creating a Star Wars name generator using specific instructions

I'm struggling with a specific method which takes in a String parameter. The promptString method will print its parameter to the user as a prompt, and then return a String that is the result of reading the console via the nextLine() method. For this program you will use nextLine() exclusively.
I've prompted the user with a question using a parameter, and then used nextLine to read the string but after that I am a bit lost. How can I get the method to print to the console?
import java.util.*;
public class StarWarsName{
public static void main (String [] args) {
promptString("Enter your first name: ");
}
public static String promptString (String n) {
Scanner console = new Scanner(System.in);
String first = console.nextline();
return first.trim();
}
}
I think you are over-thinking this thing. Just print it to the console.
public static void main(String[]args){
String result = promptString("Enter your first name: ");
System.out.println(result);
}

creating a new line for string

made a program that counts and outputs users based on user input. I want the program to display the names one below the other with the line break but stuck on how to. the code is below:
package uk.ac.reading.cs2ja16.Glen.Stringtest;
import java.util.Arrays;
import java.util.Scanner;
public class stringnames {
public static String[] countNames (String names) {
// Create Scanner object
#SuppressWarnings("resource")
Scanner names1 =new Scanner(System.in);
// Read a string
String read= names1.nextLine();
// Split string with space
String numPeople[]=read.trim().split(" ");
System.out.println("The Number of names inputted is: "+ numPeople.length);
return numPeople;
}
public static void main(String[ ] args){
System.out.println("Enter the amount of names you want(make sure you make space for each name):\n");
String[] namesout = countNames(null);
System.out.println(Arrays.toString(namesout));
}
}
First of all, the countNames method does not need a parameter, so delete that String names thingy in the method declaration. And delete the word null in your method call.
Now, you can either use a for loop or use one of the methods in the new Stream API if you're using Java 8.
I'll show you both ways.
For loop:
for (String name: namesout) {
System.out.println(name);
}
the println method automatically adds a new line character at the end of the string that you want to print.
Stream API:
Arrays.stream(namesout).forEach(System.out::println);

Java program help

I made a class Anagrams that writes the permutations of the words in a sentence and when I run the compiled program as java Anagrams "sentence1" "sentence2"... It should generate the permutations of each of the sentences. How would I get it to do that?
import java.io.*;
import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;
public class Anagrams
{
...
public static void main(String args[])
{
String phrase1 = "";
System.out.println("Enter a sentence.");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
try { phrase1 = input.readLine(); }
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println();
new Anagrams(phrase1).printPerms();
}
}
this is what i have so far i just need it to run on "sentence1" "sentence2" ...
when i type the command java Anagrams "sentece1" "sentence2" ...
ive already compiled it using javac Anagrams.java
From your comment I think your only question is how to use command line arguments to solve the task:
Your main method is looking like this:
public static void main(String args[])
but should look like this
public static void main(String[] args)
You see that there is an array of strings that holds the command line arguments. So if your executing your code with
java Anagrams sentence1 sentence2
Then the array has the length 2. In the first place (args[0]) there is the value sentence1 and in the second place (args[1]) there is the value sentence2.
An example code that prints all your command line arguments looks like this:
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
Now you should be able to use your anagram algorithm for each command line argument.
Here's a simple example of getting the arguments from the command line.
Bear in mind that this is open to "IndexOutOfBoundsException"s if you don't provide enough arguments, so make sure to check that in your code!
class ArgsExample {
public static void main(String[] args) {
System.out.println(args[0]);
System.out.println(args[1]);
}
}
C:\Documents and Settings\glow\My Documents>javac ArgsExample.java
C:\Documents and Settings\glow\My Documents>java ArgsExample "This is one" "This
is two"
This is one
This is two
C:\Documents and Settings\glow\My Documents>
Varargs would allow you to use an indeterminate number of strings in a method signature, if that's what you're looking for. Otherwise, Roflcoptr is right if it's a question of passing arguments into main.

Categories