I am making a exchange app but I'm growing frustrated and having trouble with a few steps. I know what I need to do, but in order to get there I am lost, if that makes sense. I just need help with steps to take to get to my result, no direct code. The direction says "From the text file provided [currency.txt] search for the three letter currency code of the countries typed in the textFields [CurrencyTo and CurrencyFrom]. For example, if CurrencyFrom is “United States”, your code should find the currency code ‘USD’ from the currency.txt file."
I know I need to (1) compare the country in the textbox with the country from the inputFile
and (2) if the same, then get the country code and save it in a variable.
Any advice or breakdown on the steps I need to take is all i'm looking for. Please no direct code! Thank You
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==calculateButton){
String from = currencyFrom.getText();
String to = currencyTo.getText();
try{
String line = "";
File inputFile = new File("currency.txt");
Scanner in = new Scanner(inputFile);
try{
while(in.hasNextLine()){
line = in.nextLine();
String[] lineContent = line.split("\t");
System.out.println(Arrays.toString(lineContent));
System.out.println(lineContent[0] + lineContent[1]);
//compare the country in the textbox with the country from the inputFile
//if they are the same, then get the country code and save it in a variable
}
}
finally{ in.close();
}
}
catch (FileNotFoundException ex) {
displayLabel.setText("File not found");}
//go to the website and get exchagne rate and do the calculation
String line = "";
String address = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=" + from + to + "=X";
try{
URL pageLocation = new URL(address);
Scanner in = new Scanner(pageLocation.openStream());
try{
while (in.hasNextLine()){
line = in.nextLine();
System.out.println(line);
String[] data = line.split(",");
System.out.println(Arrays.toString(data));
System.out.println(data[0] + data[1] + data[2] + data[3]);
//display calculation
displayLabel.setText("");
//display last update
updateLabel.setText("Last Updated: " + data[2] + data[3]);
}
}
finally{ in.close();
}
}
catch (MalformedURLException exception){
displayLabel.setText("Website not found!");}
catch (IOException ex) {}
if(event.getSource()==clearButton){
currencyTo.setText("");
currencyFrom.setText("");
amount.setText("100");
displayLabel.setText("");
updateLabel.setText("");
}
}
}
}
//add listener to the buttons
ActionListener listener = new ButtonListener();
clearButton.addActionListener(listener);
calculateButton.addActionListener(listener);
}
}
Related
I'm trying to do a small school practice about Java Text I/O and while trying to read a CSV file with name prefixes (a Dutch thing) and surnames I got a question mark in the beginning.
It's a small exercise where I need to add my code to an already existing project with 3 small files to practice the use of Text I/O, see project code: https://github.com/Remzi1993/klantenBestand
public void vulNamenLijst() {
// TODO: Lees het bestand "resources/NamenlijstGroot.csv" en zet elke regel (<tussenvoegsel>,<achternaam>)
// in de ArrayList namenLijst.
file = new File("resources/NamenlijstGroot.csv");
try (
Scanner scanner = new Scanner(file);
) {
while (scanner.hasNext()) {
String line = scanner.nextLine();
String[] values = line.split(",");
String namePrefix = values[0];
String surname = values[1];
namenLijst.add(namePrefix + " " + surname);
}
} catch (FileNotFoundException e) {
System.err.println("Data file doesn't exist!");
} catch (Exception e) {
System.err.println("Something went wrong");
e.printStackTrace();
}
}
I'm sorry for the use of Dutch and English at the same time in the code. I try to write my own code in English, but this code exercise already existed and I only needed to add some code with the //TODO to practice Text I/O.
This is what I get:
My CSV file:
#funky is correct. Your file starts with a UTF8-BOM.
output of xxd:
00000000: efbb bf64 652c 4a6f 6e67 0a2c 4a61 6e73 ...de,Jong.,Jans
00000010: 656e 0a64 652c 5672 6965 730a 7661 6e20 en.de,Vries.van
The first three bytes are: ef bb bf
To mitigate the BOM using a 'standard' component, you can use Apache's BOMInputStream. Note that BOMs come in multiple flavours (see here for more details), and this should handle them all reliably.
If you have a sizeable project, you may find you have the BOMInputStream in your project already via commons-io
Scanner will take an input stream (see here)
I found an easy solution:
final String UTF8_BOM = "\uFEFF";
if (line.startsWith(UTF8_BOM)) {
line = line.substring(1);
}
A simple workable example:
File file = new File("resources/NamenlijstGroot.csv");
try (
Scanner scanner = new Scanner(file, StandardCharsets.UTF_8);
) {
while (scanner.hasNext()) {
String line = scanner.nextLine().strip();
final String UTF8_BOM = "\uFEFF";
if (line.startsWith(UTF8_BOM)) {
line = line.substring(1);
}
String[] values = line.split(",");
String namePrefix = values[0];
String surname = values[1];
namenLijst.add(namePrefix + " " + surname);
}
} catch (FileNotFoundException e) {
System.err.println("Data file doesn't exist!");
} catch (Exception e) {
System.err.println("Something went wrong");
e.printStackTrace();
}
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;
}
I have a text file named "message.txt" which is read using Buffer Reader. Each line of the text file contains both "word" and "meaning" as given in this example:
"PS:Primary school"
where PS - word, Primary school - meaning
When the file is being read, each line is tokenized to "word" and "meaning" from ":".
If the "meaning" is equal to the given input string called "f_msg3", "f_msg3" is displayed on the text view called "txtView". Otherwise, it displays "f_msg" on the text view.
But the "if condition" is not working properly in this code. For example if "f_msg3" is equal to "Primary school", the output on the text view must be "Primary school". But it gives the output as "f_msg" but not "f_msg3". ("f_msg3" does not contain any unnecessary strings.)
Can someone explain where I have gone wrong?
try {
BufferedReader file = new BufferedReader(new InputStreamReader(getAssets().open("message.txt")));
String line = "";
while ((line = file.readLine()) != null) {
try {
/*separate the line into two strings at the ":" */
StringTokenizer tokens = new StringTokenizer(line, ":");
String word = tokens.nextToken();
String meaning = tokens.nextToken();
/*compare the given input with the meaning of the read line */
if(meaning.equalsIgnoreCase(f_msg3)) {
txtView.setText(f_msg3);
} else {
txtView.setText(f_msg);
}
} catch (Exception e) {
txtView.setText("Cannot break");
}
}
} catch (IOException e) {
txtView.setText("File not found");
}
Try this
............
meaning = meaning.replaceAll("\\s+", " ");
/*compare the given input with the meaning of the read line */
if(meaning.equalsIgnoreCase(f_msg3)) {
txtView.setText(f_msg3);
} else {
txtView.setText(f_msg);
}
............
Otherwise comment the else part, then it will work.
I don't see any obvious error in your code, maybe it is just a matter
of cleaning the string (i.e. removing heading and trailing spaces, newlines and so on) before comparing it.
Try trimming meaning, e.g. like this :
...
String meaning = tokens.nextToken();
if(meaning != null) {
meaning = meaning.trim();
}
if(f_msg3.equalsIgnoreCase(meaning)) {
txtView.setText(f_msg3);
} else {
txtView.setText(f_msg);
}
...
A StringTokenizer takes care of numbers (the cause for your error) and other "tokens" - so might be considered to invoke too much complexity.
String[] pair = line.split("\\s*\\:\\s*", 2);
if (pair.length == 2) {
String word = pair[0];
String meaning = pair[1];
...
}
This splits the line into at most 2 parts (second optional parameter) using a regular expression. \s* stands for any whitespace: tabs and spaces.
You could also load all in a Properties. In a properties file the format key=value is convention, but also key:value is allowed. However then some escaping might be needed.
ArrayList vals = new ArrayList();
String jmeno = "Adam";
vals.add("Honza");
vals.add("Petr");
vals.add("Jan");
if(!(vals.contains(jmeno))){
vals.add(jmeno);
}else{
System.out.println("Adam je už v seznamu");
}
for (String jmena : vals){
System.out.println(jmena);
}
try (BufferedReader br = new BufferedReader(new FileReader("dokument.txt")))
{
String aktualni = br.readLine();
int pocetPruchodu = 0;
while (aktualni != null)
{
String[] znak = aktualni.split(";");
System.out.println(znak[pocetPruchodu] + " " +znak[pocetPruchodu + 1]);
aktualni = br.readLine();
}
br.close();
}
catch (IOException e)
{
System.out.println("Nezdařilo se");
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter("dokument2.txt")))
{
int pocetpr = 0;
while (pocetpr < vals.size())
{
bw.write(vals.get(pocetpr));
bw.append(" ");
pocetpr++;
}
bw.close();
}
catch (IOException e)
{
System.out.println("Nezdařilo se");
}
So say for example I have this file
I want my program to search for the title and respective author using the input from the user and then ask for replacement values. Then these replacements will change the current value in the file.
This is my current implementation:
import java.io.*;
import javax.swing.*;
public class SecondChild4 extends SecondParent
{
public void edit(String sFileName, String sFileName2)
{
try
{
sFileName2 = "Second.txt";
File nfile2 = new File("Second.txt");
File file2 = new File("TempSecond.txt");
FileReader reader2 = new FileReader(sFileName2);
BufferedReader br2 = new BufferedReader(reader2);
FileWriter twriter2 = new FileWriter(file2);
BufferedWriter tbw2 = new BufferedWriter(twriter2);
String line2 = "";
String edit2 = "";
String btitle = JOptionPane.showInputDialog (null, "Title: ", "");
String bauthor = JOptionPane.showInputDialog (null, "Author: ", "");
//how to search if value was found from the file?
String btitle1 = JOptionPane.showInputDialog (null, "Replace with title: ", "");
String bauthor1 = JOptionPane.showInputDialog (null, "Replace with author: ", "");
line2 = br2.readLine();
while(line2 != null){
if (line2 == null)
{
// End of File
tbw2.close();
br2.close();
}
else if(what condition to put here?)
{
System.out.println("Search found");
edit = line2.replaceAll(btitle, btitle1);
edit2 = line2.replaceAll(bauthor, bauthor1);
tbw1.append(edit);
tbw1.append(",");
tbw1.append(edit2);
tbw1.append("\n");
tbw2.write(edit);
tbw2.write("\t");
tbw2.write(edit2);
tbw2.newLine();
tbw1.close();
tbw2.close();
br1.close();
br2.close();
}
else{
tbw1.append(line1);
tbw1.append("\n");
tbw2.write(line2);
tbw2.newLine();
tbw1.close();
tbw2.close();
br1.close();
br2.close();
}
}
file2.delete();
file2.renameTo(nfile2);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
I made a temp file for the storage of the modified values and then delete the old file and rename the temp file according to the previous file's name. In the code I made, there are problems such as the file contents get empty(I am also saving it in csv but did not put the codes related to that here. When it comes to csv, only the first line of the previous file gets rewritten to the temp), the file don't get deleted and renamed.
I know there are lots of mistakes with my code. I'm pretty new to programming. Please help me :)
You can do it nicely by creating a book.properties file like
Title=Foo
Author=bar
Java code will be like :
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class SecondChild4 {
private InputStream inputStream;
public static void main(String[] args) {
SecondChild4 s = new SecondChild4();
s.getPropValues();
}
public String getPropValues() {
String result = "";
try {
Properties prop = new Properties();
String propFileName = "book.properties";
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
// get the property value and print it out
String title = prop.getProperty("Title");
String author = prop.getProperty("Author");
result = "Book = " + author + " title " + title;
System.out.println("current book details are " + result);
// replace logic here
prop.setProperty("Title", "Hamlet");
prop.setProperty("Author", "William Shakespeare");
System.out.println("after modification");
result = "Book = " + prop.getProperty("Author") + " title " + prop.getProperty("Title");
System.out.println("cuurrent book details are " + result);
} catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
}
Output :
current book details are Book = bar title Foo after modification
current book details are Book = William Shakespeare title Hamlet
Some things for you to remember while coding :
Dont put everything in try catch block just for sake of avoiding exceptions,keep only part that actually throws that exception...not whole code.
call all close methods eg: buffereader.close() in finally block
Never, never, never throw an exception , instead catch it there itself.
I just did a simple code which takes user name and phone number and save those into an arraylist by creating object. I want to save those information (name and phonenumber) into a text file so that all old information I can get again. How do I do it? Here is my code ...
import java.util.ArrayList;
import java.util.Scanner;
public class manager {
Scanner input = new Scanner(System.in);
ArrayList <objectclass> Test = new ArrayList <objectclass> ();
public void mainloop() {
for (int i = 0; i < 100; i++) {
String x;
System.out.println("Please Select your option");
System.out.println("............................");
System.out.println("1 ADD NAME AND NUMBER\n2 SEARCH NAME AND NUMBER \n0 EXIT");
System.out.println("............................");
x = input.nextLine();
if (x.equalsIgnoreCase("0")) {
System.out.println("Thank you!");
break;
}
if (x.equalsIgnoreCase("1")) {
String Name;
String Number;
System.out.println("Please Enter your Name below");
Name = input.nextLine();
System.out.println("Please Enter your Number below");
Number = input.nextLine();
objectclass objectclassObject = new objectclass(Name, Number);
Test.add(objectclassObject);
}
if (x.equalsIgnoreCase("2")) {
String y;
System.out.println("*** Enter your Name below for search ***");
y = input.nextLine();
for (objectclass p : Test) {
String z = p.getName();
if (z.equalsIgnoreCase(y)) {
System.out.println("Your Name is: " + p.getName() + "\nYour Number is: " + p.getNumber());
System.out.println("");
} else {
System.out.println("Contact not Found!\n");
}
}
}
}
}
}
I want to save all name and number that I store in arraylist into a text file ... how can I do it?
I tried this so far but don't know what to do next ...
import java.io.;
import java.lang.;
import java.util.*;
public class creatfile {
private Formatter x;
public void openFile(){
try{
x = new Formatter("testkyo");
}catch (Exception e){
System.out.println("you have an error");
}
}
public void addRecord(){
x.format();
}
public void closeFile(){
x.close();
}
You need to serialize an object in order to save it onto the file .
here's a tutorial on how to do it, its really simple.
When you serialize an object you can write it onto a file and then load it as it is from there .
EDIT :
example on how you could use this here , i guess the ObjectClass is the thing u want to save so :
class ObjectClass implements Serializable {
String name;
String number;
//constructor , setters , getters and w.e functions .
public static void main (String args[]){
try{
ObjectClass test = new ObjectClass("test",2);
File f = new File("path to file");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(test); // this will write the object as it is onto the file
out.close();
}catch(Exception ex){}
}
}
you wont be able to read the data cuz its serialised , but u can load them as objects like so :
ObjectInputStream in = new ObjectInputStream(new File("path to file"));
ObjectClass test =(ObjectClass) in.readObject(); // u have to cast from Object to Objectclass
what you propably want is an ObjectOutputstream writing your ArrayList to a file via an FileOutputStream when the porgram is exiting and reading the Arraylist with the coresponding InputStreams. See the links below:
http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html
http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html
A simple example:
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("./output.txt"));
writer.write("Hello World");
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
This will write "Hello World" in the text file named: "output.txt".
Check the java I/O api.
You can find a lot of tutorials on the web about this, like:
Reading, Writing, and Creating Files
Creating, Writing, Reading files using Java Files API of Java 7