Write a program that asks the user for the name of a file. The program should display the contents of the file with each line preceded with a line number followed by a colon. The line numbering should start at 1. Please edit this scanner to JOptionPane.

EBK JAVA PROGRAMMING
9th Edition
ISBN:9781337671385
Author:FARRELL
Publisher:FARRELL
Chapter13: File Input And Output
Section: Chapter Questions
Problem 10PE
icon
Related questions
Question

The problem is the following :

Write a program that asks the user for the name of a file. The program should display the contents of the file with each line preceded with a line number followed by a colon. The line numbering should start at 1.

Please edit this scanner to JOptionPane. I don't really know how to do that. 

 

//Java Program by Yuiri Fujita and Darrick Drewry 10/30/2020

import java.util.Scanner;
import java.io.*;

public class LineNumbers {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub


Scanner input = new Scanner(System.in);
String userFileName;

System.out.println("Please enter the name of the file.( Enter LineNumbers.txt)");
userFileName = input.nextLine();

File file = new File( userFileName);

while( !file.exists() ){
System.out.println( userFileName + " does not exist. Please enter a different file name");
userFileName = input.nextLine();
file = new File ( userFileName);
}
Scanner fileToScan = new Scanner (file);

String line;

int counter = 0;

while (fileToScan.hasNext()){
counter += 1;
line = fileToScan.nextLine();
System.out.println(counter + ": " + line);
}

}
}

Expert Solution
trending now

Trending now

This is a popular solution!

steps

Step by step

Solved in 2 steps with 2 images

Blurred answer
Knowledge Booster
File Input and Output Operations
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
EBK JAVA PROGRAMMING
EBK JAVA PROGRAMMING
Computer Science
ISBN:
9781337671385
Author:
FARRELL
Publisher:
CENGAGE LEARNING - CONSIGNMENT
C++ Programming: From Problem Analysis to Program…
C++ Programming: From Problem Analysis to Program…
Computer Science
ISBN:
9781337102087
Author:
D. S. Malik
Publisher:
Cengage Learning