Help with my mess...using multiple delimiters and string splits...
Alright what I need to do is take a text file that contains data formatted as so:
5
4 + 2 i
-5 + -23 i
etc...
And what I need to do is read in these complex numbers into my program and then separate them so they will read as 4 2 so that I can compare the 2 integers to determine in which quadrants each complex number falls in.
As of last night I was sure that I had managed to remove both the plus sign and i from each line, but when I ran my code today either the + or the i remains in each line, and I still cant figure out how to compare the two integers....any help would be greatly appreciated...
my code so far is as follows: and as you can see its pretty much a mess as I do not really understand what I am doing...
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.*;
import java.lang.*;
import java.util.regex.*;
public class ComplexCatalog1b {
public static void main(String[] args) {
File file = new File("complex.txt");
Scanner scanner = null;
String part = null;
try {
//
// Here we use the Scanner class to read file content line-by-line.
//
scanner = new Scanner(file);
scanner.nextLine();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//
// From the above line of code we got a line from the file
// content. Now we want to split the line with "+" and the "i" as the
// charater delimiters.
//
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter("\\+"); //sets delimiter "+"
lineScanner.useDelimiter("i"); //sets delimiter "i"
while (lineScanner.hasNext())
{
//
// Get each splited data from the Scanner object and prints
// the value.
//
part = lineScanner.next();
System.out.print(part);
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Maybe you can help me understand this...
In my code I wrote a segment that would hopefully take the first part of the complex number, for example, 1 + 2 i, and would convert it from a string to and integer.
String realPart = lineScanner.next();
int realValue = Integer.parseInt(realPart);
What this does is it throws a :
java.lang.NumberFormatException: For input string: "1" at java.lang.NumberFormatException.forInputString(Num berFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:458)
at java.lang.Integer.parseInt(Integer.java:499)
at ComplexScanner.main(ComplexScanner.java:56)