I am writing a game that revolves around guessing what words in other languages mean. For example, guessing what "hola" means in English. For this game, I am creating a scoring system that uses the frequency of the word (from Google N Gram) being guessed to assign points. Basically, less times showing up = more points. However, when trying to send over the Java String that holds the word to R, I came to the realization that I have no idea what to do.
So far I have experimented with rJava to send over the word, but I am having difficulty making it work. I would greatly appreciate if someone who has experience with R could help me with my problem.
Java Class that generates word:
import java.util.Scanner;
import java.util.Random;
import java.io.File;
import java.io.IOException;
//this program gathers the words to be translated
//for game 1
public class dictionary {
private String line;
public dictionary() {
this.line = "";
}
public dictionary (String line) {
//getting word
try {
this.line = line;
Random random = new Random();
Scanner in = new Scanner (System.in);
int count = 0;
int rand = 1 + random.nextInt(8110);
//read file name from standard input
File file = new File("words.txt");
//overwrite scanner to read file
in = new Scanner(file);
while (in.hasNextLine() && count != rand) {
this.line = in.nextLine();
count = count + 1;
}
in.close();
}
catch(IOException e) {
System.out.println("File does not exist.");
}
}
public String getLine() {
return this.line;
}
}
R code that I came up with. Goal is to ingest the word from Java word (line):
library("ngramr")
library("rJava")
.jinit(parameters = getOption("java.parameters")
.jcall("java/lang/String", returnSig = "S", method = "getLine", evalString = TRUE)
word <- .jclassString("string", "line")
ngram(word, year_start = 1800, smoothing = 0)
Bonus:
Also, if anyone is familiar with Google Ngram and knows how to record the amount of instances of a word in R and send it to Java, please let me know as it is a crucial part of the scoring system.
It’s been a few weeks since I originally posted this question. Since then I have found a solution to both problems listed by using Python sockets instead of R. If anyone is interested in how I did that, it’s in my GitHub. I am going to leave this question here however, in the hopes someone will answer it for others with a similar problem.
Related
I am working on a project that has many different parts and methods. For this one specific part I need to ask the user for the name of a file that contains a set of words, one per line. (see attached) Then I need to compute the average score/sentiment of the word by comparing it to a movieReview file that scores the sentiment of words. (see attached)
[Edit] : I have not gotten my code to take the first line of the wordList file, search through the movieReview file for the word, and find the average score of the word. And after the search is complete, move onto the next word. However, it is printing NaN for the rest of the words after the first, "mechanical"
Example: The first word in the wordList file is "mechanical". Mechanical is found in the movieReview file 6 times and the total score is 4. The average sentiment for the word "mechanical" is .666666666.
How can I make my code so the loop continues and finds the average for every single word and prints it out? Sorry if this sound confusing, let me know if I need to clarify. Also, I am a very beginner coder so please try to not use difficult concepts. (Also, it was said using an array or buffer wasn't needed)
Movie Review File :
http://nifty.stanford.edu/2016/manley-urness-movie-review-sentiment/movieReviews.txt
Content of Word List file(txt):
mechanical
car
soulless
style
family
wonderful
historical
nor
strong
slapstick
complicated
provoking
interest
cast
witty
muted
sentiment
narrative
refreshing
preachy
horrible
resolutely
terrible
dialogue
incoherent
spend
words
moving
devoid
indulgent
dull
value
barely
always
dog
tale
hardly
unfocused
formulaic
eccentric
quirky
unpredictable
tears
writing
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class methodThree {
public static void main (String [] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of the file with words you want to score: ");
String inputFileName = in.next();
File inputFile = new File(inputFileName);
while(!inputFile.exists())
{
System.out.println("Please enter a valid file name:");
inputFile = new File(in.next());
}
Scanner wordFile = new Scanner (inputFile);
File inputMovie = new File("movieReviews.txt");
Scanner movieReview = new Scanner (inputMovie);
String reviewText;
int reviewScore;
while (wordFile.hasNextLine())
{
int count = 0;
double total = 0;
String word = wordFile.nextLine();
while (movieReview.hasNext()) {
reviewScore = movieReview.nextInt();
reviewText = movieReview.nextLine();
if (reviewText.contains(word)) {
count++;
total = total + reviewScore;
}
}
double average = (total / count);
System.out.println (word + " " + average);
}
}
}
So what you basically want to do is repeat this code for every line in the wordfile?
int count = 0;
double total = 0;
String word = wordFile.nextLine();
while(movieReview.hasNext()){
reviewScore = movieReview.nextInt();
reviewText = movieReview.nextLine();
if (reviewText.contains(word)) {
count++;
total = total + reviewScore;
}
}
double average = (total / count);
System.out.println(average);
if thats the case you could surround it with another while loop. The loop must run for every line in wordFile, so it's more or less the same loop as your movieReview.hasNext() loop.
while(wordFile.hasNext()){
int count = 0;
...
}
The loop runs as long as wordFile has another word to score.
As talked about above I am trying to create a balanced delimiter checker in java. I have seen several examples of how to make one all of which were well done, but I have not found any that deal with having to get input from the user with the stack. I have looked into it, but I have not been able to find much with it. Below is what I have so far. I have been working on it but I have done more to confuse myself than anything else. Am I looking at this the right way? Or is there a better route to go about this?
import java.util.Scanner;
import java.util.Stack;
public class BalancedParenthensies
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
String line = input.nextLine();
Stack<Character> S = new Stack<Character>();
while(input.hasNext())
{
System.out.println("Enter: ");
Character z= input.nextLine();//this line is not working
S.push(z);
}
for (int i=0; i<line.length(); i++)
{
char c = line.charAt(i);
// do something with c
}
}
}
Hi I'm in a programming class over the summer and am required to create a program that reads input from a file. The input file includes DNA sequences ATCGAGG etc and the first line in the file states how many pairs of sequences need to be compared. The rest are pairs of sequences. In class we use the Scanner method to input lines from a file, (I read about bufferedReader but we have not covered it in class so not to familiar with it) but am lost on how to write the code on how to compare two lines from the Scanner method simultaneously.
My attempt:
public static void main (String [] args) throws IOException
{
File inFile = new File ("dna.txt");
Scanner sc = new Scanner (inFile);
while (sc.hasNextLine())
{
int pairs = sc.nextLine();
String DNA1 = sc.nextLine();
String DNA2 = sc.nextLine();
comparison(DNA1,DNA2);
}
sc.close();
}
Where the comparison method would take a pair of sequences and output if they had common any common characters. Also how would I proceed to input the next pair, any insight would be helpful.. Just stumped and google confused me even further. Thanks!
EDIT:
Here's the sample input
7
atgcatgcatgc
AtgcgAtgc
GGcaAtt
ggcaatt
GcT
gatt
aaaaaGTCAcccctccccc
GTCAaaaaccccgccccc
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
gctagtacACCT
gctattacGcct
First why you are doing:
while (sc.hasNextLine())
{
int pairs = sc.nextLine();
While you have pairs only in one line not pairs and two lines of input, but number of lines once? Move reading pairs from that while looop and parse it to int, then it does not matter but you could use it to stop reading lines if you know how many lines are there.
Second:
throws IOException
Might be irrelevant but, really you don't know how to do try catch and let's say skip if you do not care about exceptions?
Comparision, if you read strings then string has method "equals" with which you can compare two strings.
Google will not help you with those problems, you just don't know it all, but if you want to know then search for basic stuff like type in google "string comparision java" and do not think that you can find solution typing "Reading two lines from an input file using Scanner" into google, you have to go step by step and cut problem into smaller pieces, that is the way software devs are doing it.
Ok I have progz that somehow wokrked for me, just finds the lines that have something and then prints them out even if I have part, so it is brute force which is ok for such thing:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class program
{
public static void main (String [] args) throws IOException
{
File inFile = new File ("c:\\dna.txt");
Scanner sc = new Scanner (inFile);
int pairs = Integer.parseInt(sc.nextLine());
for (int i = 0; i< pairs-1; i++)
{
//ok we have 7 pairs so we do not compare everything that is one under another
String DNA1 = sc.nextLine();
String DNA2 = sc.nextLine();
Boolean compareResult = comparison(DNA1,DNA2);
if (compareResult){
System.out.println("found the match in:" + DNA1 + " and " + DNA2) ;
}
}
sc.close();
}
public static Boolean comparison(String dna1, String dna2){
Boolean contains = false;
for (int i = 0; i< dna1.length(); i++)
{
if (dna2.contains(dna1.subSequence(0, i)))
{
contains = true;
break;
}
if (dna2.contains(dna1.subSequence(dna1.length()-i,dna1.length()-1 )))
{
contains = true;
break;
}
}
return contains;
}
}
In my program, it reads a file called datafile.txt... inside the datafile.txt is a random 3 lines of words. What my program does is reads the file the user types in and then they can type in a Line # and Word # and it will tell them the word that is in that location.. for example..
What is the file to read from?
datafile.txt
Please enter the line number and word number (the first line is 1).
2 2
The word is: the
My problem is that my program reads the 3 lines in the txt doc as 0, 1 ,2 and the words start from 0. So to read the first word in the first line they would have to type 0,0 instead of 1,1. What I am trying to do is make it work so they can type 1,1 instead of 0,0. Not sure what my problem is right now, here is my code....
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class readingFile {
/**
* #param args
* #throws IOException
* #throws validException
*/
public static void main(String[] args) throws IOException, checkException
{
System.out.println("Enter file name: " );
Scanner keyboard = new Scanner(System.in);
BufferedReader inputStream = null;
ArrayList<String> file = new ArrayList<String>();
String fileName = keyboard.next();
System.out.println ("The file " + fileName +
" has the following lines below: ");
System.out.println();
try
{
inputStream = new BufferedReader(new FileReader(fileName));
ArrayList<String> lines = new ArrayList<String>();
while(true)
{
String line = inputStream.readLine();
if(line ==null)
{
break;
}
Scanner itemnize = new Scanner(line);
while(itemnize.hasNext())
{
lines.add(itemnize.next());
}
lines.addAll(lines);
System.out.println(lines+"\n");
}
System.out.println("Please enter the line number and word number");
int index1 = keyboard.nextInt();
int index = keyboard.nextInt();
System.out.println("The word is: "+ lines.get(index));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " + fileName);
}
inputStream.close();
}
private static void checkValid(ArrayList<String> items, int index) throws checkException
{
throw new checkException("Not Found");
}
}
The obvious solution to adapt 1-based user input to 0-based internal representation is to subtract one at some point. Seeing that you don't even use index1, writing
lines.get(index - 1)
isn't going to solve your problem completely. But I guess you can take it from there, and do something similar for the word index.
As I assume you are just learning to program I will point out 3 areas of improvement
Much like how mathematics has BIDMAS which determines the order of evaluation of an expression Java and other program languages evaluate statements in a particulate way. This means within the Parentheses of a function you may include a statment instead of a variable or constant. This will be evaluated with the result (or return) been passed into the called function. This is why MvG says you can do lines.get(index - 1)
Not all exceptions you should consider and plan around will the compiler inform you about. For example in your code an invalid input for line number or word number is entered you will get a Runtime Exception (array index out of bound)
Naming of variables should be useful, you have index and index1. What's the difference? I assume from reading your code one should be the user selected index of the line number and the second should be the index of the word on said line. May I suggest requestedLineIndex and requestedWordIndex.
On a final note this is not a usual StackOverflow question hence why your question has been 'voted down'. If you are learning as part of a course is there a course forum or Virtual Learning Environment (VLE) you can post questions on? The support of your peers at the same level of learning tends to help with exploring the basics of a language.
I have looked at all the links and cannot seem to get what I am looking for. I have a text file I need to read in. First the text file format:
3 STL NY Chi //all on one line
STL NY 575 //on its own line
NY Chi 550 //on its own line
STL Chi 225 //on its own line
I need to read the int into an int variable, say we call it count. Then the actual cities on that same line into an array. The next lines need to read into an array to where the mileage is associated with the array, such as [STL NY]=575. I can only use arrays. No hash tables, list, stacks or queues. Here is what I got so far and honestly it isn't much. I could really use some help for I am pretty stumped on the "howto" on this.
import java.io.*;
import java.util.*;
public class P3 {
/**
* #param args the command line arguments
*/
public static int count;
public static void main(String[] args) {
try {
FileInputStream dataFile = new FileInputStream("Data.txt");
//BufferedReader br = new BufferedReader(new InputStreamReader(dataFile));
String line = br.readLine();
}
catch (IOException e) {
System.err.println ("Unable to open file");
System.exit(-1);
}
}
}
I think I'm getting there, but I am getting an error code of: "non-static variable cities cannot be referenced from a static context." I am trying to test my code by printing. Can anyone help me with this printing? I would like to see what is in the arrays to make sure I did it correctly. Here is my code:
package p3;
import java.io.*;
import java.util.*;
class citiesDist {
String cityOne;
String cityTwo;
int miles;
}
class city {
String cityName;
int numberLinks;
citiesDist[] citiesDists;
}
public class P3 {
city[] cities;
void initCity(int len) {
for (int i = 0; i < len; i++) {
cities[i] = new city();
}
}
void initCitiesDist (int index, int len) {
for (int i = 0; i < len; i++) {
cities[index].citiesDists[i] = new citiesDist();
}
}
void parseFile() throws FileNotFoundException, IOException {
FileInputStream fstream = new FileInputStream("Data.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int numberCities = Integer.parseInt(br.readLine());
cities = new city[numberCities];
initCity(numberCities);
for (int i = 0; i < numberCities; i++) {
String line = br.readLine();
int numberLink = Integer.parseInt(line.split(" ")[1]);
cities[i].cityName = line.split(" ")[0];
cities[i].numberLinks = numberLink;
initCitiesDist (i, numberLink);
for (int j = 0; j < numberLink; j++){
line = br.readLine();
cities[i].citiesDists[j].cityOne = line.split(" ")[0];
cities[i].citiesDists[j].cityTwo = line.split(" ")[1];
cities[i].citiesDists[j].miles = Integer.parseInt(line.split(" ")[2]);
}
}
}
public static void main(String args[]) {
System.out.println("city" + cities.city);
}
}
If you're ever stumped on code, don't think about the programming language; it only serves to further muddle your logic. (Separate the algorithm from the language.) When you have a clear idea of what you want to accomplish, add your language in (insofar as, "how do I accomplish this particular task?").
Ultimate Goal
From your design, your goal is to have a graph relating the distances between each city. It would appear something like this:
[STL][NY] [Chi]
[STL][0] [575][25]
[NY] [575][0] [550]
[Chi][25] [550][0]
This isn't too terribly difficult to accomplish, in terms of the file input and the Scanner class.
First Steps
You have to extract the dimensions of your graph (which is a 3 by 3). This is provided for you in the first line of your input file. Getting an integer from a Scanner with a File in it isn't too difficult, just make sure you have the proper classes imported, as well as the proper error handling (either try...catch or throwing the exception).
Scanner sc = new Scanner(new File("input.txt"));
You'll need two arrays - one for the cities, and one for the distances themselves. We don't know how large they are (you never assume the data in a file, you just assume the form of the data), so we have to get that from the file itself. Luckily, we are given an integer followed by the cities themselves. We will read this integer once and use it in multiple different locations.
String[] cities = new String[sc.nextInt()];
int[][] distances = new int[cities.length][cities.length];
for(int i = 0; i < cities.length; i++) {
// Surely there's a method in Scanner that returns String that reads the _next_ token...
}
The Exercise to the Reader
You now have your data structure set up and ready to go. What you would need to do from here is bridge the gap between the cities array and distances array. Consider the order in which they arrived in the file, and the order in which we're encountering them. You would be well-served with some methodology or way to answer the question, 'Which came first - STL or NY?'
Give it a whirl and see if you can get further.