So, I have looked through just about every suggestion on this forum so far and none of them can really help me towards the answer that I need.
Here is the my main code:
I've left out the implements as this works fine.
public class Management {
private static int Price1 = 0;
private static int Price2 = 0;
public static void main(String[] args) {
try
{
Scanner file = new Scanner(new File("friendsfile"));
String s;
while(file.hasNext())
{
s = file.nextLine();
if(s.contains("House 1"))
{
Price1 = getPrice(s);
}
if(s.contains("House 2"))
{
Price2 = getPrice(s);
}
}
Filewriter fw = new Filewriter();
fw.fileWriter(Price1,Price2);
}
catch(FileNotFoundException fnfe)
{
System.out.println("File not found");
}
catch(Exception e)
{
System.out.println("HERE IS AN ERROR MATE!");
}
}
private static int getPrice(String s)
{
StringTokenizer st = new StringTokenizer(s,";");
st.nextToken();
int price1 = Integer.parseInt(st.nextToken().replace(" ",""));
return price1;
}
}
Now the Filewriter looks like this:
public class Filewriter {
public static void fileWriter(int price1, int price2)
{
System.out.println("Ye");
final String FILE_PATH = "housesfile";
final String MARKER_LINE1 = "price1";
final String TEXT_TO_ADD1 = "price1: "+price1;
final String MARKER_LINE2 = "price2";
final String TEXT_TO_ADD2 = "price2: "+price2;
List<String> fileLines = new ArrayList<String>();
Scanner scanner = null;
try {
scanner = new Scanner(new File(FILE_PATH));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
fileLines.add(line);
if (line.trim().equalsIgnoreCase(MARKER_LINE1)) {
fileLines.add(TEXT_TO_ADD1);
}
if (line.trim().equalsIgnoreCase(MARKER_LINE2)) {
fileLines.add(TEXT_TO_ADD2);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
PrintWriter pw = null;
try {
pw = new PrintWriter(new File(FILE_PATH));
for (String line : fileLines) {
pw.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
}
}
Basically I want:
House 1: price; 520592
House 2: price; 342038
Those price numbers from one file, converted into this file, which is another one.
house #1
owner: -NAME-
price1: 500000
info: 3 bedrooms, 3 bathrooms.
last changed: - DATE -
rented: no
house #2
owner: -NAME-
price2: 150000
info: 3 bedroom, 3 bathroom.
last changed: -date-
rented: no
Now, it doesn't change anything in the file, why is this? Please help.
That is because you use equalsIgnoreCase() in your Filewriter class and compare it with price1, price2. However, your file has values like price1: 500000.
Hence, change equalsIgnoreCase() to contains() and it should work.
Better, change both to lower or upper cases and then match:
line.trim().toLowerCase().contains(MARKER_LINE1.toLowerCase())
Hence, you while loop within Filewrite class would be:
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
fileLines.add(line);
if (line.trim().toLowerCase().contains(MARKER_LINE1.toLowerCase())) {
fileLines.add(TEXT_TO_ADD1);
}
if (line.trim().toLowerCase().contains(MARKER_LINE2.toLowerCase())) {
fileLines.add(TEXT_TO_ADD2);
}
}
EDIT:
Tried and your code works, except it also includes the previously added price1, price2 values which you may want to exclude/overwrite (in the modified if statements above itself):
house #1
owner: -NAME-
price1: 500000
price1: 520592
info: 3 bedrooms, 3 bathrooms.
last changed: - DATE -
rented: no
house #2
owner: -NAME-
price2: 150000
price2: 342038
info: 3 bedroom, 3 bathroom.
last changed: -date-
rented: no
Related
The program is giving correct output when System.out.println(mem[i].memName); but the array of class "member" is giving output (alex alex alex alex) i.e of the last line of the file (mentioned at the END of the CODE)
it should give all the names listed in the file.
import java.io.*;
import java.util.*;
class member//CLASS TO BE USED AS ARRAY TO STORE THE PRE REGISTERED MEMBERS FED INSIDE
{ //THE FILE "member.txt"
static int memId;
static String memName, memEmail, memPh, date;
}
public class entry// file name
{
static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
static LocalDateTime now = LocalDateTime.now();
static Scanner input = new Scanner(System.in);
static member[] mem = new member[100];
static trainer[] tr = new trainer[100];
static FileWriter fwriter = null;
static BufferedWriter bwriter = null;
static FileReader fread = null;
static BufferedReader bread = null;
static void memberEntry() {
int i = 0;
System.out.println("NEW MEMBER IS BEING ADDED");
try {
fwriter = new FileWriter("C:\\Users\\itisa\\OneDrive\\Desktop\\GYM
PROJECT\\member.txt
",true);
bwriter = new BufferedWriter(fwriter);
System.out.println("Member ID is being automatically genrated");
int autoID = 101 + getMemberRecords();//Fetching the number of members so that ID can
//Be genrated automatically
i = autoID % 100;//jumping toward the next loaction location
System.out.println("Member ID of new member is" + autoID);
mem[i].memId = autoID;
System.out.print("Enter the name of the member:");
mem[i].memName = input.next();
System.out.print("Enter the email address of memeber:");
mem[i].memEmail = input.next();
System.out.print("Enter the contact number of memeber:");
mem[i].memPh = input.next();
System.out.println("Date has been feeded automatically:" + dtf.format(now));
mem[i].date = dtf.format(now);
bwriter.write(String.valueOf(mem[i].memId));
bwriter.write("|");
bwriter.write(mem[i].memName);
bwriter.write("|");
bwriter.write(mem[i].memEmail);
bwriter.write("|");
bwriter.write(mem[i].memPh);
bwriter.write("|");
bwriter.write(mem[i].date);
bwriter.write("\n");
System.out.println("MEMBER CREATED SUCCESSFULLY");
System.out.println("---------------------------------------");
bwriter.close();
} catch (IOException e) {
System.out.print(e);
}
}
static int getMemberRecords() {
int count = 0, i = 0;
try {
fread = new FileReader("C:\\Users\\itisa\\OneDrive\\Desktop\\GYM PROJECT\\member.txt");
bread = new BufferedReader(fread);
String lineRead = null;
while ((lineRead = bread.readLine()) != null)//Just to get to know the number of member
//alreadyinside the file
{
String[] t = lineRead.split("\\|");
mem[i].memId = Integer.parseInt(t[0]);
mem[i].memName = t[1];
mem[i].memEmail = t[2];
mem[i].memPh = t[3];
mem[i].date = t[4];
i++;
count++;
}
System.out.println(mem[0].memName);//should print the 1st name present in the name
//i.e, RAVI
} catch (IOException e) {
System.out.println(e);
}
return count;
}
public static void main(String[] args) throws IOException {
System.out.println("Total number of accounts:" + getMemberRecords());
}
}
Elements stored in the file:
101|RAVI|itisadi23#gmai.com|9102019656|2020/04/30
102|aditya|adi#gmail.com|9386977983|2020/04/30
103|anurag|anu#ymail.com|10000000000|2020/04/30
104|alex|alex123#mail.com|2829578303|2020/04/30
Expected output:
RAVI
Total number of accounts = 4
My output:
alex
Total number of accounts=4
In Short it is giving last name as output no matter what index number is given to fetch the data.
Your member class members must not be static, if they are, they're shared by every member class object.
The other problem is that your member array nodes are not being initialized, you'll need:
Live demo
class member
{
int memId; //non-static
String memName, memEmail, memPh, date; //non-static
}
and
//...
while ((lineRead = bread.readLine()) != null) {
String[] t = lineRead.split("\\|");
mem[i] = new member(); // initialize every node
mem[i].memId = Integer.parseInt(t[0]);
mem[i].memName = t[1];
mem[i].memEmail = t[2];
mem[i].memPh = t[3];
mem[i].date = t[4];
i++;
count++;
}
System.out.println(mem[0].memName);
//...
Output:
RAVI
Note that you can use ArrayList or other java collection.
I was trying to search for the specific data from the text file by using the ID.
But I was just able to search and display for the id T1001.
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String filepath = "Technician.txt";
System.out.print("Enter ID : ");
String searchTerm= sc.nextLine();
readRecord(searchTerm,filepath);
}
public static void readRecord(String searchTerm,String filepath){
boolean found = false;
String techID="";
String service="";
String firstName="";
String lastName="";
String salary="";
String position="";
String password="";
try
{
Scanner x = new Scanner(new File(filepath));
x.useDelimiter("[\\|]");
while(x.hasNext()&& !found)
{
techID = x.next();
service=x.next();
firstName=x.next();
lastName=x.next();
salary=x.next();
position=x.next();
password=x.next();
if(techID.equals(searchTerm)){
found = true;
}
}
if(found)
{
System.out.print("ID: "+techID+"\n"+"Service : "+service+"\n"+"First Name: "+firstName+"\n"+"Last Name : "+lastName+"\n" + "Salary : "+salary
+"\n" + "Position : "+position);
}
else
{
System.out.print("ID not found");
}
}
catch(Exception e)
{
}
}
And below is my text file :
T1001|Repair|Raymond|Lee|3000.00|staff|abc123|
T1002|Repaint|Joey|Tan|3000.00|staff|123456|
By Default Scanner class takes the first line as input from your file. But you have to read all lines, so its better to use #nextLine method and then #split method to extract your individual values from the line. Follow the bellow code :
import java.util.Scanner;
import java.io.*;
public class example {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String filepath = "Technician.txt";
System.out.print("Enter ID : ");
String searchTerm= sc.nextLine();
readRecord(searchTerm,filepath);
}
public static void readRecord(String searchTerm,String filepath){
try
{
Scanner x = new Scanner(new File(filepath));
while(x.hasNext())
{
String values[] = x.nextLine().toString().split("\\|");
if(values[0].equals(searchTerm)){
System.out.print("ID: "+values[0]+"\n"+"Service : "+values[1]+"\n"+"First Name: "+values[2]+"\n"+"Last Name : "+values[3]+"\n" + "Salary : "+values[4]
+"\n" + "Position : "+values[5] + "\n");
return;
}
}
System.out.print("ID not found");
}
catch(Exception e)
{
}
}
}
Reason of your error is that next line also contains string for next line "\n" and that's how techID is read. In my case it looks like "\n\nT1002" . That's why you need to use function contains and if not equals cut your ID. Your code:
public static void readRecord(String searchTerm,String filepath){
boolean found = false;
boolean toUpdate = false;
String techID="";
String service="";
String firstName="";
String lastName="";
String salary="";
String position="";
String password="";
try
{
Scanner x = new Scanner(new File(filepath));
x.useDelimiter("[\\|]");
while(x.hasNext()&& !found)
{
techID = x.next();
service=x.next();
firstName=x.next();
lastName=x.next();
salary=x.next();
position=x.next();
password=x.next();
if(techID.contains(searchTerm)){
found = true;
if(!techID.equals(searchTerm)) {
toUpdate = true;
}
}
}
if(found)
{
if(toUpdate) {
techID = techID.substring(4, techID.length());
}
System.out.print("ID: "+techID+"\n"+"Service : "+service+"\n"+"First Name: "+firstName+"\n"+"Last Name : "+lastName+"\n" + "Salary : "+salary
+"\n" + "Position : "+position);
}
else
{
System.out.print("ID not found");
}
x.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
}
}
}
Another way can be using delimiter two times. Firstly to make rows in result "x" and then make x.split("|") for example.
As the topic states im trying to get a specific string that is usually auto generated into the same string and it seems to work because the temp file is created and the string is replaced with "" but its seems that there is an IOException when it comes to renaming to original when deleting , help please?
import java.io.*;
import java.util.Scanner;
/**
* Main class to test the Road and Settlement classes
*
* #author Chris Loftus (add your name and change version number/date)
* #version 1.0 (24th February 2016)
*
*/
public class Application {
private Scanner scan;
private Map map;
private static int setting;
public Application() {
scan = new Scanner(System.in);
map = new Map();
}
private void runMenu() {
setting = scan.nextInt();
scan.nextLine();
}
// STEP 1: ADD PRIVATE UTILITY MENTHODS HERE. askForRoadClassifier, save and
// load provided
private Classification askForRoadClassifier() {
Classification result = null;
boolean valid;
do {
valid = false;
System.out.print("Enter a road classification: ");
for (Classification cls : Classification.values()) {
System.out.print(cls + " ");
}
String choice = scan.nextLine().toUpperCase();
try {
result = Classification.valueOf(choice);
valid = true;
} catch (IllegalArgumentException iae) {
System.out.println(choice + " is not one of the options. Try again.");
}
} while (!valid);
return result;
}
private void deleteSettlement() {
String name;
int p;
SettlementType newSetK = SettlementType.CITY;
int set;
System.out.println("Please type in the name of the settlement");
name = scan.nextLine();
System.out.println("Please type in the population of the settlment");
p = scan.nextInt();
scan.nextLine();
System.out.println("Please type in the number of the type of settlement .");
System.out.println("1: Hamlet");
System.out.println("2: Village");
System.out.println("3: Town");
System.out.println("4: City");
set = scan.nextInt();
scan.nextLine();
if (set == 1) {
newSetK = SettlementType.HAMLET;
}
if (set == 2) {
newSetK = SettlementType.VILLAGE;
}
if (set == 3) {
newSetK = SettlementType.TOWN;
}
if (set == 4) {
newSetK = SettlementType.CITY;
}
String generatedResult = "Name: " + name + " Population: " + p + " SettlementType " + newSetK;
String status = searchAndDestroy(generatedResult);
}
private String searchAndDestroy(String delete) {
File file = new File("C:\\Users\\Pikachu\\workspace\\MiniAssignment2\\settlements.txt");
try {
File temp = File.createTempFile("settlement", ".txt", file.getParentFile());
String charset = "UTF-8";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
for (String line; (line = reader.readLine()) != null;) {
line = line.replace(delete, "");
writer.println(line);
}
System.out.println("Deletion complete");
reader.close();
writer.close();
file.delete();
temp.renameTo(file);
}
catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! 1");
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! 2");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! , IO Exception error incurred 3");
}
return null;
}
private void save() {
map.save();
}
private void load() {
map.load();
}
public void addSettlement() {
String name;
int p;
SettlementType newSetK = SettlementType.CITY;
int set;
System.out.println("Please type in the name of the settlement");
name = scan.nextLine();
System.out.println("Please type in the population of the settlment");
p = scan.nextInt();
scan.nextLine();
System.out.println("Please type in the number of the type of settlement .");
System.out.println("1: Hamlet");
System.out.println("2: Village");
System.out.println("3: Town");
System.out.println("4: City");
set = scan.nextInt();
scan.nextLine();
if (set == 1) {
newSetK = SettlementType.HAMLET;
}
if (set == 2) {
newSetK = SettlementType.VILLAGE;
}
if (set == 3) {
newSetK = SettlementType.TOWN;
}
if (set == 4) {
newSetK = SettlementType.CITY;
}
new Settlement(name, newSetK, p);
}
private void printMenu() {
System.out.println("Please type in the number of the action that you would like to perform");
System.out.println("1: Create Settlement");
System.out.println("2: Delete Settlement");
System.out.println("3: Create Road");
System.out.println("4: Delete Road");
System.out.println("5:Display Map");
System.out.println("6:Save Map");
}
public static void main(String args[]) {
Application app = new Application();
app.printMenu();
app.runMenu();
System.out.println(setting);
if (setting == 1) {
app.addSettlement();
}
if (setting == 2) {
app.deleteSettlement();
}
app.load();
app.runMenu();
app.save();
}
}
I checked if it was deletable (file.delete throws a boolean exception) so I tried deleting it directly via windows and apparently it was being used by java so I assumed eclipsed glitch and upon closing and booting up eclipse again it worked..... well... that was rather anti-climactic .... Thank you so much for the discussion , I would definitely never had figured it out if not for the discussion :D <3 You are all in my heart
I'm doing a Phone Directory project and we have to read from a directory file telnos.txt
I'm using a Scanner to load the data from the file telnos.txt, using a loadData method from a previous question I asked here on StackOverflow.
I noticed attempts to find a user always returned Not Found, so I added a few System.out.printlns in the methods to help me see what was going on. It looks like the scanner isn't reading anything from the file. Weirdly, it is printing the name of the file as what should be the first line read, which makes me think I've missed something very very simple here.
Console
run:
telnos.txt
null
loadData tested successfully
Please enter a name to look up: John
-1
Not found
BUILD SUCCESSFUL (total time: 6 seconds)
ArrayPhoneDirectory.java
import java.util.*;
import java.io.*;
public class ArrayPhoneDirectory implements PhoneDirectory {
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
private DirectoryEntry[] theDirectory = new DirectoryEntry[capacity];
// Holds name of data file
private final String sourceName = "telnos.txt";
File telnos = new File(sourceName);
// Flag to indicate whether directory was modified since it was last loaded or saved
private boolean modified = false;
// add method stubs as specified in interface to compile
public void loadData(String sourceName) {
Scanner read = new Scanner("telnos.txt").useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else
telno = read.nextLine();
add(name, telno);
i++;
}
}
public String lookUpEntry(String name) {
int i = find(name);
String a = null;
if (i >= 0) {
a = name + (" is at position " + i + " in the directory");
} else {
a = ("Not found");
}
return a;
}
public String addChangeEntry(String name, String telno) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setNumber(telno);
} else {
add(name, telno);
}
}
return null;
}
public String removeEntry(String name) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setName(null);
i.setNumber(null);
}
}
return null;
}
public void save() {
PrintWriter writer = null;
// writer = new PrintWriter(FileWriter(sourceName));
}
public String format() {
String a;
a = null;
for (DirectoryEntry i : theDirectory) {
String b;
b = i.getName() + "/n";
String c;
c = i.getNumber() + "/n";
a = a + b + c;
}
return a;
}
// add private methods
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno) {
System.out.println(name);
System.out.println(telno);
theDirectory[size] = new DirectoryEntry(name, telno);
size = size + 1;
}
// Searches the array of directory entries for a specific name
private int find(String name) {
int result = -1;
for (int count = 0; count < size; count++) {
if (theDirectory[count].getName().equals(name)) {
result = count;
}
System.out.println(result);
}
return result;
}
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate() {
capacity = capacity * 2;
DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
System.arraycopy(theDirectory, 0, newDirectory,
0, theDirectory.length);
theDirectory = newDirectory;
}
}
ArrayPhoneDirectoryTester.java
import java.util.Scanner;
public class ArrayPhoneDirectoryTester {
public static void main(String[] args) {
//create a new ArrayPhoneDirectory
PhoneDirectory newTest = new ArrayPhoneDirectory();
newTest.loadData("telnos.txt");
System.out.println("loadData tested successfully");
System.out.print("Please enter a name to look up: ");
Scanner in = new Scanner(System.in);
String name = in.next();
String entryNo = newTest.lookUpEntry(name);
System.out.println(entryNo);
}
}
telnos.txt
John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231
In your code:
Scanner read = new Scanner("telnos.txt");
Is not going to load file 'telnos.txt'. It is instead going to create a Scanner object that scans the String "telnos.txt".
To make the Scanner understand that it has to scan a file you have to either:
Scanner read = new Scanner(new File("telnos.txt"));
or create a File object and pass its path to the Scanner constructor.
In case you are getting "File not found" errors you need to check the current working directory. You could run the following lines and see if you are indeed in the right directory in which the file is:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
You need to also catch the FileNotFoundException in the function as follows:
public void loadData(String sourceName) {
try {
Scanner read = new Scanner(new File("telnos.txt")).useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else {
telno = read.nextLine();
add(name, telno);
}
i++;
}
}catch(FileNotFoundException ex) {
System.out.println("File not found:"+ex.getMessage);
}
}
You are actually parsing the filename not the actual file contents.
Instead of:
new Scanner("telnos.txt")
you need
new Scanner( new File( "telnos.txt" ) )
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
I'm trying to scan a text file that has a format like this:
reviewers: 0
open: Sunday 08:00 16:00,Monday 06:00 20:00,Tuesday 06:00 20:00,Wednesday 06:00 20:00,Thursday 06:00 20:00,Friday 06:00 20:00,Saturday 06:00 01:00
name: The Lyre of Orpheus
city: San Francisco
cost: $$
category: Greek,Breakfast & Brunch,Seafood,Salad,Soup
rank: 0
and saving each line as a string or double, but i keep getting null with the sys.out.println inside of my forloop, anything I can change? My thought is that I'm resetting my variables inside my try too early or something.
public class Yulp {
//instance vars
ArrayList<Restaurant> resList = new ArrayList<Restaurant>();
public static void main(String args[]) {
Yulp yelp = new Yulp();
yelp.scan();
for(int i = 0; i < yelp.resList.size(); i++){
System.out.println(yelp.resList.get(i).getCity());
}
}
public void scan() {
try {
Restaurant tempRes = new Restaurant();
String name, city, category, cost;
double rank, reviewers;
Scanner scan = new Scanner(new File("randomizedList.txt"));
while (scan.hasNext()) {
//name = null; city = null; category = null; cost = null; rank = 0.0; reviewers = 0;
String line = scan.nextLine();
String rest = omitPrefix(line, "reviewers:");
if (rest != null) {
reviewers = Double.parseDouble(rest);
tempRes.setReviewers(reviewers);
}
rest = omitPrefix(line, "rank:");
if (rest != null) {
rank = Double.parseDouble(rest);
}
rest = omitPrefix(line, "name:");
if (rest != null) {
name = rest;
}
rest = omitPrefix(line, "city:");
if (rest != null) {
city = rest;
}
rest = omitPrefix(line, "category:");
if (rest != null) {
category = rest;
}
rest = omitPrefix(line, "cost:");
if (rest != null) {
cost = rest;
}
resList.add(tempRes);
}
scan.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
private String omitPrefix(String line, String prefix) {
if (line.startsWith(prefix))
return line.substring(prefix.length());
return null;
}
}
Here's what I have
import java.io.InputStream;
import java.util.Scanner;
public class Snippet {
public void scan() throws Exception {
Scanner scan = new Scanner(new File("randomizedList.txt"));
while (scan.hasNext()) {
String line = scan.nextLine();
String rest = omitPrefix(line, "reviewers:");
if (rest != null) {
System.out.println(rest);
}
rest = omitPrefix(line, "name:");
if (rest != null) {
System.out.println(rest);
}
rest = omitPrefix(line, "city:");
if (rest != null) {
System.out.println(rest);
}
rest = omitPrefix(line, "category:");
if (rest != null) {
System.out.println(rest);
}
}
scan.close();
}
private String omitPrefix(String line, String prefix) {
if (line.startsWith(prefix))
return line.substring(prefix.length());
return null;
}
public static void main(String[] args) throws Exception {
new Snippet().scan();
}
}
Main points:
Instead of line = new Scanner(scan.nextLine()); temp = line.nextLine(); you can just do scan.nextLine.
For getting the remainder of a line (for instance the part that follows the "name:" part) I introduced a helper method called omitPrefix(line, prefix) which returns line sans prefix if line starts with prefix, or null otherwise.
Here's another way of doing it.
public class FileParser {
public void scan() {
try {
File list = new File("randomizedList.txt");
Scanner scan = new Scanner(list);
String temp;
Scanner line;
while (scan.hasNext()) {
line = new Scanner(scan.nextLine());
temp = line.nextLine();
if (temp.startsWith("reviewers:")) {
System.out.println(temp.split(":",2)[1]);
}
if (temp.startsWith("name:",1)) {
System.out.println(temp.split(":",2)[1]);
}
if (temp.startsWith("open:")) {
System.out.println(temp.split(":",2)[1]);
}
if (temp.startsWith("city:")) {
System.out.println(temp.split(":",2)[1]);
}
if (temp.startsWith("category:")) {
System.out.println(temp.split(":",2)[1]);
}
}
scan.close();
}
catch(FileNotFoundException e){
System.out.println("File's MISSIN!");
}
catch(NoSuchElementException e){
System.out.println("NoSuchElementException dangus.");
}
}
public static void main(String[] args) {
new FileParser().scan();
}
}
Check the line with startsWith to find the introductory key word.
Then use split the string around the : which returns an array of two strings.
The second string in the returned array is reached by [1] and this produces the above output
There are further improvements that can be made to this code though.
The if statements should be refactored and extracted as a separate method.
The strings constants should extracted and each line should only be checked once.
Once a match is made you should move on to the next line.