> Hi all i have used the Scanner to check if this token
> is string or integer
> how can i make this checking for the whole file and
> why when i save it to a file it keep repeating the
> info
You've got an error in your code. Show the code, especially the part that prints the string, and we'll probably be able to show you the error.
My guess is that you have a loop where you read your input into a string and then use that string to write to a file. In all likelihood, you are not re-initializing that string at the top of the loop, but without code, I have no earthly idea.
Also, look at lots of sample code, especially the Sun Java tutorials and try to emulate it.
Here is the code which give multiple answer for one line, and when i try to add it to the whole file it gives milloins of lines
Kindly check it and tell me why
while((line = in.readLine() ) != null){
String st = "Mary 33 London 410";
Scanner sc = new Scanner(st);
while (sc.hasNext() )
{
if (sc.hasNextInt())
{
int number = sc.nextInt();
target+=number+" ";
}
else
{
String str = sc.next();
System.out.println("string: " + str);
target += str + "" ;
}
Sorry the scanner do check the given line read by the while loop
here is the correct code
at the checking of string there is a call for a function that converts these string to a number
i.e if i start with 'Mary 33 London 410";
i'll end up with
10 33 25 410
this will be done for all the lines in the file
while((line = in.readLine() ) != null){
Scanner sc = new Scanner(line);
while (sc.hasNext() )
{
if (sc.hasNextInt())
{
int number = sc.nextInt();
target+=number+" ";
}
else
{
String str = sc.next();
System.out.println"string: " + str);
target += convert(str) + "" ;
}
Message was edited by:
TheNewLeader
Hi all
i have used the link but there is a prolbem when i call the convert
which make use of Map
it cuase a null pointer
In the Map i sotre the word and a number next to it
the converstion was working ok, with the noraml while and read line
but when i used the scan to differencaite between intger and string it gives me an erorr
any ideas?
if (sc.hasNextInt())
{
int number = sc.nextInt();
target+=number+" ";
}
else
{
String str = sc.next();
System.out.println"string: " + str);
target += convert(str) + "" ;
}
no
if you had read the prevoius pages you will find that i had a call convert
function that convert text to number that i want
the problem is that the scanner do just write the last values of the last line
why and how can i make it write every thing in the while file
here is the code
Scanner sc = null;
try {
sc = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
int number=0 ;
String str ="";
while (sc.hasNext() )
{
if (sc.hasNextInt())
{
int number = sc.nextInt();
System.out.println("number: " + number);
target+=number+" ";
}
else
{
String str = sc.next();
System.out.println("string: " + str);
target += convert(str) ;
}
target += convert(str) + " " +number+" ";
}// while scanner
target+="**********NEW LINE********** ";
}finally {
if (sc != null) {
sc.close();
}
What are you trying to do here:
> >else
>{
> String str = sc.next();
> System.out.println("string: " + str);
> target += convert(str) ;
>}
>
> target += convert(str) + " " +number+" ";
>}// while scanner
>
>}
?
It almost looks like you're trying to convert non-numeric input into a number, which will fail of course.
Are you trying to write to a file? Also, what does your input file look like?
What does (do?) your desired output file (files?) look like?
something like this has worked for me:
import java.io.*;
import java.util.*;
class ScannerTest
{
// the following strings would change for your program
private static String inputFileName = ".\\petes\\brief2\\infile.txt";
private static String outputStringFileName = ".\\petes\\brief2\\outstrfile.txt";
private static String outputNumberFileName = ".\\petes\\brief2\\outnumfile.txt";
private static int total = 0;
private static void extractFileData() throws IOException
{
Scanner scan = null;
BufferedWriter textBufferedWriter = null;
BufferedWriter integerBufferedWriter = null;
int inputInt = 0;
String inputString = "";
try
{
scan = new Scanner(
new BufferedReader(new FileReader(inputFileName)));
textBufferedWriter = new BufferedWriter(
new FileWriter(outputStringFileName));
integerBufferedWriter = new BufferedWriter(
new FileWriter(outputNumberFileName));
while (scan.hasNext())
{
if (scan.hasNextInt())
{
inputInt = scan.nextInt();
total += inputInt;
integerBufferedWriter.write(String.valueOf(inputInt) + " ");
}
else
{
inputString = scan.next() + " ";
textBufferedWriter.write(inputString);
}
}
textBufferedWriter.write("The sum of ints is: " + String.valueOf(total));
textBufferedWriter.flush();
integerBufferedWriter.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
scan.close();
textBufferedWriter.close();
integerBufferedWriter.close();
}
}
public static void main(String[] args) throws IOException
{
extractFileData();
}
}
Yes am writing to file
No it want fail and i was able to convert non-numeric input into a number,
after that i want to have the result of each line in a sperate line
what i'm getting now is the last 2 values of the last line
how can i write every thing each in a row that its come from
i.e
20 100 30 40
150 30 55 47
> something like this has worked for me:
> > import java.io.*;
> import java.util.*;
>
> class ScannerTest
> {
> // the following strings would change for your
> program
> private static String inputFileName =
> ".\\petes\\brief2\\infile.txt";
> private static String outputStringFileName =
> ".\\petes\\brief2\\outstrfile.txt";
> private static String outputNumberFileName =
> ".\\petes\\brief2\\outnumfile.txt";
>
>
>private static int total = 0;
> private static void extractFileData() throws
> IOException
>{
>Scanner scan = null;
>BufferedWriter textBufferedWriter = null;
>BufferedWriter integerBufferedWriter = null;
>
>int inputInt = 0;
>String inputString = "";
>try
>{
> scan = new Scanner(
> new BufferedReader(new
> FileReader(inputFileName)));
>textBufferedWriter = new BufferedWriter(
> new FileWriter(outputStringFileName));
>integerBufferedWriter = new BufferedWriter(
> new
> FileWriter(outputNumberFileName));
> while (scan.hasNext())
> {
>if (scan.hasNextInt())
> {
> inputInt = scan.nextInt();
> total += inputInt;
>
> ntegerBufferedWriter.write(String.valueOf(inputInt) +
> " ");
>}
> else
>{
>inputString = scan.next() + " ";
>
> extBufferedWriter.write(inputString);
>}
>
> textBufferedWriter.write("The sum of ints is: " +
> String.valueOf(total));
>textBufferedWriter.flush();
> integerBufferedWriter.flush();
>
> catch (IOException e)
> {
> e.printStackTrace();
>finally
> {
>scan.close();
> textBufferedWriter.close();
>integerBufferedWriter.close();
>
> public static void main(String[] args) throws
> IOException
>{
>extractFileData();
>
> }
>
What are you trying to do here:
>
>else
>{
> String str = sc.next();
> System.out.println("string: " + str);
> target += convert(str) ;
>}
>
> target += convert(str) + " " +number+" ";
>}// while scanner
>
>}
?
It almost looks like you're trying to convert non-numeric input into a number, which will fail of course.
Are you trying to write to a file? Also, what does your input file look like?
What does (do?) your desired output file (files?) look like?
what you have suggest is to separate the result text alone and numbers alone
i don't want that
wheni have
Mary 20 Kids 2
John 40 kids 5
and after conversion i want to write this to one file
100 20 300 2
500 40 11 5
the converstion function is done
the problem with scanner it just save for me from above just
11 and 5
where are the rest of data?
hope this make things clear
> wheni have
> Mary 20 Kids 2
> John 40 kids 5
>
> and after conversion i want to write this to one
> file
> 100 20 300 2
> 500 40 11 5
How does:
Mary become 100
Kids (first one) become 300
John become 500
and
kids (second one) become 11
?
I would like to know how this "conversion" function that translates a string to a number works.
And where is the code that writes something to a file?
By the way, the problem with your output only showing the last line has nothing to do with the scanner and everything to do with how you are writing your output to file. That is why it is important to see your code for this.
Message was edited by:
petes1234
it is not giving me each time an output
but i can't see all the pages so i did post any number
i use a double array and search if this word is find then replace it with the corresponding number
eazy ha
then what in my code and writing to file i have error and not allow me to write each line in a separte line and all the data not just the last 2
even that was not my question
but here is the code
i think that the error in sending data to file
coz it just take the last value not all the values
try {
outT = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("C:/out.txt",true),
enc)) );
String target="";
Scanner sc = null;
try {
sc = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
int number=0 ;
while (sc.hasNext() )
{
//CHECK IF number
if (sc.hasNextInt())
{
int number = sc.nextInt();
System.out.println("number: " + number);
target+=number+" ";
}
// .... and so............
else
{
String str = sc.next();
System.out.println("string: " + str);
target+=str+" ";
}
//this is the line that does not work proply
target += " "+convert(str) + " " +number+" ";
}// while scanner
}finally {
if (sc != null) {
sc.close();
}
outT.println(target);
}
outT.close();
If you haven't done so, please do a careful check on each time you use the String variable target. I see that you are carefully making sure that you append to this variable with the "+=" operator rather than overwrite with the "=" operator. Is there any chance that somewhere in your code you either redeclare the variable or use target = xxx rather than target += xxx? I have a feeling that somewhere you are deleting everything in this variable just prior to it's receiving the last line of the file.
Also, consider switching from the String variable target to a StringBuilder. It's less resource-hungry, and you explicitly append to it rather than assign to it, so it is harder to make the mistake of using = for +=. Something like this:
StringBuffer targetStrBuf = new StringBuffer();
while (sc.hasNext())
if (sc.hasNextInt())
{
int number = sc.nextInt();
targetStrBuf.append(number + " ");
}
else
{
String str = sc.next();
targetStrBuf.append(convert(str) + " ");
}
....
....
outT.printLn(targetStrBuf.toString());
outT.flush();
outT.close()
/** note that this code has not been tested! **/
Or something like that...
Hi
i did check my code i don't have target define else where
may i ask what is resource-hungry in
(Also, consider switching from the String variable target to a StringBuilder. It's less resource-hungry, and you explicitly append to it rather than assign to it, so it is harder to make the mistake of using = for +=. Something like this:
)
> Hi
> i did check my code i don't have target define else
> where
> may i ask what is resource-hungry in
> (Also, consider switching from the String variable
> target to a StringBuilder. It's less resource-hungry,
> and you explicitly append to it rather than assign to
> it, so it is harder to make the mistake of using =
> for +=. Something like this:
> )
Actually for most purposes, doing String concatenations with + or += is just fine and has minimal performance hits compared with StringBuilder. The exception comes when you are doing many (i.e., thousands) of string concatenations within a loop, which is possible in your program if the input file is big enough. When that occurs, (I have been led to believe) StringBuilder is more efficient and requires initialization of fewer objects than concatenating String.
If anyone know differently, please pipe in!
Check out the Sun tutorial on [url=http://java.sun.com/docs/books/tutorial/java/data/buffers.html]StringBuilder class[/url]. In it they mention that:
Strings should always be used unless string builders offer an advantage in terms of simpler code (see the sample program at the end of this section) or better performance. For example, if you need to concatenate a large number of strings, appending to a StringBuilder object is more efficient.
To clarify (I hope) + is fine for simple concatenation in terms of easy to type but Strings in Java are immutable (not changeable) and the + does not magically make this not so.
What does this mean? It means, that + is converted by the compiler into a StringBuffer (or StringBuilder starting with 1.5) and various append method calls are made as needed. Followed by a toString.
If you take the following example code
public class Test{
public static void main(String args[]){
String a = "Hello";
String b = "World";
String helloWorld = a+" "+b;
System.out.println(helloWorld);
}
}
Compile it.
Then use javap - The Java Class File Disassembler -http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javap.html
javap -c Test
Here is the output
Compiled from "Test.java"
public class Test extends java.lang.Object{
public Test();
Code:
0:aload_0
1:invokespecial#1; //Method java/lang/Object."<init>":()V
4:return
public static void main(java.lang.String[]);
Code:
0:ldc#2; //String Hello
2:astore_1
3:ldc#3; //String World
5:astore_2
6:new#4; //class java/lang/StringBuilder
9:dup
10: invokespecial#5; //Method java/lang/StringBuilder."<init>":()V
13: aload_1
14: invokevirtual#6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
17: ldc#7; //String
19: invokevirtual#6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
22: aload_2
23: invokevirtual#6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
26: invokevirtual#8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
29: astore_3
30: getstatic#9; //Field java/lang/System.out:Ljava/io/PrintStream;
33: aload_3
34: invokevirtual#10; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
37: return
}
You can see what the compiler actually turned the code into.
> > but Strings in Java are immutable (not
> changeable)
>
> georgemc accused me of having a PERL script that
> found this sort of thing. I swear, I'm just running
> into it by accident. :o)
>
> ~
:blink: ?
Sorry I don't understand this. I know it's some sort of joke...
> > You can see what the compiler actually turned the
> > code into.
>
> well, I'll be dmned! Thanks again, cotton.m
You're welcome.
I should probably expand for other readers and say this. While the compiler was smart enough to only use the one StribgBuilder there this runs into a problem when you have a loop. In that scenario each loop iteration is creating a new StringBuilder object and in that scenario you
are better off to have a StringBuilder scoped outside the loop that you append to inside the loop.
> > Sorry I don't understand this. I know it's some
> sort of joke...
>
> http://forum.java.sun.com/thread.jspa?threadID=5179587
>
> http://forum.java.sun.com/thread.jspa?threadID=5177927
>
>
> ~
I see. I think you are evil. :p
Hi
i did use StringBuilder while ago but it suffer from a problem
that the println is not taken any action i.e not shown in the output file
for example if i have these 2 lines
10 300 50 14
30 80 99 47
then they will be in the output file as 1 line
10 300 50 14 30 80 99 47
i don't know why
even when i tried
out.print("\n")
it did not work too
I use this code , theoutT.printLn(targetStrBuf.toString());
does not accept the newline and write all the data together
StringBuffer targetStrBuf = new StringBuffer();
while (sc.hasNext())
if (sc.hasNextInt())
{
int number = sc.nextInt();
targetStrBuf.append(number + " ");
}
else
{
String str = sc.next();
targetStrBuf.append(convert(str) + " ");
}
outT.printLn(targetStrBuf.toString());
outT.flush();
outT.close()
> I use this code
If you're not willing to follow advice or provide necessary information, why should anyone bother to help you? The code you posted is neither self-contained nor compileable. I say again, please post an [url=http://mindprod.com/jgloss/sscce.html]SSCCE[/url] that actually demonstrates the problem. Assume we only have the core API.
~
The code i have post was complied and tested
then how do i say that the output was not comming correct
the problem with buffer since prinln does not print new line
Here is the code again
void convertFile(){
try {
outT = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("C:/Word.txt",true),
enc)) );
/**************************************************/
BufferedReader in =
new BufferedReader(
new InputStreamReader(
new FileInputStream(inputFilename),
enc));
Scanner sc = null;
try {
sc = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
/**************************************************/
StringBuffer targetStrBuf = new StringBuffer();
while (sc.hasNext())
if (sc.hasNextInt())
{
int number = sc.nextInt();
targetStrBuf.append(number + " ");
}
else
{
String str = sc.next();
targetStrBuf.append(convert(str) + " ");
}
/*i have tried to put "\n" here put it didnt word*/
outT.println(targetStrBuf.toString());
outT.flush();
outT.close();
/**************************************************/
}finally {
if (sc != null) {
}
}//while for line
sc.close();
outT.print("\n");
outT.flush();
outT.close();
in.close();
outT.close();
}//try
catch (IOException exc)
{
System.err.println("I/O error writing to output file.");
}
}
Message was edited by:
TheNewLeader
i did read that SCCE
Example - Displays the problem you are trying to solve.
if i have
mary 20 Major 40
John 30 Major 30
that code does convert all the above line to numbers and write them in one line, where mary is 100 major is 400 and john is 200
i.e.
100 20 400 40 200 30 400 30
i want it to be like this
100 20 400 40
200 30 400 30
i tried to put the \r\n before the stringBuffer and with it but no action was there
hope this make it clear