So I am a beginner with Java and I am having a hard time learning so please be easy. I am working on a solution that would take the users input of UK currency and find the exchange rate for a user input country. Don't know that I am on the right track or not but below is the code for after the user inputs the currency amount and country to convert to. I am needing to read a web based CSV file and parse in into a POJO but I can not get the in.useDelimiter to work.
public static Double findExchangeRateAndConvert(String currencyType, double amount) throws IOException {
URL url = new URL("https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/842362/exrates-monthly-1119.csv");
try (var in = new Scanner(
new BufferedReader(
new InputStreamReader(url.openStream())))) {
var line = "";
in.useDelimiter(",");
while (in.hasNextLine()) {
line = in.nextLine();
System.out.println(line);
if (line.contains(currencyType)) {
System.out.println("I found it.");
System.exit(0);
}
}
}
return null;
}
Use your scanner to read a line at a time, and then split the line based on regexp. Line by line processing is a good approach as it simple to understand what is happening.
public class Main {
public static void main(String[] args) throws IOException {
Double d = Main.findExchangeRateAndConvert("USD", 12);
System.out.println("d=" + d);
}
public static Double findExchangeRateAndConvert(String currencyType, double amount) throws IOException {
URL url = new URL("https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/842362/exrates-monthly-1119.csv");
try (var in = new Scanner(
new BufferedReader(
new InputStreamReader(url.openStream())))) {
var line = "";
in.useDelimiter(",");
while (in.hasNextLine()) {
line = in.nextLine();
System.out.println(line);
String[] splitLine = line.split(",");
if (splitLine[2].equals(currencyType)) {
System.out.println("I found it.");
return Double.valueOf(splitLine[3]);
}
}
}
return null;
}
}
Related
I have program that has a section that requires me to read and append items to a txt file. I know how to do basic reading and appending but I am confused as to how I would read every 4th line in a txt file and then store it in a variable. Or even every alternate line.
Also, if there are double valued numbers, can I read it as a number and not a string?
To read say every fourth line from a text file you would read a line and update a counter. When the counter reaches 4, you save the line in a String variable. Something like this would do the job:
import java.io.*;
public class SkipLineReader {
public static void main(String[] args) throws IOException {
String line = "";
String savedLine = "";
int counter = 0;
FileInputStream fin = new FileInputStream("text_file.txt");
BufferedReader bufIn = new BufferedReader(new InputStreamReader(fin));
// Save every fourth line
while( (line = bufIn.readLine()) != null) {
counter++;
if( counter == 4 ) {
savedLine = line;
System.out.println(line);
}
}
}
}
To save every alternate line, you would save the line every time the counter reaches two and then reset the counter back to zero. Like this:
// Save every alternate line
while( (line = bufIn.readLine()) != null) {
counter++;
if( counter % 2 == 0 ) {
counter = 0;
savedLine = line;
System.out.println(line);
}
}
As for reading doubles from a file, you could do it with a BufferedReader and then use Double's parseDouble(string) method to retrieve the double value, but a better method is to use the Scanner object in java.util. The constructor for this class will accept a FileInputStream and there is a nextDouble() method that you can use to read a double value.
Here's some code that illustrates using a Scanner object to grab double values from a String (to read from a file, supply a FileInputStream into the Scanner class's constructor):
import java.util.*;
public class ScannerDemo {
public static void main(String[] args) {
String s = "Hello World! 3 + 3.0 = 6 true";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// use US locale to be able to identify doubles in the string
scanner.useLocale(Locale.US);
// find the next double token and print it
// loop for the whole scanner
while (scanner.hasNext()) {
// if the next is a double, print found and the double
if (scanner.hasNextDouble()) {
System.out.println("Found :" + scanner.nextDouble());
}
// if a double is not found, print "Not Found" and the token
System.out.println("Not Found :" + scanner.next());
}
// close the scanner
scanner.close();
}
}
This is my code example.
public static void main(String[] args) throws Exception {
// Read file by BufferedReader line by line.
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("test.txt"));
String line = reader.readLine();
while (line != null) {
line = line.trim();
System.out.println(line);
// Using regular expression to check line is valid number
if (!line.trim().equals("") && line.trim().matches("^\\d+||^\\d+(\\.)\\d+$")) {
double value = Double.valueOf(line.trim());
System.out.println(value);
} else {
String value = line.trim();
System.out.println(value);
}
// Read next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Hello so i have an assignment and my code is not working. I ask a user to input a filename and after that it freezes and does not process the number of lines. im doing something wrong but im not sure what? can someone please help me im really desperate this part is crashing my whole program and i might fail and i dont know who to ask :( for help
public static void fileReader()
{
Scanner sc = new Scanner(System.in);
int catNum;
int dogNum;
int fishNum;
String fileName;
System.out.println("Please enter the Name of the file you want to read in
from");
fileName = sc.nextLine();
System.out.println("this is the file name --> "+fileName);
catNum = TestFile.getNum(fileName, "cat");
dogNum = TestFile.getNum(fileName, "dog");
fishNum = TestFile.getNum(fileName, "fish");
System.out.println("THE CAT IS" +catNum);
System.out.println("THE DOG IS" +dogNum);
System.out.println("THE FISH IS" +fishNum);
}
i dont see anything wrong after i ask for the file name it freezes
public static int getNum (String fileName, String word) {
Scanner sc = new Scanner(System.in);
int lineNum = 0;
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
try {
fileStrm = new FileInputStream (fileName);
rdr = new InputStreamReader (fileStrm);
bufRdr = new BufferedReader (rdr);
line = bufRdr.readLine();
while (line != null)
{
String firstWord = processString(line);
if(firstWord.equalsIgnoreCase(word)) //this submodule i going to get the number to create each array like e.g. how many states so that it can create it in country object
{
lineNum++;
line = bufRdr.readLine() ;
}
}
fileStrm.close();
}
catch (IOException e)
{
if (fileStrm != null)
{
try
{
fileStrm.close();
}
catch(IOException ex2)
{
System.out.println("This is Error");
}
}
System.out.println("error reading file !!" +e.getMessage());
}
return lineNum; }
the file looks something like this (each line is like this):
CAT:NAME=doopie:SHORTNAME=doop:LANGUAGE=English:AREA=America:POPULATION=2222:POPREF=Census2016
Look at this while loop:
while (line != null)
{
String firstWord = processString(line);
if(firstWord.equalsIgnoreCase(word)) //this submodule i going to get the number to create each array like e.g. how many states so that it can create it in country object
{
lineNum++;
line = bufRdr.readLine() ;
}
}
If firstWord.equalsIgnoreCase(word) returns false, then what will happen? The value of line will never be updated and the loop will never exit.
I have a text file that looks like this
BEG#Belgrave#19 February 1962
FSS#Flinders Street#12 September 1854
TSN#Tecoma#1 February 1924
im trying to write a program, asking the user to input the filename (i can do this part), then the user is prompted to enter in a "Code". The program is then to read the txt file, and output information according the the unique code.
for example:
java Codes
Enter file name >> stationsMaster.txt
Enter station code >> FSS
Station name: "Flinders" has code "FSS" date built: 12 September 1854
here is the code of what i have done so far, im just really stuck on how to write the code so that the program reads through the text file and outputs the according information from the user input.
import java.util.*;
import java.io.*;
public class Codes
{
public static void main (String [] args) throws IOException
{
Scanner keyboard = new Scanner (System.in);
System.out.print("Enter File Name");
String filename = keyboard.nextLine();
File f = new File (filename);
Scanner fin = new Scanner (f);
String stationcode = fin.nextLine();
String stationname = fin.nextLine();
String date = fin.nextLine ();
while (fin.hasNextLine ( ) )
{
System.out.print (date);
System.out.print(stationname);
}
fin.close ();
}
You can try something like this: hope this can solve your problem
public class Test {
private Map<String, Station> stationMap = new HashMap<>();
public static void main(String[] args) throws Exception {
// first read the file and store the data to the map
Test test = new Test();
test.readFile();
// now ask the user for the station code
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Please enter the code: ");
String code = scanner.nextLine();
Station station = test.stationMap.get(code.toUpperCase());
if (station == null) {
System.out.println("There is no such station present fot this code!");
continue;
}
System.out.println("Station name: "+station.getName());
System.out.println("Station code: "+station.getCode());
System.out.println("Station built date: "+station.getBuiltDate());
}
}
private void readFile() {
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("path/to/file")))) {
String line;
while ((line = reader.readLine()) != null) {
String[] strs = line.split("#");
Station station = new Station(strs[0], strs[1], strs[2]);
stationMap.put(station.getCode().toUpperCase(), station);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private class Station {
private String name;
private String code;
private String builtDate;
public Station(String name, String code, String builtDate) {
this.name = name;
this.code = code;
this.builtDate = builtDate;
}
public String getName() {
return name;
}
public String getCode() {
return code;
}
public String getBuiltDate() {
return builtDate;
}
}
}
I am having an issue trying to search a text file for the exact input that a user enters. I want to output the sentence not only by direct user input but i want the program to recognize some word(s) that would signal the desired text. I got searching for the keyword part down pack and working but i am only able to search the text based on the keyword. I want to search based on the keyword and the entire inputted sentence. For example if the keyword is e-mail and the user enter's what is mars e-mail? and the text file contains "mars e-mail is mars3433#aol.com, john e-mail is anonymous" i want to output mars e-mail is ... instead of both sentences. I am completely stuck trying to figure out this issue, Can anyone help me?
public static class DicEntry {
String key;
String[] syns;
Pattern pattern;
public DicEntry(String key, String... syns) {
this.key = key;
this.syns = syns;
pattern = Pattern.compile(".*(?:"
+ Stream.concat(Stream.of(key), Stream.of(syns))
.map(x -> "\\b" + Pattern.quote(x) + "\\b")
.collect(Collectors.joining("|")) + ").*");
}
}
public static void removedata(String s) throws IOException {
File f = new File("data.txt");
File f1 = new File("data2.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while ((line = br.readLine()) != null) {
if (line.contains(s)) {
System.out.println("Enter new Text :");
String newText = input.readLine();
line = newText;
System.out.println("Thank you, Have a good Day!");
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
public static void parseFile(String s) throws IOException {
File file = new File("data.txt");
Scanner forget = new Scanner(System.in);
Scanner scanner = new Scanner(file);
int flag_found = 0;
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
flag_found = 1;
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(lineFromFile);
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
}
}
if (flag_found == 0) {// input is not found in the txt file so
// flag_found remains 0
writer();
}
}
public static void writer() {
Scanner Keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
File file = new File("data.txt");
try (BufferedWriter wr = new BufferedWriter(new FileWriter(
file.getAbsoluteFile(), true))) { // Creates a writer object
// called wr
// file.getabsolutefile
// takes the filename and
// keeps on storing the old
System.out.println("I Do not know, Perhaps you want to teach me?"
+ "..."); // data
while ((Keyboard.hasNext())) {
String lines = Keyboard.nextLine();
System.out.print(" is this correct ? ");
String go = input.nextLine();
if (go.equals("no")) {
System.out.println("enter line again");
lines = Keyboard.nextLine();
System.out.print(" is this correct ? ");
go = input.nextLine();
}
else if (go.equals("yes")) {
wr.write(lines);
// wr.write("\n");
wr.newLine();
wr.close();
}
System.out.println("Thankk you");
break;
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
}
private static List<DicEntry> populateSynonymMap() {
List<DicEntry> responses = new ArrayList<>();
responses.add(new DicEntry("student", "pupil", "scholar"));
responses.add(new DicEntry("office", "post", "room"));
responses.add(new DicEntry("topics", "semester talk"));
return responses;
}
public static void getinput() throws IOException {
List<DicEntry> synonymMap = populateSynonymMap(); // populate the map
Scanner scanner = new Scanner(System.in);
String input = null;
/* End Initialization */
System.out.println("Welcome ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
String[] inputs = input.split(" ");
int flag_found = 0;
for (DicEntry entry : synonymMap) { // iterate over each word of the
// sentence.
if (entry.pattern.matcher(input).matches()) {
// System.out.println(entry.key);
parseFile(entry.key);
flag_found = 1;// Input is found
}
}
if (flag_found == 0) {// input is not found in the txt file so
// flag_found remains 0
writer();
}
}
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
getinput();
}
}
So my methods work like this, the parse file method searching the text file for the keyword in the sentence. My writer( ) writes to the file if the input is not found and my remove data ( ) erases the line and updates it with the new string upon user request. and get input is just a method to get information from the scanner.
In my opinion, additional obstacle is fact, that some word can repeat in unrelated sentences. My solution seems to be quite long for me, but it works. However when I test it, I didn't use your dicEntry. It is impossible to hard-code all synonyms, so you should reconsider this approach.
I added one class, jast as data holder for int repetition variable (see below) and particular sentence:
public class Pair {
int repetitions;
String sentence;
public Pair(int rep, String string){
repetitions = rep;
sentence = string;
}
public int getRepetitions() {
return repetitions;
}
public String getSentence() {
return sentence;
}
}
Then I wrote a method, which loop through input sentence, and file content, looking for sentence from file, in which most inputs words repeted. I pretty sure, it is not most efficient way, but I don't know another :P.
public static String getMostAppropriate(String[] input) throws IOException{
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
ArrayList<Pair> pairs = new ArrayList<>();
int repetitions = 0;
while (scanner.hasNextLine()) {
String newLine = scanner.nextLine();
String[] line = newLine.split(","); // this regex depends on your file format style,
String oneSentence = "";
for(String sentence : line){ // for sentence in file lines
for(String string : sentence.split(" ")){ // for words in these sentences
for(String word : input){ // for words from input
if(word.equals(string)){
repetitions += 1;
oneSentence = sentence;
}
}
}
pairs.add(new Pair(repetitions,oneSentence));
repetitions = 0;
}
}
return mostCommon(pairs);
}
The argument is String[] inputs form your getInput method. In return statement I called another new method, which looks for sentences with most repetitions:
public static String mostCommon(ArrayList<Pair> pairs){
Pair max = new Pair(0,"");
String result = "";
for(Pair pair : pairs){
if(pair.getRepetitions() > max.getRepetitions()){
result = pair.getSentence();
max = pair;
}else if(pair.getRepetitions()==max.getRepetitions()){
result += "; " + pair.getSentence();
}
}
return result;
}
If some sentences have same number of repetitions, it returns both(or more) connected into one sentence (sentence; sentence; etc.).
Implementation into your code I left for you, if you are interested.
As I said, I didn't use your dicEntry, still you can add it as additional loop, but chacking whole dictionary will not be too effective with my method.
Also, if I were you, I would divide some of your methods into smaller one, I mean like: read file in one, ask for additional input in another. Because it is easier to implement changes this way. You don't need to keep eye on whole method, just arguments they pass to each other.
I hope you will find something useful in my post.
Ok so here is the code I created for the program to read a text file.
Now can someone tell me how to switch every letter's case from uppercase to lower and vice versa in the result? Notice that I want the program to read the file from the command line and not a string.
If possible I'd like the answer in code :| Thanks
I am very new in Java and could use some help thanks.
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
java.io.File file = new java.io.File("C:\\Users\\Lifeless\\Desktop\\123.txt");
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
String num = input.nextLine(); //grabs line
System.out.println(num);
}
}
catch (FileNotFoundException e) {
System.err.format("File does not exist \n");
I used a bufferedReader and put all lines of the file in an ArrayList.
static ArrayList<String> lines;
public static void main(String[] args) throws FileNotFoundException, IOException
{
lines = new ArrayList<>();
File f = new File(args[0]);
BufferedReader r = new BufferedReader(new FileReader(f));
String line = r.readLine ();
while(line != null)
{
lines.add(invert(line));
line = r.readLine ();
}
for(String s : lines)
{
System.out.println(s);
}
}
private static String invert(String line)
{
char[] singleChars = line.toCharArray (); //split Line into single Characters
for(int i = 0;i< singleChars.length;i++) //Iterate over every single Character
{
if(Character.isAlphabetic (singleChars[i]))
{
if(Character.isUpperCase (singleChars[i])) //swap Upper to Lower and vice versa
{
singleChars[i] = Character.toLowerCase (singleChars[i]);
}else
{
singleChars[i] = Character.toUpperCase (singleChars[i]);
}
}
}
return new String(singleChars);
}