I am new to JAVA and this forum and am trying to figure out an issue with a project that classifies triangles from three sides given in a file. The file can be multiple different lines (multiple triangles), lines must start with '#' to be considered valid by the program, and can have superfluous data of varying types after the three sides are listed. For reference here is a sample input file and the corresponding output file that should be made when the program runs. input/output reference. I feel pretty confident in the majority of my program but the specific issue i'm having is dealing with the input file in my main method. I don't understand a) how to get the program to recognize only lines starting with '#' as valid input. b) how to get to the next Scanner token after '#' and assign those three to sides 1-3 only if they are integers (they don't necessarily have to be). c) how to assign the remaining data after the sides, if there is any, to a String variable. If there are any helpful Scanner methods that you know of that can assist me I would be greatly appreciative. Reading through the JAVA API is still Greek to me. The biggest thing is if there is a method that returns what the data type of the current token is, I keep getting InputMismatchException from trying to assign non-integers to my sides. Finally here is my main method that keeps plaguing me. Again thank you for any insight you can provide.
public static void main (String[] args) throws FileNotFoundException, IOException
{
String input, output;
int side1 = 0, side2 = 0, side3 = 0, lineCounter = 1;
String irrelevant;
File inputFile;
Scanner inputRead = null;
System.out.println("Please choose the .txt file you would like to use for triangle side input.");
input = fileSelect();
System.out.println("Please choose the .txt file you would like to use as the program output file.");
output = fileSelect();
FileWrite outputFile = new FileWrite();
outputFile.fileCreate(output);
inputFile = new File(input);
try
{
inputRead = new Scanner(inputFile);
}
catch (FileNotFoundException e)
{
System.out.println("No file or unsupported file found: Please choose another input file.");
input = fileSelect();
}
while (inputRead.hasNextLine())
{
String line = inputRead.nextLine();
while (line != null)
{
if(inputRead.hasNext("#"))
{
side1 = inputRead.nextInt();
side2 = inputRead.nextInt();
side3 = inputRead.nextInt();
irrelevant = inputRead.next();
areaCalc(side1, side2, side3, lineCounter, output);
}
lineCounter ++;
}
}
if (!inputRead.hasNext())
{
}
inputRead.close();
}
How about doing line parsing like below
try {
String content[] = line.split(" ");
if(content.length > 3) {
if(content[0].equals("#")) {
int side1 = Integer.valueOf(content[1]);
int side2 = Integer.valueOf(content[2]);
int side3 = Integer.valueOf(content[3]);
if(side1 > 0 && side2 > 0 && side3 > 0) {
areaCalc(side1, side2, side3, lineCounter, output);
}
}
}
}catch(NumberFormatException e){}