怎样从写入了的文件中获取数字

huangapple go评论65阅读模式
英文:

How to get number from file that is written

问题

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

public class Trip {
    
    private String password;
    private String placeOfDeparture;
    private String destination;
    private int durationInDays;
    private double wage;
    private double rentPrice;
    private String firstName;
    private String lastName;
    private String[] passwords;
    
    public Trip(String placeOfDeparture, String destination, int durationInDays, double wage,
            double rentPrice, String firstName, String lastName) {
        super();
        this.placeOfDeparture = placeOfDeparture;
        this.destination = destination;
        this.durationInDays = durationInDays;
        this.wage = wage;
        this.rentPrice = rentPrice;
        this.firstName = firstName;
        this.lastName = lastName;
        generateTripPassword();
    }

    
    public void generateTripPassword() {
        Random rand = new Random();
        int randomNumbers = rand.nextInt(100);
        String personInitials = "";
        String departureInitials = "";
        String destinationInitials = "";
        
        personInitials += firstName.substring(0, 1).toUpperCase();
        personInitials += lastName.substring(0, 1).toUpperCase();
        departureInitials += placeOfDeparture.substring(0, 2).toUpperCase();
        destinationInitials += destination.substring(0, 2).toUpperCase();
        
        for(int i = 0; i < passwords.length; i++) {
            if(passwords[i] == null) {
                passwords[i] = personInitials + departureInitials + destinationInitials + randomNumbers;
                break;
            }
        }
        
        this.password = personInitials + departureInitials + destinationInitials + randomNumbers;
    }
    
    public void getTripInformation() {
        System.out.println("Trip details: \n");
        System.out.println("Trip password: " + password);
        System.out.println("Passenger name: " + firstName + " " + lastName + ".");
        System.out.println("Duration in days: " + durationInDays + ".");
        System.out.println("Wage: " + wage + ".");
        System.out.println("Rent price is: " + rentPrice + ".");
    }
    
    public void writeTripInfo(String tripType) {
        File file = new File(this.password + ".txt");
        try {
            FileWriter trip = new FileWriter(file);
            trip.write("Trip details:");
            trip.write("Trip password: " + password);
            trip.write("Passenger name: " + firstName + " " + lastName + ".");
            trip.write("Duration in days: " + durationInDays + ".");
            trip.write("Wage: " + wage + ".");
            trip.write("Rent price is: " + rentPrice + ".");
            trip.write("Type of the trip is: " + tripType);
            trip.close();
            System.out.println("File writing successfully completed! Name of the file is: " + this.password + ". Enjoy.");
        } catch (IOException e) {
            System.out.println("An error occurred while writing the file.");
            System.out.println("Here is the error debug code:");
            e.printStackTrace();
        }
    }
}
英文:

I am making an java program for college and I am stuck at one point, the exam says I need to extract information from an txt file that is already written. I need to get only the information from the end of the lines like password or something.

DISCLAIMER:

I know how to do it by using scanner and file. But it is not really clear how to extract only the information not the whole line.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class Trip {
private String password;
private String placeOfDeparture;
private String destination;
private int durationInDays;
private double wage;
private double rentPrice;
private String firstName;
private String lastName;
private String[] passwords;
public Trip(String placeOfDeparture, String destination, int durationInDays, double wage,
double rentPrice, String firstName, String lastName) {
super();
this.placeOfDeparture = placeOfDeparture;
this.destination = destination;
this.durationInDays = durationInDays;
this.wage = wage;
this.rentPrice = rentPrice;
this.firstName = firstName;
this.lastName = lastName;
generateTripPassword();
}
public void generateTripPassword() {
Random rand = new Random();
int randomNumbers = rand.nextInt(100);
String personInitials = &quot;&quot;;
String departureInitials = &quot;&quot;;
String destinationInitials = &quot;&quot;;
personInitials += firstName.substring(0, 1).toUpperCase();
personInitials += lastName.substring(0, 1).toUpperCase();
departureInitials += placeOfDeparture.substring(0, 2).toUpperCase();
destinationInitials += destination.substring(0, 2).toUpperCase();
for(int i = 0; i &lt; passwords.length; i++) {
if(passwords[i] == null) {
passwords[i] = personInitials + departureInitials + destinationInitials + randomNumbers;
break;
}
}
this.password = personInitials + departureInitials + destinationInitials + randomNumbers;
}
public void getTripInformation() {
System.out.println(&quot;Trip details: \n&quot;);
System.out.println(&quot;Trip password: &quot; + password);
System.out.println(&quot;Passenger name: &quot; + firstName + &quot; &quot; + lastName + &quot;.&quot;);
System.out.println(&quot;Duration in days: &quot; + durationInDays + &quot;.&quot;);
System.out.println(&quot;Wage: &quot; + wage + &quot;.&quot;);
System.out.println(&quot;Rent price is: &quot; + rentPrice + &quot;.&quot;);
}
public void writeTripInfo(String tripType) {
File file = new File(this.password + &quot;.txt&quot;);
try {
FileWriter trip = new FileWriter(file);
trip.write(&quot;Trip details: &quot;);
trip.write(&quot;Trip password: &quot; + password);
trip.write(&quot;Passenger name: &quot; + firstName + &quot; &quot; + lastName + &quot;.&quot;);
trip.write(&quot;Duration in days: &quot; + durationInDays + &quot;.&quot;);
trip.write(&quot;Wage: &quot; + wage + &quot;.&quot;);
trip.write(&quot;Rent price is: &quot; + rentPrice + &quot;.&quot;);
trip.write(&quot;Type of the trip is: &quot; + tripType);
trip.close();
System.out.println(&quot;File writing successfully completed! Name of yje file is: &quot; + this.password + &quot; . Enjoy.&quot;);
} catch (IOException e) {
System.out.println(&quot;An error occured while writing file.&quot;);
System.out.println(&quot;Here is the error debug code: &quot;);
e.printStackTrace();
}
}
}

答案1

得分: 1

public void readTripInfo(String path)
{
    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        String line;
        // 读取文件的每一行
        while ((line = br.readLine()) != null) {
            // 以':'为分隔符拆分每一行
            String[] parts = line.split(":");
            if (parts.length == 2) {
                // 保存数据
                if (parts[0].equals("旅行密码")) {
                    password = parts[1].trim();
                } else if (parts[0].equals("乘客姓名")) {
                    String[] names = parts[1].trim().split(" ");
                    if (names.length == 2) {
                        firstName = names[0];
                        lastName = names[1];
                    }
                } else if (parts[0].equals("持续天数")) {
                    durationInDays = Integer.parseInt(parts[1].trim());
                }
                // 处理其他部分
            }
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}
英文:

After you have put each part on its own line (and removed the '.' at the end), you can parse each line by splitting on ':'

public void readTripInfo(String path)
{
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
// Read each line of file
while ((line = br.readLine()) != null) {
// Split on &#39;:&#39;
String [] parts = line.split(&quot;:&quot;);
if (parts.length == 2) {
// Save
if (parts[0].equals(&quot;Trip password&quot;)) {
password = parts[1].trim();
}
else if (parts[0].equals(&quot;Passenger name&quot;)) {
String [] names = parts[1].trim().split(&quot; &quot;);
if (names.length == 2) {
firstName = names[0];
lastName = names[1];
}
}
else if (parts[0].equals(&quot;Duration in days&quot;)) {
durationInDays = Integer.parseInt(parts[1].trim());
}
// Continue for the rest
}
}
}
catch (Exception e) {
System.out.println(e);
}
}

huangapple
  • 本文由 发表于 2020年9月12日 20:39:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63860422.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定