Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problems using/making method!

 
kristian jarvi
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this code cuts the lines in file into equal length
peaces.
Parsing works fine if i do everything in main without making
method (Cut) to the parsing part.
But I to want to make method (Cut) that does the parsing.
It's not working right. If first word is "this" it should parse
the file into lines that have 4 chars. It works fine until there is
under 4 chars left for the last line. So it shows only even lines.
Why is that?
FILE
this is
not
working

now it prints
this
is n
ot w
orki
---last line missing.Why?
it should print
this
is n
ot w
orki
ng
import java.io.*;
import java.util.*;
class Parse{
public static void main(String []args)throws IOException {
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
try{
File inputFile = new File ("help.txt");
FileReader fis =new FileReader(inputFile);
BufferedReader bis = new BufferedReader(fis);
StringBuffer sb=new StringBuffer();
for(String line=bis.readLine().trim();line != null;line=bis.readLine()) {
sb.append(" ").append(line.trim());
}
String test=sb.toString();
Cut(test);
}
catch ( FileNotFoundException fnfe ) {
fnfe.printStackTrace();
}
catch ( IOException ioe ) {
ioe.printStackTrace();
}//catch
}//main

public static String Cut(String test){
String tmp=" ";
int space=0;
test=test.trim();
int len=test.indexOf(" ");
for(int i=0;i<test.length();i++){
char c=test.charAt(i);
if(c!=' ') tmp=tmp+""+c;
if(c==' ' && (space<1) && !(tmp.equals(""))) {
tmp +=""+c;
space++;
}
if(tmp.length()==len) {
System.out.println(tmp);
tmp="";
space=0;
}
}
if(tmp.length()<len){
for(int i=0;i<=(len-tmp.length());i++)
tmp +=""+' ';
}
return(tmp);
}
}
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Here's the code formatted using [ code ] and [ /code]:
 
Steve Fahlbusch
Bartender
Posts: 605
7
Mac OS X Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kristian,
Look at inserting a print statement in the if
block after the for block in cut.
steve
 
Michael Matola
whippersnapper
Ranch Hand
Posts: 1820
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by kristian jarvi:
[QB]this code cuts the lines in file into equal length peaces.
<snip>
it should print
this
is n
ot w
orki
ng

So wait, the space that's already there between "this" and "is" should be taken out but the end-of-line markers should be converted to spaces?
Maybe I'm completely missing the point of what this code is supposed to be doing, but I took a shot at simplifying it anyhow:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic