[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 648
  • Last Modified:

displaying text and converting

hello
2 part question

what is the best way to diplay multiple lines of text, i don't want the user to be able to edit, in a frame? do i just draw string?

i want to read a string from a file with numbers something like:
12 34 54 73 97 and so on
I want to convert each number in the string to an integer
so that 12 would be an integer 34 another integer and so on

please give examples
thanks
0
Samooramad
Asked:
Samooramad
  • 52
  • 32
  • 25
  • +2
2 Solutions
 
brunomsilvaCommented:
well,
you could use HTML <html>line1<br>line2</html> for the multiline question

bruno
0
 
CEHJCommented:
Just use a JTextArea and setEditable(false)
0
 
CEHJCommented:
You could also do this in your frame

JEditorPane textDisplay = new JEditorPane("file:/c/yourFile.txt");
getContentPane().add(textDisplay, BorderLayout.CENTER);

which will display the file
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
CEHJCommented:
If you need to display AND convert, then you'll need to break up the operation, reading 'manually' from the file
0
 
SamooramadAuthor Commented:
I'm not using html bruno
0
 
SamooramadAuthor Commented:
>> JTextArea and setEditable(false)
some answers are so simple they make me feel like a moron. I'm sure that will do the trick
0
 
SamooramadAuthor Commented:
>>If you need to display AND convert, then you'll need to break up the operation, reading 'manually' from the file
no i don't want to display the file. I just want to break the string up into integers(that have a max of 2 digits) then i will use them seperatly somewhere else
0
 
CEHJCommented:
I'm getting confused - this is what you said first:

>>what is the best way to diplay multiple lines of text, i don't want the user to be able to edit
0
 
CEHJCommented:
Have a look at this example. Then you can add the following functionality

http://javaalmanac.com/egs/java.io/ReadLinesFromFile.html

try {
        BufferedReader in = new BufferedReader(new FileReader("infilename"));
        ArrayList numbers = new ArrayList();
        String str;
        while ((str = in.readLine()) != null) {
            numbers.add(process(str, numbers));
        }
        in.close();
    } catch (IOException e) {
    }



........


public void process(String numberLine, List numbers) {
      String[] strNumbers = numberLine.split("\\s");
      for(int i = 0;i < strNumbers.length;i++) {
            numbers.add(new Integer(Integer.parseInt(strNumbers[i])));

      }
}
0
 
CEHJCommented:
Oops

>>numbers.add(process(str, numbers));


should be

process(str, numbers);
0
 
SamooramadAuthor Commented:
sorry i wasn't clear cehj
the first part has nothing to do with the second i have a frame that will display directions but i couldn't figure out how to display MULTIPLE lines s of text except with JTextArea which can be edited. I didn't know you can disable that

the second part is where i have an applet that uses values(integers) for drawing shapes. i want the added feature of opening a file and reading numbers from the file to use in drawing. to do that i need them converted into integers so that i can use each one to draw a different shape in the applet. I have figured out how to read from a file and how to display what is read in the applet. my problem is they need to be integers so i can use them and i don't know how to break up the string and convert into integers
0
 
CEHJCommented:
OK. That code i just posted will do that for you. When you come to use them, you need to do another operation, since the list does not contain primitives:

int firstInt = ((Integer)numbers.get(0)).intValue();
0
 
SamooramadAuthor Commented:
is there any quick way for me to check if it is working correctly getting it into the drawing part will take me a while
0
 
CEHJCommented:
Not that i can think of. A small adjustment here:

>>numbers.add(new Integer(Integer.parseInt(strNumbers[i])));


should be

numbers.add(new Integer(Integer.parseInt(strNumbers[i].trim())));
0
 
SamooramadAuthor Commented:
numbers would be a list of integers then? is that similar to an array of integers?
0
 
SamooramadAuthor Commented:
what does trim do?
0
 
CEHJCommented:
>>numbers would be a list of integers then? is that similar to an array of integers?

yes and yes

>>what does trim do?

removes unwanted space at the ends of the String

0
 
SamooramadAuthor Commented:
well thanks cehj. It will take me till tomorrow to find out if its working right(I'm sure it will) you've been great help in just a couple hours :)
I will post any more questions I have same time tomorrow. hope i find you
thanks again
0
 
SamooramadAuthor Commented:
one more question

>>BufferedReader in = new BufferedReader(new FileReader("infilename"));
what is infilename? variable? do i use mine?
0
 
CEHJCommented:
ok
0
 
CEHJCommented:
>>what is infilename? variable? do i use mine?

It's the name of the file to read. You'd use your own
0
 
objectsCommented:
import javax.swing.*;

public class DisplayText
{
   public static void main(String[] args)
   {
      JFrame f = new JFrame();
      JTextArea ta = new JTextArea("first line\nsecond line\nthird line");
      ta.setEditable(false);
      f.getContentPane().add(new JScrollPane(ta));
      f.pack();
      f.show();
   }
}
0
 
objectsCommented:
import java.util.*;

public class DisplayText
{
   public static void main(String[] args)
   {
      String line = "12 34 54 73 97";
      StringTokenizer st = new StringTokenizer(line);
      int values = new int[st.countTokens()];
      int i = 0;
      while (st.hasMoreTokens()) values[i++] = Integer.parseInt(st.nextToken());

      // print it out
      for (int j=0; j<values.length; j++) System.out.println(values[j]);
   }
}
0
 
objectsCommented:
better change the name of that second one:

import java.util.*;

public class ParseText
{
   public static void main(String[] args)
   {
      String line = "12 34 54 73 97";
      StringTokenizer st = new StringTokenizer(line);
      int values = new int[st.countTokens()];
      int i = 0;
      while (st.hasMoreTokens()) values[i++] = Integer.parseInt(st.nextToken());

      // print it out
      for (int j=0; j<values.length; j++) System.out.println(values[j]);
   }
}
0
 
SamooramadAuthor Commented:
i'm using list and i got an error:
Error #: 304 : reference to List is ambiguous; both interface java.util.List in package java.util and class java.awt.List in package java.awt match at line 423, column 8
 
what does that mean?
0
 
CEHJCommented:
That's a blunder by Sun. Use the fully qualified names

java.util.List items = new ArrayList();
java.awt.List guiItems = new java.awt.List(....


or whatever
0
 
SamooramadAuthor Commented:
got another error from using split method in the code you posted
Error #: 300 : method split(java.lang.String) not found in class java.lang.String at line 411, column 39
0
 
CEHJCommented:
That means you have an out of date version of Java. I'd recommend you update it unless you have a good reason for not doing so as you'll be missing out on a lot of powerful functionality added in 1.4.

http://java.sun.com/j2se/1.4.2/download.html
0
 
SamooramadAuthor Commented:
do i need to download both the software kit and runtime environment?
would it just update the older version or do i install it separetly?
0
 
CEHJCommented:
You may as well get both. Unless you've got a good reason for not doing, i'd uninstall your old version(s) first and then install the new one(s).
0
 
SamooramadAuthor Commented:
no reason. I just worry I'll uninstall the working one and won't get the new version installed then I'll be in a mess
0
 
CEHJCommented:
Well i don't blame you - i get like that myself ;-). If you're not feeling like it at the moment, combine my code with objects StringTokenizer code, then you'll get out of that split() problem
0
 
SamooramadAuthor Commented:
so just replace split with string tokenizer?
I'm in the proccess of downloading.. keep your fingers crossed :)
I'll be one sad girl if this doesn't work
0
 
SamooramadAuthor Commented:
ok so there was a problem downloading...if there is any possible way to do this for now I'd prefer that.
objects code went right over my head... could you give me an idea how to use it with yours?
0
 
CEHJCommented:
Just change my process method to

public void process(String numberLine, List numbers) {
     StringTokenizer st = new StringTokenizer(numberLine);
     while(st.hasMoreTokens()) {
          numbers.add(new Integer(Integer.parseInt(st.nextToken().trim())));
     }
}
0
 
SamooramadAuthor Commented:
ok I'll try it
thanks
0
 
objectsCommented:
> so just replace split with string tokenizer?

see the code I posted earlier :)

> objects code went right over my head

Then ask what you're confused about :)
Though CEHJ's example looks pretty much the same.
0
 
objectsCommented:
save the second example as ParseText.java and run it using:
java ParseText

import java.util.*;

public class ParseText
{
   public static void main(String[] args)
   {
      // line of text to parse

      String line = "12 34 54 73 97";
     
      // tokenize the string

      StringTokenizer st = new StringTokenizer(line);

      // create array to store values

      int values = new int[st.countTokens()];
      int i = 0;

      // read ints from string and store in array

      while (st.hasMoreTokens()) values[i++] = Integer.parseInt(st.nextToken());

      // print it out

      for (int j=0; j<values.length; j++) System.out.println(values[j]);
   }
}
0
 
SamooramadAuthor Commented:
if there were only one thing I was confused about i would be specific objects :)
I just didn't get how it would work at all.. I've never used tokenizer either so I'm not exactly what it does
0
 
objectsCommented:
> I've never used tokenizer either so I'm not exactly what it does

I have commented the code above.
0
 
SamooramadAuthor Commented:
ok i dont want to print it out. after saving values in the array i want to read them one at a time into another method that will use them to draw.
I'm still trying cehj's code but i'm having problems
0
 
SamooramadAuthor Commented:
I can't get past this problem
the method cehj posted so i could transfer my results to another file through a method gives me this error
Error #: 303 : 'this' cannot be referenced from a static context at line 423, column 6also the methos get does not work in the other file
I need to transfer my resulting integers to another file to put in a method one by one like with an index [i]
IT just wont work
0
 
objectsCommented:
> ok i dont want to print it out.

that was just as an example to show what it was doing :)

> after saving values in the array i want to read them one at a time into another method that will use them to draw

just pass the generated array to the method
0
 
objectsCommented:
> the method cehj posted so i could transfer my results to

which uses the same technique as I had suggested :)

> a method gives me this error

post the code u are currently using and i'll sort out the problem
0
 
CEHJCommented:
Make sure you are not calling instance methods from static methods
0
 
objectsCommented:
Thats not the problem, if you look at the error the problem is that 'this' is being used in a static method.
this cannot be used from a static method.
0
 
CEHJCommented:
It could well be the problem if they are are instance methods of classes that form instance variables
0
 
SamooramadAuthor Commented:
is there a way to transfer them without sing "this"?
0
 
CEHJCommented:
What is your class called? Have you create an instance of it?
0
 
objectsCommented:
this refers to the current object, a static method does not have a current object so it cannot be used.
One option would be to make the method not static. ie. remove the static keyword.
0
 
SamooramadAuthor Commented:
I'm using the code cehj posted exactly that way.. them i passed the list to set method and tried to "get" it from the other file. that did'nt work so i tried passing the integer values throught the methods after this line of code
 int firstInt = ((Integer)numbers.get(0)).intValue();
all the code I used was in the original file... the only thing I tried to was "Get" them in the other file then i got the error
"Spots.java": Error #: 300 : method getNumber() not found in class at line 400, column 62
0
 
objectsCommented:
What is it specifically you want to do, and how do you need it to fit into your code.
0
 
SamooramadAuthor Commented:
please help.. I'm a hopless case and I'm getting really frustrated. I've been working on this same bit for days and can't figure out how to fix it
0
 
SamooramadAuthor Commented:
the methods were static then i changed them.. what are they supposed to be?
0
 
objectsCommented:
can you post your code where you are trying to handle this
0
 
SamooramadAuthor Commented:
objects....
what does st.countTokens() do?
does it count the characters or something like that?
0
 
objectsCommented:
> what does st.countTokens() do?

It returns the number of token in the line, in this case it would be the number of integers.

Does your text file contain more than one line?

0
 
SamooramadAuthor Commented:
try {
        File file = new File(fileName);
        BufferedReader in = new BufferedReader(new FileReader(fileName));////add
        ArrayList numbers = new ArrayList();
        String str;

        while ((str = in.readLine()) != null) {
            process(str, numbers); }
        in.close();

        //jTextArea1.setText(new String(data, 0, chars_read));
    }
    catch (IOException e) {}
}
//////////////////////////////
public void process(String numberLine, java.util.List numbers) {
     StringTokenizer st = new StringTokenizer(numberLine);
     while(st.hasMoreTokens()) {
          numbers.add(new Integer(Integer.parseInt(st.nextToken().trim())));
     firstInt = ((Integer)numbers.get(0)).intValue();
     setNumber(firstInt);
     }
}


that is the code I'm using... I want to read the string from a file, separate into integers then take each integer into another file. I tried using a getNumber method that returns the value of the integer after i set it but the set and get methods don't seem to be visible in the other file
so in a nutshell everything i did including code and declarations and methods are in the first file
all i want to do in the second file is get the value of the integers one by one using an index if possible
0
 
SamooramadAuthor Commented:
it should only contain one line
0
 
CEHJCommented:
The method containing that try block should not be static
0
 
SamooramadAuthor Commented:
>>What is your class called? Have you create an instance of it?sorry cehj i just saw this comment

do you mean the file? visualize.java
0
 
objectsCommented:
try {
        File file = new File(fileName);
        BufferedReader in = new BufferedReader(new FileReader(fileName));////add
       StringTokenizer st = new StringTokenizer(in.readLine());

       // create array to store values

       int[] values = new int[st.countTokens()];
       int i = 0;

       // read ints from string and store in array

        while (st.hasMoreTokens()) values[i++] = Integer.parseInt(st.nextToken());

        in.close();

        // now do what you want with your int array.

    }
    catch (IOException e) {}
0
 
objectsCommented:
to loop thru the values in your array you would then use:

for (int i=0; i<values.length; i++)
{
   int value = values[i];
   // do as needed
}
0
 
CEHJCommented:
>>do you mean the file? visualize.java

If you've got a class called 'visualize' containing the try block you just posted, you should be creating an instance of it
0
 
objectsCommented:
import java.util.*;
import java.io.*;

public class ParseText
{
   public static void main(String[] args)
   {
     try
     {
        File file = new File(args[0]);
        BufferedReader in = new BufferedReader(new FileReader(file));
       StringTokenizer st = new StringTokenizer(in.readLine());

       // create array to store values

       int[] values = new int[st.countTokens()];
       int i = 0;

       // read ints from string and store in array

        while (st.hasMoreTokens()) values[i++] = Integer.parseInt(st.nextToken());

        in.close();

        // now do what you want with your int array.

    for (int i=0; i<values.length; i++)
   {
      int value = values[i];
      // do as needed
    }

    }
    catch (IOException e)
   {
      ex.printStackTrace();
   }
  }
}
0
 
SamooramadAuthor Commented:
>>The method containing that try block should not be static
it isn't... I just called it
void openfile(filename)
0
 
CEHJCommented:
OK. So in main you should have something like

visualize v = new visualize();
v.openFile(args[0]);
0
 
SamooramadAuthor Commented:
>>If you've got a class called 'visualize' containing the try block you just posted, you should be creating an instance of it
I'm not sure I know what you mean
0
 
objectsCommented:
the code you are using is unnecessarilt compilicated, you don't need to worry about using an ArrayList and can just use an int array.
0
 
SamooramadAuthor Commented:
objects
do i put "public class ParseText"
in a separate file or in my original file.. if so how do i get the other file to see int[] values ?
0
 
objectsCommented:
all you need is this:

try {
        BufferedReader in = new BufferedReader(new FileReader(fileName));
       StringTokenizer st = new StringTokenizer(in.readLine());

       // create array to store values

       int[] values = new int[st.countTokens()];
       int i = 0;

       // read ints from string and store in array

        while (st.hasMoreTokens()) values[i++] = Integer.parseInt(st.nextToken());

        in.close();

     setNumber(values[0]);
    }
    catch (IOException e) {}
0
 
SamooramadAuthor Commented:
>>OK. So in main you should have something like
but my main is in a completly different file... does that make any difference?
0
 
objectsCommented:
> do i put "public class ParseText"
> in a separate file or in my original file..

That should be put in a seperate file and was just intended as an example as i don't have your code to see how to incorporate it.
The code above that i just posted should drop into your class.
0
 
objectsCommented:
> but my main is in a completly different file... does that make any difference?

Certainly does, not sure why he suggested that.
How do you call this method?
0
 
CEHJCommented:
The following is a runnable version of the code you posted. See the comment in capitals:

import java.io.*;
import java.util.*;

public class visualize {

      public static void main(String[] args) {
            visualize v = new visualize();
            v.openFile(args[0]);
      }

      public void openFile(String fileName) {
            try {
                  File file = new File(fileName);
                  BufferedReader in = new BufferedReader(new FileReader(fileName));
                  ////add
                  ArrayList numbers = new ArrayList();
                  String str;
                  while ((str = in.readLine()) != null) {
                        process(str, numbers);
                  }
                  in.close();

            }
            catch (IOException e) {
                  e.printStackTrace();
            }
      }

      public void process(String numberLine, java.util.List numbers) {
            StringTokenizer st = new StringTokenizer(numberLine);
            while (st.hasMoreTokens()) {
                  numbers.add(new Integer(Integer.parseInt(st.nextToken().trim())));
                  int firstInt = ((Integer) numbers.get(0)).intValue();
                  // DO YOUR SET NUMBER HERE
                  //setNumber(firstInt);
                  System.out.println(firstInt);
                  
            }
      }

}
0
 
SamooramadAuthor Commented:
>>setNumber(values[0]);
how do i write set method without using " this"? that was causing another error
0
 
objectsCommented:
> how do i write set method without using " this"?

make your method non-static.
0
 
objectsCommented:
eg.

public void openFile(String fileName)
{
try {
        BufferedReader in = new BufferedReader(new FileReader(fileName));
       StringTokenizer st = new StringTokenizer(in.readLine());

       // create array to store values

       int[] values = new int[st.countTokens()];
       int i = 0;

       // read ints from string and store in array

        while (st.hasMoreTokens()) values[i++] = Integer.parseInt(st.nextToken());

        in.close();

     setNumber(values[0]);
    }
    catch (IOException e) {}
}
0
 
SamooramadAuthor Commented:
ok so say the file with main is called fileone...all this has is a few basic lines
then there is filetwo where i have the code you wrote and the bulk of my program...this is where i want to open file and read and turn into integers
then in filethree which is incharge of the drawing part all i want is to get the integer values i got as a result of code in filetwo
0
 
CEHJCommented:
btw, why are you interested in them being integers?
0
 
SamooramadAuthor Commented:
>> make your method non-static
i did
0
 
objectsCommented:
>>> make your method non-static
>i did

post the error, and your method.
0
 
SamooramadAuthor Commented:
>>btw, why are you interested in them being integers?
 the code written for drawing only accepts integers as values..thats why i need to pass integers
0
 
SamooramadAuthor Commented:
I still get
Error #: 300 : method getNumbers() not found in class Spots at line 400, column 62
spots is the applet I'm trying to pass the integer to
are getNumber and setNumber supposed to be written in a specific way?
0
 
objectsCommented:
> Error #: 300 : method getNumbers() not found in class Spots at line 400, column 62

then you need a reference to your Spots instance and use:

spots.setNumber(values[0]);
0
 
SamooramadAuthor Commented:
//methods to get and set
 public void setNumber(int number) {
     this.number = number;
}
 public int getNumber() {
     return number;
}
0
 
objectsCommented:
if it isn't already available as a member variable in that class then you could possibly also pass it as a parameter to the method:

public void openFile(Spots spots, String fileName)
{
   ...

0
 
SamooramadAuthor Commented:
>>then you need a reference to your Spots instance and use:

spots.setNumber(values[0]);
what about get? which happens inside spots?
0
 
SamooramadAuthor Commented:
>>then you need a reference to your Spots instance and use:

spots.setNumber(values[0]);
now i get this error:
Error #: 300 : method setNumber(int) not found in class java.applet.Applet at line 413, column 12
0
 
SamooramadAuthor Commented:
also got
"Spots.java": Error #: 300 : method getNumbers() not found in class Spots at line 400, column 62
0
 
objectsCommented:
Where is spots variable declared?
0
 
SamooramadAuthor Commented:
public void openFile(Spots spots, String fileName)
{

didn't work
do i need to put the set and get methods in the second file instead of the first?
0
 
SamooramadAuthor Commented:
Where is spots variable declared?
thats the name of the second file(the applet)
i have it declared at the begining of the first file (visualize)
as Applet Spots = new Spots();
0
 
objectsCommented:
> Applet Spots = new Spots();

change that to:

Spots spots = new Spots();
0
 
SamooramadAuthor Commented:
Spots spots = new Spots();
did that and spots.setNumber(values[0]);
still get
Error #: 300 : method setNumber(int) not found in class visualizer.Spots at line 414, column 12
0
 
objectsCommented:
can u post your spots class, that error is saying it does not have a setNumber() method but earlier you said it did.
0
 
SamooramadAuthor Commented:
its very long..do u want me to post it all?
0
 
objectsCommented:
ok, just post the setNumber() method.
0
 
SamooramadAuthor Commented:
node._node(vertices[i].x -10,vertices[i].y-10,getNumbers(),vertices[i].c,vertices[i].c2,g);

this is the line in spots i want to pass the integer to
it calls a method "node" inside the classs "node" and i want to pass the integer where get numbers is
0
 
SamooramadAuthor Commented:
i didn't put setNumber in spots
just in visualize file where the openfile code u posted is
i only want to use getNumber in spots
0
 
SamooramadAuthor Commented:
public void setNumber(int number) {
     this.number = number;}

 public int getNumber() {
     return number;
}
0
 
objectsCommented:
if setNumber is in visualize then just use:

setNumber(values[0]);

Then in your spot class you will need to have a visulaize instance to call getNumber():

int i = myvisualize.getNumber();
0
 
SamooramadAuthor Commented:


int number;

public void setNumber(int number) {
     this.number = number;}

 public int getNumber() {
     return number;
}
0
 
SamooramadAuthor Commented:
ok
is it right to have the get and set methods in visualize and not in spots? or is that causing some problem?
0
 
SamooramadAuthor Commented:
>>Then in your spot class you will need to have a visulaize instance to call getNumber():
so
visualize myvisualize = new visualize();
then
int i = myvisualize.getNumber();

like that?
0
 
objectsCommented:
> like that?

no

> is it right to have the get and set methods in visualize and not in spots?

its hard to say without knowing more about your design.
But from what you've stated in this question it would seem more appropriate to have it in the Spots class.
eg. move the following from visualize to spots:

int number;

public void setNumber(int number) {
     this.number = number;}

 public int getNumber() {
     return number;
}
0
 
vishalbhandoCommented:
This will solve your problem..


Reader r = new BufferedReader(new InputStreamReader(new FileIntputStream("yourFileName")));
StreamTokenizer st = new StreamTokenizer(r);
int tokenType=0;
while((tokenType=st.nextToken())!=StreamTokenizer.TT_EOF){
      if(tokenType==StreamTokenizer.TT_NUMBER){
      System.out.print((int)st.nval);
      }
}
0
 
CEHJCommented:
8-)
0
 
SamooramadAuthor Commented:
it finally woked! thanks
0
 
SamooramadAuthor Commented:
uuh worked
0
 
objectsCommented:
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 52
  • 32
  • 25
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now