I am scanning an movieFile.txt using Java programming with the content below. Ho
ID: 3767941 • Letter: I
Question
I am scanning an movieFile.txt using Java programming with the content below. How can I scan it in the way tht movies are stored in a variable and the integer in another variable? The variable will update for every new movie.
For example: when scanning the first item, "Harry Potter" the variable would be, String movie = "Harry Potter" and int numAvailable = 2. Then movie = " Twilight" when twilight is scan and numAvailable=1.
If there is no integer listed beside the movie, it is set to default 1.
Explanation / Answer
/**
* The java program that reads input text file called
* movieFile.txt . Then file cotains movie name and number
* of movies included in parenthesis, ().
* If parenthesis, () absent, numMoives are set to 1.
*
* */
//ReadFile.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile
{
public static void main(String[] args)
{
Scanner scanner=null;
String fileName="movieFile.txt";
int numMovies=0;
try
{
scanner=new Scanner(new File(fileName));
String line="";
String movieName="";
while(scanner.hasNextLine())
{
line=scanner.nextLine();
//Check if the line contains parenthesis
if(line.contains("("))
{
//split the line using ()
String movies[]=line.split(" ()");
for (int i = 0; i < movies.length-1; i++)
{
//Append movies
movieName+=" "+movies[i];
}
//Convert the string of number of movies to integer
numMovies=Integer.parseInt
(String.valueOf(movies[movies.length-1].charAt(1)));
}
else
{
//Set line to movieName
movieName=line;
//Set numMovies to 1
numMovies=1;
}
//print movie name
System.out.println("Movie Name : "+movieName);
//print numbe of movies
System.out.println("Num of Movies : "+numMovies);
//Set movieName to empty
movieName="";
//Set movieName to zero
numMovies=0;
}
scanner.close();
}
catch (FileNotFoundException e)
{
System.out.println("File Not found");
}
}
}
----------------------------------------------------------------------
movieFil.txt
Harry Potter (2)
Twilight
Singin' in the Rain
A Streetcar Named Desire (5)
-------------------------------------------------------------------------
Sample Output
Movie Name : Harry Potter
Num of Movies : 2
Movie Name : Twilight
Num of Movies : 1
Movie Name : Singin' in the Rain
Num of Movies : 1
Movie Name : A Streetcar Named Desire
Num of Movies : 5
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.