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.

Respuesta :

Answer:

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());

}

}

}