14 Replies Latest reply: Mar 3, 2007 8:33 PM by 807606 RSS

    Taking an int out from a string

    807606
      Hi,

      I got a scanner reading in a string.
      eg: 1+2     *3

      I need to read out the numbers out from the string so i can store them into an array. How do i do so? Many thanks.
        • 1. Re: Taking an int out from a string
          807606
          I forgot to add, it has no spacing between the operands and operators
          so scanner.nextInt() does not work.
          • 2. Re: Taking an int out from a string
            807606
            Try
            package testing;
            import java.util.Scanner;
            public class Test
            {
              public static void main(String[] args)
              {
                String s = "10+2*3=16";
                Scanner scan = new Scanner(s).useDelimiter("\\D"); // <- \\D for non-digit
                while (scan.hasNextInt())
                  System.out.println(scan.nextInt());
                scan.close();
              }
            }
            #
            • 3. Re: Taking an int out from a string
              807606
              Hi, the code doesnt work for the standard input channel. It doesnt display anything.

              I have a text file and input it in the command prompt like..
              java Prog <data1.txt
              • 4. Re: Taking an int out from a string
                800282
                Hi, the code doesnt work for the standard input
                channel. It doesnt display anything.

                I have a text file and input it in the command prompt
                like..
                java Prog <data1.txt
                Then use the command line arguments (String[] args) instead of the String s. Look at the Scanner class to see if there's a constructor which take a file:
                http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html
                • 5. Re: Taking an int out from a string
                  807606
                  My instructions insists i use the scanner class as there's a difference in the format of inputting files between using args[] and scanner class.

                  Is there other ways I can use the delimiter on a string instead of a scanner?
                  • 6. Re: Taking an int out from a string
                    807606
                    import java.util.*;
                    
                    
                    
                    public class StringToken
                    {
                         public static void main(String args[])
                         {
                              String str="1+2*3";
                                 
                              StringTokenizer stz=new StringTokenizer(str,"+-*/");
                                     String str1=new String[stz.countTokens()];
                                     int i=0;
                              System.out.println(stz.countTokens());
                    
                              while(stz.hasMoreTokens())
                              {     
                                   try
                                   {
                                                     str1=stz.nextToken();
                                        System.out.println(str1[i]);
                    i++;
                                   }
                                   catch(Exception e)
                                   {
                                   }
                              }
                         }
                    }


                    Message was edited by:
                    qUesT_foR_knOwLeDge
                    • 7. Re: Taking an int out from a string
                      800282
                      My instructions insists i use the scanner class as
                      there's a difference in the format of inputting files
                      between using args[] and scanner class.

                      Is there other ways I can use the delimiter on a
                      string instead of a scanner?
                      No, you misunderstood. If you do
                      java Prog data1.txt
                      then the String array called args will hold the String "data1.txt" at it's first (and only) index. So
                      args[0] -> "data1.txt"
                      .
                      You can create a Scanner object from the command line arguments:
                      // ...
                      Scanner scan = new Scanner(new File(args[0]));
                      // ...
                      • 8. Re: Taking an int out from a string
                        807606
                        Try this for ideas
                        Scanner scan = new Scanner(new File("filename"));
                        while (scan.hasNextLine())
                        {
                          String[] array = scan.nextLine().split("\\D");
                          for (int i = 0; i < array.length; ++i)
                            System.out.print(array[i] + (i == array.length - 1 ? "\n" : " "));
                        }
                        scan.close();
                        #
                        • 9. Re: Taking an int out from a string
                          807606
                          Error: cannot find symbol
                          symbol : class File
                          when i try to use new File
                          • 10. Re: Taking an int out from a string
                            807606
                            Error: cannot find symbol
                            symbol : class File
                            when i try to use new File
                            import the java.io.File package

                            Add this to the code
                            import java.io.*;
                            • 11. Re: Taking an int out from a string
                              807606
                              ok guys, the delimiter works now.
                              unfortunately, when i pass this value in 1+2 <2 white spaces> *3-4/2+5*6
                              It appears to take in as "1+2-3/4+2*5"

                              Is the white spaces in the equation causing the - and / sign to mix up?

                              Message was edited by:
                              javaPOTATO
                              • 12. Re: Taking an int out from a string
                                807606
                                There are too many solutions here for me to guess which one you have employed.
                                • 13. Re: Taking an int out from a string
                                  807606
                                  Sorry. This is what i did.

                                  public static void cuthemintopieces(String Line){
                                  Scanner token = new Scanner(Line).useDelimiter("\\s");
                                  Scanner operands = new Scanner(Line).useDelimiter("\\D");
                                  Vector<String> aLine = new Vector<String>();

                                  while(token.hasNext()){
                                  String line = token.next();

                                  for(int i=0; i<line.length(); i++){ //to cycle through char by char in each  token

                                  char sent = line.charAt(i);
                                  switch(sent){
                                  case '+': ....//add to vectorlist
                                  case '-': .....all the way to case '/'
                                  default: String num = operands.next(); //add numbers
                                  • 14. Re: Taking an int out from a string
                                    807606
                                    Got the solution by placing the scanner operand inside the loop.
                                    Thanks all for helping.
                                    Will give duckbill the stars because the solving point of my initial question was useDelimiter("\\D")