String Replace not working as I think it should [duplicate] - java

This question already has answers here:
Java String replace not working [duplicate]
(6 answers)
Closed 8 years ago.
public static boolean passwordConfirmed() {
String attempt = JOptionPane.showInputDialog("Password: ");
FileReader fstream = null;
String password = "";
try {
fstream = new FileReader("pass.txt");
BufferedReader in = new BufferedReader(fstream);
password = in.readLine();
password.replace("Password: ", " ");
System.out.println(password);
} catch (IOException e) {
e.printStackTrace();
}
if (attempt.equals(password)) {
System.out.print("True");
return true;
} else System.out.println("false");
return false;
}
Trying to remove "Password: " from the line.
It gets the line "Password: " + text afterwards (Password)
I want to remove the "Password: ", so all i have left is purely the text afterwards.

Always re-assign it.
password = password.replace("Password: ", " ");
Strings are immutable in Java, meaning you can't modify an existing instance of it. By re-assigning it, you'll be capturing the new value of the string into an existing variable.

Related

Index 2 out of bounds for length 1 [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 8 months ago.
I have the following service for to get values inside a string document, this service is called inside a for, getting the data for every flight and then generate a PDF.
I'm getting the Index 2 out of bounds for length 1 when try to call the service, this is the code:
private Map<String, Object> readFileLsd(String content) {
Map<String, Object> mapResult = new LinkedHashMap<>();
try {
Reader inputString = new StringReader(content);
BufferedReader br = new BufferedReader(inputString);
String line;
String TotalBaggagesCargo = "";
String PASSENGER = "";
String TOTAL_TRAFFIC = "";
String validCharacters = "[\\x00-\\x1F]|[\\x21-\\x2c]|[\\x3B-\\x40]|[\\x5B-\\x60]|[\\x7B-\\xFF]";
while ((line = br.readLine()) != null) {
line = line.replaceAll(validCharacters, "").trim();
if (line.startsWith("LOAD IN COMPARTMENTS")) {
TotalBaggagesCargo = line;
}
if (line.startsWith("PASSENGER/CABIN BAG")) {
PASSENGER = line;
}
if (line.startsWith("TOTAL TRAFFIC LOAD")) {
TOTAL_TRAFFIC = line;
}
}
mapResult.put("TotalBaggagesCargo", TotalBaggagesCargo.trim().replaceAll("\\s+", " ").split(" ")[3]);
mapResult.put("PASSENGER", PASSENGER.trim().replaceAll("\\s+", " ").split(" ")[2]);
mapResult.put("TOTAL_TRAFFIC", TOTAL_TRAFFIC.trim().replaceAll("\\s+", " ").split(" ")[3]);
} catch (Exception e) {
e.printStackTrace();
}
return mapResult;
}
Underlying Problem
The line which starts with PASSENGER/CABIN BAG apparently has only one whitespace character and when you split it by a space it results in a String array with only one entry.
Possible solution
If the amount of passengers is sometimes not present in the input String, then you could make the put of key conditional.
String[] passengers = PASSENGER.trim().replaceAll("\\s+", " ").split(" ");
if (passenger.length > 2) mapResult.put("PASSENGER", passengers[2]);
This might bring different problems later in your program. So before working around it, you must try to understand, why it is absent. If it is reasonable that it is missing, then the workaround is acceptable, maybe you will need an else-case like that
else mapResult.put("PASSENGER", "");
when the key has to be present later on.

How do you allow a user to retrieve values from a list in Java?

I created a list in a FlightBookingSystem Java Class, as you can see below:
public List<Flight> getFlights() {
List<Flight> out = new ArrayList<>(flights.values());
return Collections.unmodifiableList(out);
}
Which I imported from a text file show below:
1::LX2500::Birmingham::Munich::2020-11-25::
2::LX2500::Denmark::London::2021-07-01::
3::LY2380::London::France::2021-06-28::
It's a basic text file which holds the information for each flight
Here is the code I wish to adjust:
public Flight execute(FlightBookingSystem flightBookingSystem, int id)
throws FlightBookingSystemException {
List<Flight> flights = flightBookingSystem.getFlights();
for (Flight Flight : flights) {
if (Flight.getFlightNumber() == flightNumber) {
System.out.println(Flight.getFlightNumber() + " flight(s)");
return flights.get(id);
}
System.out.println(((Flight) flights).getFlightNumber() + " flight(s)");
}
return flights.get(id);
}
How do I change that code so that it allows the user to retrieve one single record from the text file?
Why not to retrieve all and get the one you want by key or id using HashMap ?
If you still want the other option, you can read the text file line by line, and check if it startsWith(...) and the to retrieve this line.
Code example:
try (BufferedReader br = new BufferedReader(new FileReader(file)))
{
String line;
while ((line = br.readLine()) != null)
{
// Add here 'if' condition and parse your line
}
}
Your question is a bit confusing. Your title states:
How do you allow a user to retrieve values from a list in Java?
and the very last line of your post states:
How do I change that code so that it allows the user to retrieve
one single record from the text file?
Which is it, from a List or from a text file?
If it's from a List because you already have the mechanism available then is could be something similar to this:
public String getFlightInfo(String flightNumber) {
List<Flight> flights = FlightBookingSystem.getFlights();
for (Flight flite : flights) {
if(flite.getFlightNumber().equalsIgnoreCase(flightNumber)){
return flite.toString();
}
}
JOptionPane.showMessageDialog(null, "<html>Flight number <font color=red><b>"
+ flightNumber + "</b></font> could not be found!</html>", "Flight Not "
+ "Found", JOptionPane.INFORMATION_MESSAGE);
return null;
}
The code above assumes you have an overriden toString() method applied to the Flight class. If you don't then create one.
If it's actually from file then it could be something like this:
public String getFlightInfo(String flightNumber) {
// 'Try With Resouces' to auto-close reader.
try (BufferedReader reader = new BufferedReader(new FileReader("Flights.txt"))) {
String fileLine = "";
while ((fileLine = reader.readLine()) != null) {
fileLine = fileLine.trim();
// If by chance the file line read in is blank then skip it.
if (fileLine.isEmpty()) {
continue;
}
// First, remove the double colons at the end of line (if any).
if (fileLine.endsWith("::")) {
fileLine = fileLine.substring(0, fileLine.lastIndexOf("::")).trim();
}
/* Split each read in file line based on a double colon delimiter.
The "\\s*" within the regex for the split method handles any
cases where the might be one or more whitespaces before or after
the double-colon delimiter. */
String[] lineParts = fileLine.split("\\s*\\:\\:\\s*");
if(lineParts[1].equalsIgnoreCase(flightNumber)){
// At this point you could just return the line, for example:
// return fileLine;
// or you can return a string with a little more structure:
return new StringBuilder("Flight ID: ").append(lineParts[0])
.append(", Flight #: ").append(lineParts[1]).append(", From: ")
.append(lineParts[2]).append(", To: ").append(lineParts[3])
.append(", Date: ").append(lineParts[4]).toString();
}
}
}
catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
JOptionPane.showMessageDialog(null, "<html>Flight number <font color=red><b>"
+ flightNumber + "</b></font> could not be found!</html>", "Flight Not "
+ "Found", JOptionPane.INFORMATION_MESSAGE);
return null;
}

Reading up to a character in a text file

I remember doing something identical in Python and finding it easy, but I can't seem to find a solution in Java. I basically need to program to read a text file, but only the first part of each line.
The text file currently looks like
test1,Test1
test2,Test2
test3,Test3
I have a validation system so when a user signs up, it checks the username is not already taken. I just need to be able to check the usernames without the passwords, or in other words, read the line up to the comma. I already have the code to check the username and password for the login, which looks like this
String user = userText.getText();
String pString = String.valueOf(passwordText.getPassword());
File file = new File("C:/Users/Will/Desktop/UnPs.txt");
boolean found = false;
Scanner scan = null;
try {
scan = new Scanner(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(scan.hasNextLine() && found == false) {
String passCheck = scan.nextLine();
if(passCheck.equals(user + "," + pString)) {
System.out.println("Found");
found = true;
}
else if(!passCheck.equals(user + "," + pString)) {
System.out.println("not found");
}
}
I'm sure this has been asked before, but I can't seem to find anything related to the subject.
As I understand it, you can do something like this
Scanner read = new Scanner (new File("C:/Users/Will/Desktop/UnPs.txt"));
read.useDelimiter(",");
String name, pwd;
while(read.hasNext())
{
name = read.next();
pwd= read.next();
System.out.println(name+ " " + pwd + "\n"); //just for debugging
}
read.close();
Or use split method : https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#split(java.lang.String)
maybe too simple, but try
...
String nameCheck = scan.nextLine();
if (nameCheck.startsWith(userName + ",")) {
...
to really get the name of each line:
...
String line = scan.nextLine();
int comma = line.indexOf(',');
if (comma != -1) {
String name = line.substring(0, comma);
...
} else {
//no comma? error message, or just ignore
}
or using regular expression :
...
String line = scan.nextLine();
String name = line.replaceFirst(",.*", "");
...
despite I think that regular expression is kind of an overkill here...but neat

Count number of lines that starts with & character in CSV file [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
BufferedReader is skipping every other line when reading my file in java
(3 answers)
Closed 2 years ago.
I am trying to make a function that will count how many lines starts with & in given file.
So far i came up with following function
public int CountNumberOfTexts(String filename) {
try{
File file = new File(filename);
if(file.exists()){
FileReader fr = new FileReader(file);
LineNumberReader lnr = new LineNumberReader(fr);
int linenumber = 0;
while (lnr.readLine() != null){
if (lnr.readLine().substring(0,1) == "&") {
linenumber++;
}
}
Log.d("Count", "NUMBER OF LINES: " + linenumber);
lnr.close();
return linenumber;
}else{
System.out.println("File does not exists: " + filename);
}
}catch(IOException e){
e.printStackTrace();
}
return 0;
}
Current Function error is: Not recognizing lines starting with & character.
You are facing two problems:
You are reading in two lines, but only evaluating every second:
while (lnr.readLine() != null){ <- first consumption
if (lnr.readLine().substring(0,1) == "&") { <- second
You are comparing strings with == operator instead of equals method. Or in your case you can even use startsWith method which is created precisely for scenarios like yours.
This will do the trick:
String line;
while ((line = lnr.readLine()) != null){
if (line.startsWith("&")) {

how to trim a string twice and getting different info? [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 6 years ago.
I'm working an project where the program is supposed to analyze other project, the other projects are located in a specisfic directory. The projects are named under a standard similar to the following:
Projectname-version-downloadingDate example:
ElasticSearch-1.0-20160417
right now the program can return the whole project name as one string and save it to CSV file, using the following methods:
private String projectName;
public void setProjectName(String projectName){
this.projectName = projectName;
}
public String getProjectName(){
return projectName;
}
and here is the method call for writing the name of the project:
private void writeReport() {
BufferedWriter out = null;
try {
File file = new File("out.csv");
boolean exists = file.exists();
FileWriter fstream = new FileWriter(file, exists /*=append*/);
out = new BufferedWriter(fstream);
if (!exists) {
out.write("File Name;");
out.write(System.getProperty("line.separator"));
}
out.write(String.valueOf(newFiles.getProjectName()) + ";"); //method call
out.write(System.getProperty("line.separator"));
// }
//Close the output stream
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
// return;
}
}
now my question is how can I split the name of the project into three parts and write each one separated in the CSV file?
the project name, the version and the download date? meaning that it should take the project name from the substring located before the first "-" and the version after the first "-" and finally the date after the second "-"?
any tips how to do that?
thanks
Use the string.split method.
String string = "ElasticSearch-1.0-20160417";
String[] parts = string.split("-");
String projectName = parts[0]; // ElasticSearch
String versionNumber= parts[1]; // 1.0
String downloadDate= parts[2]; // 20160417

Categories