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.
Related
I am currently programming an assignment for a class of mine. I am trying to print to my output file to a csv file. The problem is, after I end my second print statement, my output doesn't line up after starting the print statement in my while loop.
For example, here is my code:
oFile = new PrintStream(new File("output.csv"));
oFile.println("First Name" + "," + "Last Name" + "," + "Lecture Section"+","+"Lab Section"+","+"Lab 1"+","+"Lab 2"+","+"Lab 3"+","+"Lab 4"+","+"Lab 5"+","+"Lab 6"+","+"Lab 7"+","+"Lab 8"+","+"Lab 9"+","+"Lab 10");
loadLectureArray();
loadLabArray();
sortClassSections();
for (int i = 0; i < stud.size(); i++) {
oFile.println(stud.get(i).getStudFirstName() + ","+stud.get(i).getStudLastName()+","+stud.get(i).getStudLectureNum()+","+stud.get(i).getStudLabNum()+",");
while (numLab < 10 && i < stud.size()) {
oFile.println(labStud.get(i).grades.getStudLabGrade()[numLab]);
numLab++;
}
numLab = 0;
}
After I execute my while loop, my new data is printed in-between my header and other data. Some of the code is not perfect, but currently I am just seeking advice about reformatting my output to line back up with the print statements.
This is my first time exporting a file to csv, so if there is something I am doing wrong or need to change, please let me know! I hope you can make sense out of what I'm trying to ask for. Thanks in advance!
well, println always prints a newline, so you get a newline after every grade. you should be able to get what you want using oFile.print(...) instead of oFile.println(...) inside the for loop and just one oFile.println() at the very end of it.
i also noticed that the test for i < stud.size() in the head of the while loop is redundant since nothing should be changing either i or stud.size() between this test and the same test in the head of the for loop.
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).
My program is supposed to read a file that looks like this:
8 7
~~~~~~~
~~~~~~~
B~~~~~~
~~~~~~~
~~~~B~~
~~~~B~~
~~~~~~B
~~~~~~~
I need to disregard the first line (8 and 7) and read the following characters into a 2-D array. I thought the code I wrote up would do so, but it doesnt. I need map[0][0] to correspond to the first "~", and for map[3][0] to correspond to the first 'B'. This is the code I'm using.
try
{
File file = new File(args[1]);
Scanner sc = new Scanner(file);
String themap = sc.nextLine();
theFirst = themap.indexOf(" ");
theSecond = themap.lastIndexOf(" ");
int rows = Integer.parseInt(themap.substring(0, theFirst));
int columns = Integer.parseInt(themap.substring(theSecond+1));
char[][] map = new char[rows][columns];
while (k < rows)
{
//System.out.println(k);
while (j < columns)
{
while (sc.hasNextLine())
{
themap = sc.nextLine();
System.out.println(themap);
map[k][j] = themap.charAt(j);
System.out.println(map[k][j]);
}
j++;
}
k++;
}
sc.close();
}
catch (Exception e)
{
System.out.println("ERROR: File does not exist");
}
I threw in a test statement there to see what was happening with map[j][k] and it only prints out the first character of each line. Like I said, I need it to correspond to the file I'm reading it from, but I'm not sure what I'm doing wrong. Help would be appreciated.
You're calling nextLine() repeatedly within your innermost loop on the first time through; after which there's nothing more to read. So the only thing you're populating is map[0][0].
You need to get rid of the innermost while loop entirely, and move sc.nextLine() to inside your outer loop.
The basic structure should be this. Feel free to add any println calls and error checking. Also, many people would find it more intuitive to use for loops instead of while.
while (k < rows) {
themap = sc.nextLine();
j = 0;
while (j < columns) {
map[k][j] = themap.charAt(j);
j++;
}
k++;
}
Your problem is you are reading every line due to the inner while loop every column (not 1 line every row).
Move the nextLine() call outside the column loop.
Other improvements:
It seems obvious that the first line is the number or rows and columns - you should rely on and use that
Don't use while loops, use for loops and name the loop variable row and column to make your code more readable
Don't use hasNextLine() as a loop control - check it if you must and throw an exception if a line should be there but isn't
make your code more modular by creating a method to return an array of char given a String
consider throwing an exception if the line length is incorrect
use nextInt() to read the numbers
Your looping is incorrect . try this.
Your logic to determine no of rows and columns is good and there is no problem with that. Some people have mentioned that you discarded the first line but you didn't.
for(int i=0;i<rows&&sc.hasNextLine();i++){
themap = sc.nextLine();
for(int j=0;j<columns;j++){
map[i][j] = themap.charAt(j);
System.out.print(map[i][j]);
}
System.out.println();
}
I need to read a text file using java. Not a problem. But I need to reject the empty lines at the end of the file. The file is quite large, around a million or so lines. I need to process each line, one at a time. Even if they are empty.
But, if the empty lines are at the end of the file, then I need to reject it. Note that there can be multiple empty lines at the end of the file.
Any quick solutions? I almost want to write a FileUtility.trimEmptyLinesAndEnd(File input). But I cant help feeling that someone might have written something like this already.
Any help appreciated.
Note:
I have read this link.
Java: Find if the last line of a file is empty.
But this is not what I am trying to do. I need to reject multiple
empty lines.
When you find an empty line, increment a counter for the number of empty lines. If the next line is also empty, increment the counter. If you reach the end of the file, just continue on with what you want to do (ignoring the empty lines you found). If you reach a non-empty line, first do whatever you do to process an empty line, repeating it for each empty line you counted. Then process the non-empty line as normal, and continue through the file. Also, don't forget to reset the empty line counter to zero.
Pseudo code:
emptyLines = 0;
while (the file has a next line) {
if (line is empty) {
emptyLines++;
} else {
if (emptyLines > 0) {
for (i = 0; i < emptyLines; i++) {
process empty line;
}
emptyLines = 0;
}
process line;
}
}
You have to read all lines in your file. You can introduce a guarding that will store the value of last not empty line. At the end return the subset from zero to guardian.
In case you have a stream process.
read line
if empty
increase empty lines counter
else
if there was some empty lines
yield fake empty lines that counter store
reset counter
yield line
Thanks for all the responses. I think both Vash - Damian LeszczyĆski and forgivenson cracked the pseudocode for this problem. I have taken that forward and am providing here the Java code for people who come looking for an answer after me.
#Test
public void test() {
BufferedReader br = null;
try {
String sCurrentLine;
StringBuffer fileContent = new StringBuffer();
int consecutiveEmptyLineCounter = 0;
br = new BufferedReader(new FileReader("D:\\partha\\check.txt"));
while ((sCurrentLine = br.readLine()) != null) {
// if this is not an empty line
if (!(sCurrentLine.trim().length() == 0)) {
// if there are no empty lines before this line.
if (!(consecutiveEmptyLineCounter > 0)) {
// It is a non empty line, with non empty line prior to this
// Or it is the first line of the file.
// Don't do anything special with it.
// Appending "|" at the end just for ease of debug.
System.out.println(sCurrentLine + "|");
} else {
// This is a non empty line, but there were empty lines before this.
// The consecutiveEmptyLineCounter is > 0
// The "fileContent" already has the previous empty lines.
// Add this non empty line to "fileContent" and spit it out.
fileContent.append(sCurrentLine);
System.out.println(fileContent.toString() + "#");
// and by the way, the counter of consecutive empty lines has to be reset.
// "fileContent" has to start from a clean slate.
consecutiveEmptyLineCounter = 0;
fileContent = new StringBuffer();
}
} else {
// this is an empty line
// Don't execute anything on it.
// Just keep it in temporary "fileContent"
// And count up the consecutiveEmptyLineCounter
fileContent.append(sCurrentLine);
fileContent.append(System.getProperty("line.separator"));
consecutiveEmptyLineCounter++;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Thanks for all the help.
And, what I have provided here is just one solution. If someone comes across something more clever, please share. I can't shake the feeling off that there should be some FileUtils.trimEmptyLinesAtEnd() sort of method somewhere.
Just read the File backwards. Starting from the first line you read, refrain from processing all blank lines you encounter.
Starting with the first non-blank line you encounter, and thereafter, process all lines whether or not they're blank.
The problem is "intractable" wrt to a neat solution if you read the File forward since you can never know if at some point after a long run of blank lines there might yet be a non-blank line.
If the processing of lines in order, first-to-last, matters, then there is no neat solution and anything like what you have now is about what there is.
I'm trying to make a piece of code that will yell out anything I input.
So the command is 'yell'
I want to be able to type 'yell (whatever i want here)' and it will yell it out. I've managed to get this working with a help of a friend. But for some reason it will only yell the first word that's been output. So I can't type a sentence because it will only say the first word of a sentence.
Here's the piece of code, I hope you can help.
case "npcyell":
for (NPC n : World.getNPCs()) {
if (n != null && Utils.getDistance(player, n) < 9) {
String sentence = "";
for (int i = 1; i < cmd.length; i++) {
sentence = sentence + " " + cmd[i];
}
n.setNextForceTalk(new ForceTalk("[Alert] "
+ Utils.getFormatedMessage(sentence)));
}
}
return true;
Well I did something similar a while ago. You said that you wanted to be able to say "yell(text)" and have it output whatever the text was. I have a different way of implementing it than you do, but the general result is the same, but it can be adapted to however you are using it in this context. This is also assuming that you are running this program as a console project only. if not change the scanner with whatever you are using to input text into and replace the text assignment to text = textInputArea.getText().toString(); and change the output statement to System.out.println(text.getText().toString().substring(6,text.getText().toString().length() - 1));
Scanner s = new Scanner(System.in);
String text = s.nextLine();
if (text.startsWith("yell(") && text.endsWith(")")){
System.out.println(text.substring(6,text.length() - 1));
}
I hope this works for you. And I honestly hope that this is adaptable towards the program you are making.