Method is illegal start of expression - java

Below is some code that tries to find the first word above a certain amount of characters.
public class FirstMatch {
public static void main(String[] args) throws java.io.FileNotFoundException {
Scanner in = new Scanner(new FileReader("aliceInWonderland.txt"));
String longWord = "";
boolean found = false;
public void threshold (int Threshold) {
while (in.hasNext() && !found) {
String word = in.next();
if (word.length() > Threshold) {
longWord = word;
found = true;
}
}
System.out.println("The first long word is: " + longWord);
}
}
}
(In the above code I didn't copy in all the import statements)
For some reason for my threshold method it returns illegal start of expression. I think it is a stupid mistake but can't figure out what's wrong...

You should declare your threshold method out of the main method.
A method can only be created at class level, and not inside another method.
import java.io.FileReader;
import java.util.Scanner;
public class FirstMatch {
public static void main(String[] args) throws java.io.FileNotFoundException {
Scanner in = new Scanner(new FileReader("aliceInWonderland.txt"));
threshold(in, 10);
}
public static void threshold(Scanner in, int threshold) {
String longWord = "";
boolean found = false;
while (in.hasNext() && !found) {
String word = in.next();
if (word.length() > threshold) {
longWord = word;
found = true;
}
}
System.out.println("The first long word is: " + longWord);
}
}

Related

Recursion Troubling me

I'm new to all this so.. thanks
Just curious why this won't work.
Its telling me that public int sumFirst(int n) is an illegal start to an expression.
package program8;
public class Program8 {
public static void main(String[] args) {
public int sumFirst(int n)
{
Scanner input = new Scanner(System.in);
n = input.nextInt();
if (n == 0)
return 0;
else
return sumFirst(n-1) + sumFirst(n-2);
}
}
For one, you are trying to define a method inside your main method which will not work; Methods can only be defined at a class level.
Secondly, n = input.nextInt(); inside the sumFirst method will be executed for each recursion, which is probably not what you want.
Try this instead:
public class Program8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(sumFirst(input.nextInt()));
}
public int sumFirst(int n) {
if (n == 0) {
return 0;
} else {
return sumFirst(n-1) + sumFirst(n-2);
}
}
}

subroutine taking an array as a parameter in Java

In the following program, the user is supposed to enter a String (name of a City) and the program should return the index of the corresponding City in the array.
But I get an error, in the subroutine indexCities the following message:
"nameCity cannot be resolved".
I guess it is a problem of variable scoping but I don't figure out how I should do.
Thanks for your help.
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(cities);
}
public static int indexCities(String cities[]) {
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
}
nameCity is a local variable inside your main method. You can not access it outside the method.
One option for you is to pass the nameCity also as an argument in indexCities method. Also return type of your indexCities method should be void since you are not returning anything.
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(cities, nameCity);
}
public static void indexCities(String cities[], String nameCity){
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
You could do it in this way:
public static void main(String[] args) {
String cities[] = { "Vierzon", "Salbris", "Nouans", "LB", "LFSA", "Orleans" };
int index = indexCities(cities, "Vierzon");
System.out.println("Index of city Vierzon is: " + index);
}
public static int indexCities(String cities[], String cityName) {
List<String> cityList = Arrays.asList(cities);
return cityList.indexOf(name);
}
Scope of variable nameCity is limited to main function. You can not access it outside of main function.
The variable is out of scope when you try to use it inside the method indexCities. One solution is making the variable nameCity an instance variable by moving it's definition out of the main method, but your code can be improved in several ways too. Check some option below:
This will print the index of the city you're looking for inside the array:
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(nameCity, cities);
}
public static void indexCities(String copyOfNameCity, String cities[]){
for (int i = 0; i < cities.length; i++) {
if(copyOfNameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
}
You you can improve it by making the method return a value. Like this:
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
int cityIndex = indexCities(nameCity, cities);
System.out.println(cityIndex == -1 ? "City not found" : "City found in index " + cityIndex);
}
public static int indexCities(String nameCity, String cities[]){
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
return i;
}
}
return -1;
}
}
Another way is:
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
String cities[] = {"Vierzon", "Salbris", "Nouans", "LB", "LFSA", "Orleans"};
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of city to be searched -> ");
String nameCity = input.nextLine();
int cityIndex = indexCities(nameCity, cities);
System.out.println(cityIndex == -1 ? "City not found" : "Found at position " + cityIndex);
input.close();
}
public static int indexCities(String cityName, String cities[]) {
List<String> cityList = Arrays.asList(cities);
return cityList.indexOf(cityName);
}
}

How would I search for a user determined word and count the occurrences in a text file using java?

I've gotten to a point where I can read the file and output the actual text in the file but i'm not quite sure on how to proceed with searching for a specific word and displaying the word count.
There are many ways. If you're reading the file line-by-line, you can using the method indexOf on the String class to search each line for the text. You'd need to call it repeatedly to move through the line looking for additional occurrences.
See documentation on indexOf at:
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int)
As I understand your question, if you are reading the text line after line you can use recursivity to count how many occurences of the word appear in the same line:
The following method counts how many times a word appears in the same line
private static int numberOfLineOccurences;
public static int countNumberOfTimesInALine(String line, String word) {
if (line.indexOf(word) == -1) {
return numberOfLineOccurences;
} else {
numberOfLineOccurences++;
if (line.indexOf(word) + word.length() > line.length() -1 ) {
return numberOfLineOccurences;
}
return countNumberOfTimesInALine(
line.substring(line.indexOf(word) + word.length()), word );
}
}
In order to keep track of the first occurence of my word in my file along with the number of occurence I created a WordInfo class like this:
class WordInfo {
private int firstOccurenceLineNumber;
private int firstOccurenceColumnNumber;
private String word;
private int numberOfOccurences;
public String getWord() {
return word;
}
public int getNumberOfOccurences() {
return numberOfOccurences;
}
public WordInfo(String word) {
this.word = word;
}
public void upOccurrence() {
numberOfOccurences++;
}
public void upOccurrence(int numberOfTimes) {
numberOfOccurences+= numberOfTimes;
}
public int getFirstOccurenceLineNumber() {
return firstOccurenceLineNumber;
}
public void setFirstOccurenceLineNumber(int firstOccurenceLineNumber) {
this.firstOccurenceLineNumber = firstOccurenceLineNumber;
}
public int getFirstOccurenceColumnNumber() {
return firstOccurenceColumnNumber;
}
public void setFirstOccurenceColumnNumber(int firstOccurenceColumnNumber) {
this.firstOccurenceColumnNumber = firstOccurenceColumnNumber;
}
}
Now I can create my searchWord method. I give him the word to look for, the fileName and a WordInfo object to fill as input parameters
public static boolean searchWord(String word, String filePath, WordInfo wInfo) throws IOException {
boolean result = false;
boolean firstOccurenceFound = false;
int lineNumber = 0;
BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)));
String line = null;
while ( (line = reader.readLine()) != null) {
lineNumber++;
numberOfLineOccurences= 0;
if (line.indexOf(word) != -1) {
if (!result) {
result = true;
}
if (!firstOccurenceFound) {
firstOccurenceFound = true;
wInfo.setFirstOccurenceLineNumber(lineNumber);
wInfo.setFirstOccurenceColumnNumber(line.indexOf(word) + 1);
}
wInfo.upOccurrence(countNumberOfTimesInALine(line, word));
}
}
reader.close();
return result;
}
Here is an illustration and the result below
I have the following content in a file called DemoFile.txt
And I test the code using the following main method (I am looking for the word conceptfor example):
public static void main(String[] args) throws IOException {
WordInfo wInfo = new WordInfo("concept");
if ( searchWord("concept", FILE_PATH, wInfo)) {
System.out.println("Searching for " + wInfo.getWord());
System.out.println("First line where found : " + wInfo.getFirstOccurenceLineNumber());
System.out.println("First column found: " + wInfo.getFirstOccurenceColumnNumber());
System.out.println("Number of occurrences " + wInfo.getNumberOfOccurences());
}
}
And I obtain the following results:

Java error method is undefined for the type Echo

I am getting an error on the 11th line of this code "e.results();"
Here is my driver class
import java.util.Scanner;
import java.io.*;
public class LineScrabbleDriver {
public static void main(String args[]) throws IOException {
String fileName;
Scanner nameReader = new Scanner(System.in);
System.out.println("Enter a file name");
fileName = nameReader.nextLine();
Echo e = new Echo(fileName);
e.readLines();
e.results();
}
}
This is the extended class of Echo
import java.io.*;
public class LineScrabble extends Echo{
double max = 0.0;
String bestWord = "";
int lineNumer = 0;
public LineScrabble(String f) throws IOException {
super(f);
}
//scrabbles
int[] scrabbles = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
//process the given line
public void processLine(String s) {
s.toLowerCase();
int score = 0;
for(int i = 0; i<s.length(); i++){
char ch = s.charAt(i);
if(Character.isLetter(ch)){
int pos = ch - 'a';
score += scrabbles[pos];
}
}
if(score > max){
max = score;
bestWord = s;
}
}
//displays the winner and score
public void results() {
System.out.println("Winner: " + bestWord);
System.out.println("score: " + max/bestWord.length());
}
}
Here is the Echo class
import java.util.Scanner;
import java.io.*;
public class Echo{
String fileName; // external file name
Scanner scan; // Scanner object for reading from external file
public Echo(String f) throws IOException
{
fileName = f;
scan = new Scanner(new FileReader(fileName));
}
public void readLines(){ // reads lines, hands each to processLine
while(scan.hasNext()){
processLine(scan.nextLine());
}
scan.close();
}
public void processLine(String line){ // does the real processing work
System.out.println(line);
}
}
I'm not quite sure why it is giving me a undefined type error. I'm new to java programming. please help!
Because you are using the original Echo and not a LineScrabble, I think you wanted something like -
// Echo e = new Echo(fileName); //
LineScrabble e = new LineScrabble(fileName);
e.readLines();
e.results(); // <-- Echo does not have results() you could add it there, or
// use LineScrabble.

Identifying positive and negative words in text

I am trying to work out how to scan a text file of a conversation find how many positive words and negative words there are. The positive and negative words are contained within two separate text files which are used to 'scan' the conversation text file.
After it finds the number of positive and negative words I am trying to get it to tally each up and then tell me if there are more positive or negative words found.
I have the code below so far, it only gives me a count on the positive words. I am not looking at something like NLP at this stage just something on a much more basic level.
I think I have the second part looking for the negative words in the wrong location. And I think I need to use a boolean to tell me if there are more positive or negative words found, but I can't work out how to do it.
I am pretty stuck as I am new to Java, and programing in general.
Any help would be greatly appreciated.
package omgilisearch;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class SentimentTest {
public static void main(String[] args) throws Exception {
printAllCounts(
readWordFile("ConversationTest.txt", loadKeywords("PositiveWords.txt")));
}
public static void main1(String[] args) throws Exception {
printAllCounts(
readWordFile("ConversationTest.txt", loadKeywords("NegativeWords.txt")));
}
private static Map<String, Integer> readWordFile(
String fname, Set<String> keywords) throws FileNotFoundException
{
final Map<String, Integer> frequencyData = new TreeMap<String, Integer>();
for (Scanner wordFile = new Scanner(new FileReader(fname));
wordFile.hasNext();)
{
final String word = wordFile.next();
if (keywords.contains(word))
frequencyData.put(word, getCount(word, frequencyData) + 1);
}
return frequencyData;
}
private static void printAllCounts(Map<String, Integer> frequencyData) {
System.out.println("-----------------------------------------------");
System.out.println(" Occurrences Word");
for(Map.Entry<String, Integer> e : frequencyData.entrySet())
System.out.printf("%15d %s\n", e.getValue(), e.getKey());
System.out.println("-----------------------------------------------");
}
private static int getCount(String word, Map<String, Integer> frequencyData) {
return frequencyData.containsKey(word)? frequencyData.get(word) : 0;
}
private static Set<String> loadKeywords(String fname)
throws FileNotFoundException
{
final Set<String> result = new HashSet<String>();
for (Scanner s = new Scanner(new FileReader(fname)); s.hasNext();)
result.add(s.next());
return result;
}
}
You would have to have some array of so called "bad" words (wich are hard coded) and then iterate through the whole text file and compare every word in the array with the word you currently inspecting. If the word matches with one of the words in the array, then increase some variable that is holding the amount of badwords eg. badWords++;. I believe this approach should work.
package omgilisearch;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class SentimentTest {
public static void main(String[] args) throws Exception {
printAllCounts(
readWordFile("ConversationTest.txt"));
}
private static Map<String, Integer> readWordFile(String string) {
return null;
}
String[] goodWordsHolder = new String[3];{
goodWordsHolder[0] = "good"; goodWordsHolder[1] = "great";goodWordsHolder[2] = "excellent";
for(int iteration = 0; iteration < goodWordsHolder.length; iteration++) { String currentWordInText;
if(goodWordsHolder[iteration] == currentWordInText) { }// The word is a bad word } }
private static void printAllCounts(Map<String, Integer> frequencyData) {
System.out.println("-----------------------------------------------");
System.out.println(" Occurrences Word");
for(Map.Entry<String, Integer> e : frequencyData.entrySet())
System.out.printf("%15d %s\n", e.getValue(), e.getKey());
System.out.println("-----------------------------------------------");
}
}
package omgilisearch;
import java.io.*;
public class SentimentTest {
public static void main(String[] args) {
String[] lines = new String[0];
String path = "ConversationTest.txt";
BufferedReader br = null;
try {
File file = new File(path);
br = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
String line;
while( (line = br.readLine()) != null ) {
lines = add(line, lines);
}
br.close();
} catch(IOException e) {
System.out.println("read error: " + e.getMessage());
}
print(lines);
}
private static String[] add(String s, String[] array) {
String[] goodWordsHolder = new String[3];{
}goodWordsHolder[0] = "good"; goodWordsHolder[1] = "great";goodWordsHolder[2] = "excellent";
for(int iteration = 0; iteration < goodWordsHolder.length; iteration++) { String currentWordInText = null; if(goodWordsHolder[iteration] == currentWordInText) { }}
return goodWordsHolder; }
private static void print(String[] data) {
for(int i = 0; i < data.length; i++)
System.out.println(data[i]);
}
}
Arrays store multiple items of the same information type eg. String[] badWords;. I believe you should use this, since I'm sure you will have more than 1 bad word that you would like to find in the conversation text, if not, then simple use 1 String eg. String badWord;.
I'm not going to write out all the code that will make it work, I'll just give you an algorithm.
public class test {
// The process of picking out all the good and bad words
public static void main(String[] args) {
// Setting up all the needed variables
// Set up all the good words
String[] goodWordsHolder = new String[2];
goodWordsHolder[0] = "firstGoodWord";
goodWordsHolder[1] = "secondGoodWord";
// Set up all the bad words
String[] badWordsHolder = new String[2];
badWordsHolder[0] = "firstBadWord";
badWordsHolder[1] = "secondBadWord";
// Set up the counters
int amountOfGoodWords = 0;
int amountOfBadWords = 0;
int currentWordInText = 0;
// boolean that will exit the loop
boolean ConversationEnded = false;
while(!ConversationEnded) {
// Compare the currentWord from the conversation with the hard coded words
for(int iteration = 0; iteration < goodWordsHolder.length; iteration++) {
if(goodWordsHolder[iteration] == getWordInText(currentWordInText)) {
amountOfGoodWords++;
}
}
for(int iteration = 0; iteration < badWordsHolder.length; iteration++) {
if(badWordsHolder[iteration] == getWordInText(currentWordInText)) {
amountOfBadWords++;
}
}
// Increase the current word value so the next time we compare the next word in the conversation will be compared
currentWordInText++;
// Check that we haven't reached the end of the conversation
if(endOfTheConversationHasBeenReached()) {
// This will exit the while loop
ConversationEnded = true;
}
}
// Now print all the information to the console
System.out.println("Amount of good Words: " + amountOfGoodWords);
System.out.println("Amount of bad Words: " + amountOfBadWords);
if(amountOfGoodWords > amountOfBadWords) {
System.out.println("There are more good words than bad words.");
}
else {
System.out.println("There are more bad words than good words.");
}
}
// The method(s) you'll have to code out yourself. I suggest you read up on the web and so on to assist you with this.
private static String getWordInText(int currentWordInText) {
// TODO Auto-generated method stub
return null;
}
private static boolean endOfTheConversationHasBeenReached() {
// TODO Auto-generated method stub
return false;
}
}
Excuse me if there are any logical errors. The code hasn't been debugged yet. ;) Hopefully this will guide you into the right direction.

Categories