Ask Question

You coded the following class:

try

{

Scanner file = new Scanner (new File ("data. txt"));

String s = file. nextLine ();

}

catch (ArithmeticException ae)

{

System. out. println (ae. getMessage ());

}

Explain what the problem is and how to fix it.

+3
Answers (1)
  1. 1 October, 22:49
    0
    The code above tries to read a file using the scanner class in java programming language.

    But it was done properly.

    First, the scanner class library is not imported to the program.

    Second, the syntax used in this program is an invalid way of reading a file in java programming language using the scanner class.

    Lastly, "String s = file. nextLine (); " is not a proper way of reading each line

    To correct this problem; use the following code;

    import java. util. Scanner;

    import java. io. File;

    import java. io. FileNotFoundException;

    public class ReadFileWithScanner {

    try

    {

    public static void main (String args[]) throws FileNotFoundException {

    File text = new File ("data. txt");

    Scanner file = new Scanner (text);

    int lines = 1;

    while (file. hasNextLine ()) {

    String line = filw. nextLine ();

    System. out. println ("line " + lines + " : " + line);

    lines++;

    }

    catch (ArithmeticException ae)

    {

    System. out. println (ae. getMessage ());

    }

    }

    }
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “You coded the following class: try { Scanner file = new Scanner (new File ("data. txt")); String s = file. nextLine (); } catch ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers