I am writing a program that determines the type of triangle based on the length of its sides which is provided using a separate .txt file. My code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class triangle {
static String a; //first side
static String b; //second side
static String c; //third side
private static Scanner sc;
public static void main(String[] args) {
try {
sc = new Scanner(new File("imput.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(sc.hasNextInt())
a = sc.nextLine();
b = sc.nextLine();
c = sc.nextLine();
if(a == b && a == c)
System.out.println("Equilateral");
else if(a != b || a != c)
System.out.println("Isocelese");
else if(a != b && a != c)
System.out.println("Scalene");
else
System.out.println("Not a Triangle");
}
}
I have confirmed that the filepath to the input file is correct and my program is able to successfully compile, however when the program is run I receive this error:
Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Unknown Source) at triangle.main(triangle.java:41)
What can I do to get my program to properly read the input file?
You are omitting braces {} in the while body, this cause that the only statement that in the while loop is the assignment of the variable a
The scanner is consuming the hole info rewriting over and over again the variable a, once the scanned has no next you exit the while and try to get the next line trying to assign the variable b, that causes the NoSuchElementException
your problem:
while (sc.hasNextInt())
a = sc.nextLine();
b = sc.nextLine();
c = sc.nextLine();
what you need to do:
while (sc.hasNextInt()){
a = sc.nextLine();
b = sc.nextLine();
c = sc.nextLine();
}