This is my first ever question, apologies for any mistakes I make while asking for help!
I am trying to sort the 5 most repeated words from a text file in Processing and I'm confused about this error I keep getting. I'm new to Java and after searching the internet, any changes I make are not appear to be helping. What do I need to do to amend to fix the issue?
Here is the code in question -
import java.util.Iterator;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;
void setup() {
size(800, 480);
smooth();
String[] data = loadStrings("data/data.txt");
ImmutableMultiset<String> myMultiset = ImmutableMultiset.copyOf(data);
top = Multisets.copyHighestCountFirst(myMultiset);
}
Iterator it = top.entrySet().iterator();
for (int i = 0; (i < 5) && it.hasNext(); i++) {
Multiset.Entry entry = (Multiset.Entry) it.next();
String word = (String) entry.getElement();
int count = entry.getCount();
System.out.println(word + " -> " + count);
}
Thank you kindly in advance for the help!!
I edited to fix your indentation, and you appear to have an extra brace on the last line. If you copied the for-loop from inside a function, and accidentally copied the function's closing brace, please show us the rest of the function.
top = Multisets.copyHighestCountFirst(myMultiset);
}
It seems like this brace here isn't right.
Do you intend to end your "setup" method here?
If so you can't have things like sysout and for's not in a method, as well as there being an extra brace at the end.
Try putting the rest of your code in a method like so:
void iteratorMethod(){
Iterator it = top.entrySet().iterator();
for (int i = 0; (i < 5) && it.hasNext(); i++) {
Multiset.Entry entry = (Multiset.Entry) it.next();
String word = (String) entry.getElement();
int count = entry.getCount();
System.out.println(word + " -> " + count);
}
}
Note that you will have to call iteratorMethod() in the last line of your setup method (assuming that's what you want to do).
Related
Problem
I am currently creating a program to read a file and find a couple of variables. I am running into this problem where changing one println changes the entire output of my code. I have never run into this before and am not sure if this is an eclipse error or my error?
My Code
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FileAnalyzer {
public static void main(String args[]) throws IOException {
Scanner input = new Scanner(System.in);
String fileName;
int words = 0, letters = 0, blanks = 0, digits = 0, miscChars = 0, lines = 0;
System.out.print("Please enter the file path of a .txt file: ");
fileName = input.nextLine();
File text = new File(fileName);
//System.out.println(text.exists());
Scanner word = new Scanner(text);
while(word.hasNext()) {
//System.out.println(word.next());
words++;
}
word.close();
Scanner letter = new Scanner(text);
while(letter.hasNext()) {
String currentWord = letter.next().toLowerCase();
for(int i = 0; i < currentWord.length(); i++) {
if(Character.isLetter(currentWord.charAt(i))) {
letters++;
}
}
}
letter.close();
Scanner blank = new Scanner(text);
while(blank.hasNextLine()) {
String currentWord = blank.nextLine();
for(int j = 0; j < currentWord.length(); j++) {
if (currentWord.charAt(j) == ' ') {
blanks++;
}
}
}
blank.close();
System.out.println("Words: " + words);
System.out.println("Letters: " + letters);
System.out.println("Blanks: " + blanks);
}
}
However
Simply changingSystem.out.println(word.next()) in the first Scanner instance changes the entire output. If i leave it in I get the three print statements at the bottom and what I am looking for. If I remove it since I do not want each word printed in the file it shows as nothing in the console. Not Sure why one print statement within a while statement changes the entire output.The only reason it was there in the first place was to make sure the scanner was taking input the way I had wanted.
Not Sure why one print statement within a while statement changes the entire output
Because when the statement is present, you're consuming a token from the scanner. When it's commented out, you're not. It's not the printing that consumes the token, it's the call to next().
With it commented out, your loop is:
while (word.hasNext()) {
words++;
}
hasNext() doesn't modify the state of the scanner, so that will just loop forever if it goes into the loop body at all.
If you want to have a line you can comment out or not, change the code to:
while (word.hasNext()) {
String next = word.next(); // Consume the word
System.out.println(next); // Comment this out if you want to
words++;
}
By using System.out.println(word.next()); you are cycling through the elements in a collection due to the next() method. So invoking next() directly will allow you to move through the iteration.
When commenting out //System.out.println(word.next());, then word.hasNext() will cause you to loop forever(provided there is a word) as you will not be able to move to the next token.
The below snippet will help you achieve your desired result
while(word.hasNext()){
word.next();
words++;
}
Not sure why you would want to go thru the text three times. But if you really have to, I would close the first scanner before opening the next.
I'm very new to stack overflow, and I've been learning Java for a few months now. I have so far created a calculator which can find multiple sets of brackets and correctly work them out. However I'm struggling to figure out how to get it to correctly find brackets inside of brackets correctly.
For example;
Say I input the below string...
"10+(2+(3*2))"
I basically want it to set "3*2" to another string. How would I go about getting whats inside the deepest brackets?
Thanks in advance for any help/advice, ask questions if I've been unclear or too vague.
Here is what I have so far for checking for brackets;
public static String checkForBrackets(String formula) {
for (int i = 0; i < formulaChars.size(); i++) {
for (int j = 0; j < formulaChars.size(); j++) {
if ((formulaChars.get(i) == ')') && (formulaChars.get(j) == '(')) {
bracketFormula = formula.substring(j + 1, i);
formulaChars.clear();
}
}
}
System.out.println(bracketFormula)
}
The for loops are checking for the left most opening and closing bracket.
If I was to input the string "10+(2+(3*2))", the code would return "2+(3*2" instead of what I want; "3*2"
while(reader.hasNextLine()){
String s = reader.nextLine();
String[] tokens = s.split(" ");
while(t < tokens.length){
a = 0;
while( a < 6 ) {
if(tokens[t].equals(d[a])){
System.out.println("found keyword -> " + tokens[t]);
files = 1;
}
a++;
}
p = 0;
while( p < 2 ) {
if(tokens[t].equals(xyz[p])){
System.out.println("found token -> " + tokens[t]);
files2 = 1;
}
p++;
}
if (files2 == 0 && files == 0){
System.out.println("found identifier -> " + tokens[t]);
}
files = 0;
files2 = 0;
t++;
}
reader.close();
}
I posted something similar like this the other day, but however the while loop didn't fix it . Can some please help me through this. The problem is that it doesn't read the entire the file but only reads the one line, and that is the first line. I don't know what I am doing honestly. Thanks.
It looks like you are closing your reader (reader.close();) inside of the while loop.
As #rlinden just mentioned, be sure to reset your loop variables. Where you currently have reader.close(); make sure to set t = 0; for the next loop or take #user184994's sage advice.
Either way, you'll need to move reader.close(); outside of (below) the outermost while loop.
Is there any more code missing above this block? That could have a big effect on how the reader is functioning. Please post your new / edited code below the first block of code so I can see where any new problems are. Mark them with the tag Update:
I'll watch for edits and provide more advice if possible.
I believe that the problem is that you didn't reset t after the inside while. Try including the line
t=0;
before the inside loop.
I did not debug your code, but I assume that if the first line has a number of tokens that is equal or bigger than the second, when the second line is read t is already equal to tokens.length.
I hope it helps.
As was mentioned by others, the reader.close(); call is inside the while(reader.hasNextLine()) loop. This is causing the reader to be closed before the second line is ever read. Move it outside the outermost loop (i.e. after the } on the following line). Then address the issue of the variable t not getting set/reset.
I have a program that reads from a csv file full of peoples last names, first names, and birth years, assigns them into a special class array, and then gets sorted according to their last name. I believe that my code is working, so all I have to do to verify this is output the list and see if indeed all of the people were sorted by their last name. However, I am having trouble finding the right syntax to do this.
Here is the code of my Main.java, where I think the issue must be.
package project_1_sorting;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws IOException {
// open file input stream
BufferedReader reader = new BufferedReader(new FileReader(
"C:\\Users\\Owner\\Desktop\\Data 18k.csv")); // double check where this is trying to read it from
// read file line by line
String line = null;
Scanner scanner = null;
int index = 0;
Human[] pplArray = new Human[18000];
int i = 0;
while ((line = reader.readLine()) != null) {
Human ppl = new Human();
scanner = new Scanner(line);
scanner.useDelimiter(",");
while (scanner.hasNext()) {
String data = scanner.next();
if (index == 0)
ppl.setLastName(data);
else if (index == 1)
ppl.setFirstName(data);
else if (index == 2)
ppl.setBirthYear(data);
else
System.out.println("invalid data::" + data);
index++;
}
ppl.setKey(0); //change this for later things, you can use loop
ppl.setOrder(0); //change this to 1 if you want to invert the list of people
index = 0;
pplArray[i] = ppl;
i++;
System.out.println(pplArray);
}
//close reader
reader.close();
System.out.println(pplArray); // create
Selection_Sort selection = new Selection_Sort();
for (int j = 0; j < 18000; j++)
{
System.out.println(pplArray[j]);
}
}
}
So I was expecting this to output a giant list of all of my people from the csv file(ordered), with all of their info in the same format as they originally were, right. (one person per row, with 3 collumns for their 3 strings). However this is what I got instead:
run:
Test
17
true
0.142857
BUILD SUCCESSFUL (total time: 0 seconds)
I am not sure what the meaning of this is. It would seem that its doing something completely unrelated to what I am trying to do. This is the only project that I have open in NetBeans, so it must be generated from my functions, right? If anyone knows what this is all about, please let me know. If there is nothing else wrong with this Main.java, I can post my other .java files.
One thing I did notice was that, even when I commented out my selection sort function call, and all of the printline commands in this .java file, the same output was displayed on my screen.
Please let me know what you think.
You have a few issues
The statements
Selection_Sort selection = new Selection_Sort();
for (int i = 0; i < 18000; i++)
{
System.out.println(pplArray[i]);
}
should be in the main18k method rather than the class block
Then the variable i has already been used so you need to use a different variable name either of those places where its used
for (int j = 0; j < 18000; j++)
Lastly use main instead of main18k so the application has a valid entry point
You have not close the bracket properly.Also variable i is used twice in the main method.So change the variable name.
Remove bracket before line Selection_Sort selection = new Selection_Sort();
Change the variable i to j and code is as below :
for (int j = 0; j < 18000; j++)
{
System.out.println(pplArray[j]);
}
So I have this text file
\begin{document}
{\Large \begin{center} Homework Problems \end{center}}\begin{itemize}\item\end{itemize}
\begin{enumerate}
\begin{proof}
\begin{align}
\end{align}
\end{proof}
\begin{proof}
\begin{align}
\end{align}
\end{proof}
\end{enumerate}
\end{document}
And I want to go through each line, find all of the "\begin" pieces and then take the string with in the "{_}" and store it in a stack. When the corresponding "\end" is found, I call the pop() command on the Stack and remove it. I'm have a few issues though...
I'm running into dealing with all sorts of crazy cases and making sure everything is accommodated and its becoming too specific to this case when I want to make it work for all sorts of files that are written as such.
I don't know how to check for "\begin" and "\end" as opposed to "begin" and "end", the reason this is important is because if the file contains text that says "begins" or "end" it might not be a command and thus, not what I'm looking for.
All "if" statements DO NOT work on account of the "\" being present, I tried adding square brackets but it didn't fix anything.
Here is my code so far, and its getting really confusing, can anyone help organize and help rectify the issues I've stated above?
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
public class LaTeXParser{
public static void main(String args[]) throws FileNotFoundException{
Scanner scan = new Scanner(System.in);
Stack s = new Stack();
int lineCount = 0;
String line;
String nextData = null;
String title = null;
String fname;
System.out.print("Enter the name of the file (no extension): ");
fname = scan.next();
fname = fname + ".txt";
FileInputStream fstream = new FileInputStream(fname);
Scanner fscan = new Scanner(fstream);
System.out.println();
while(fscan.hasNextLine()){
lineCount++;
line = fscan.nextLine();
StringTokenizer tok = new StringTokenizer(line);
while(tok.hasMoreElements()){
nextData = tok.nextToken();
System.out.println("The line: "+nextData);
if(nextData.contains("\\begin") && !nextData.contains("\\end")){
if(nextData.charAt(1) == 'b'){
title = nextData.substring(nextData.indexOf("{") + 1, nextData.indexOf("}"));
s.push(title);
}
else{
//title = nextData.substring();
}
}//end of BEGIN if
if(nextData.contains("\\end") && !nextData.contains("\\begin")){
if(s.peek().equals(nextData.substring(nextData.indexOf("{") + 1, nextData.indexOf("}")))){
s.pop();
}
}//end of END if
if(nextData.contains("\\begin") && nextData.contains("\\end")){
String[] theLine = nextData.split("[{}]");
for(int i = 0 ; i < theLine.length ; i++){
if(theLine[i].equals("\\end") && theLine[i+1].equals(s.peek())){
s.pop();
}
if(theLine[i].equals("\\begin")){
title = theLine[i+1];
s.push(title);
}
}
}//end of BEGIN AND END if
}
}//end of whiles
fscan.close();
while(!s.isEmpty()){
System.out.println("the top "+s.pop());
}
}
}
EDIT: In the if statement that is used to check a line to see if it contains both a "\begin" and "\end" after finding the "\begin", how do I go back through to check if that line also contains it's "\end"? So I am talking about the case...
\begin{itemize}\item\end{itemize}
See I can get to the "\begin" and add the proper string, but it just moves and passes the "\end{itemize}". Anyway to fix this?
Actually it should check and perform normally even after the "itemize" string is pushed, but it doesn't work! I believe it has to do with "\end", can anyone confirm? It skips over that step, and obviously because it doesn't fit the conditions, but it works for the other lines. Just not this specific case!
You probably need to escape the backslashes, so write \\ instead of \. And if they are in regular expressions (regexprs) you need to escape them twice: \\\\ ; I don't think the brackets are needed.