-1

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?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
rburrus
  • 19
  • 2
  • 1
    You sure, that the file is named `imput.txt` instead of `input.txt` – marpme May 13 '17 at 08:37
  • The exact cause of your code dying is probably just that the scanner ran out of things to read, yet your code kept calling `nextLine()`. Beyond that, you are comparing strings using `==`, which is wrong; you should use `String#equals()`. – Tim Biegeleisen May 13 '17 at 08:37

1 Answers1

0

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();
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97