Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PROBLEM USING SPACE A DELIMITER IWHILE READING FILE IN JAVA

I WANT TO STORE MOVIE YEAR AND TITLE IN VARIABLES BUT AM HAVING PROBLEM GETTING THE TITLE PART USING "SPACE AS A DELIMITER". HOW DO I GET THE WHOLE MOVIE TITLE WITHOUT GETTING THE FIRST WORD ONLY?

import java.io.File;
import java.util.Scanner;

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author HP
*/
public class TopMoviesReadFromFileDriver {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Movie[] movieArray = new Movie[1000];
Movie movie;

String title;
int year, counter = 0;

try {
Scanner inputFile = new Scanner(new File("movies.txt"));

//while loop to read every line in the file, one at a time
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine();
String[] splitLine = line.split(" ");
System.out.println(splitLine[1]);

year = Integer.parseInt(splitLine[0]);
title = splitLine[1];

//TO DO: continue reading the rest of the data in the line
//TO DO: create a Movie object with all the values just read
movie = new Movie(year, title);
counter++;

}

//TO DO: DISPLAY OUTPUT AS ON THE SAMPLE SCREEN
} catch (java.io.FileNotFoundException e) {
System.out.println("File Not Found");
}
}

}

movies.txt

1931 City Lights
1936 Modern Times
1942 Casablanca
1946 It's a Wonderful Life
1954 Rear Window
1954 Seven Samurai
1957 12 Angry Men

THIS IS WHAT AM GETTING WHEN I RUN THE PROGRAM. I WANT TO GET THE WHOLE TITLE

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think that you could just use:

String[] splitLine = line.split(" ",2);

You can read about split method on https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading