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();
}
}
#
> 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>
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[i]=stz.nextToken();
System.out.println(str1[i]);
i++;
}
catch(Exception e)
{
}
}
}
}
Message was edited by:
qUesT_foR_knOwLeDge
> 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 dojava Prog data1.txtthen the String array called args will hold the String "data1.txt" at it's first (and only) index. Soargs[0] -> "data1.txt"
.
You can create a Scanner object from the command line arguments:// ...
Scanner scan = new Scanner(new File(args[0]));
// ...
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();
#
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
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>