PDA

View Full Version : useDelimiter Help (Last time, promise :P)




Maleficum
Dec 14, 2006, 06:12 PM
My predicament of the day is a lack of correspondence between my file and my Scanner methods. The point of the code is to remove the "-" in the data file, then add the numbers after using the method useDelimiter.

Lab12C.Dat:
7
22-11-22-11-22
1-2-3-4-5-6
90-100-90
1000-232
1-1-1-21-1-1-111-9999-1
9-9-9-9-9-9-9-9-9-9-9-9-9-9-9-9
1


Lab12C:

//Name -
//Date -
//Lab -

import java.io.IOException;
import java.io.File;
import java.util.Scanner;
import static java.lang.System.*;

class Social
{
private String socialNum;
private int sum;

public Social()
{
socialNum="";
sum = 0;

}

public Social(String soc)
{
socialNum = soc;
sum = 0;

}

public void setWord(String w)
{
socialNum=w;
setWord(w);

}

public void chopAndAdd()
{

Scanner g = new Scanner(socialNum);

for(int i = 0; i<socialNum.length(); i++)
{
socialNum.useDelimiter("-");
sum = sum+g.nextInt();

System.out.println(sum);
}


}

public String toString()
{
return "";
}
}

public class Lab12c
{
public static void main( String args[] ) throws IOException
{

Scanner file = new Scanner(new File("lab12c.dat"));
int size = file.nextInt();
file.nextLine();
for(int i=0; i<size; i++)
{
String line = file.nextLine();
Social test = new Social(line);
test.chopAndAdd();
System.out.println(test);
}









}
}



Any help is greatly appreciated!



MacFan26
Dec 19, 2006, 05:34 PM
If the point was to use the useDelimeter method in Scanner, you need to use

g.useDelimiter("-"); instead of socialNum.useDelimiter("-");

Also, then comment out this line:

int size = file.nextInt();
//file.nextLine();

Since nextInt() will move it to the next line.

Finally:
Use while (g.hasNext())
Instead of for (int i = 0; i < socialNum.length(); i++)

Because you don't want to do that for the number of characters that are in the socialNum string, only while there more integers on the line.

Hope that makes sense :)

HiRez
Dec 19, 2006, 10:45 PM
Also, I think you'd want to move the useDelimiter line outside of the loop. Things that don't need to be called every pass through a loop, shouldn't be in the loop.

bozigle
Dec 20, 2006, 01:56 AM
I'm not sure what is really meant... and i kind of gave up on trying to make sense to what coders mean... including myself

public void chopAndAdd(){
StringTokenizer st = new StringTokenizer(socialNum,"-");
sum=0;
while (st.hasMoreTokens())
sum += Integer.parseInt(st.nextToken());
System.out.println(sum);
}



other things aside, setWord() is recursive with no condition --> infinite loop