I need help making changes to a text file in java - java

I am working on my project for intro to programming. The program is supposed to use a text file as a database to store first names, last names, and phone numbers. The program needs to be able to manipulate the data on the text file.
Instructions
Here is my entire code so far:
import java.util.*;
import java.io.*;
import java.lang.*;
import java.nio.*;
public class Project
{
private static Scanner input;
private static Formatter x;
public static void main(String[] args)
{
String choice = "";
Scanner userInput = new Scanner(System.in);
System.out.printf("Please choose one of the following commands:%nL (Listing), I (insert), S (search), D (delete)%nM (modify), W (write), Q (quit with saving)");
loop: while (choice != "Q") {
System.out.printf("%nEnter your Command: ");
choice = userInput.nextLine();
switch (choice)
{
case "L":
Listing();
break;
case "I":
Insert();
break;
case "S":
break;
case "D":
break;
case "M":
break;
case "W":
break;
case "Q":
break loop;
} // end switch statement
} // end while loop
} // end method main
public static void Listing() // List records from MiniDB.txt file
{
try {
File file = new File("MiniDB.txt");
input = new Scanner(file);
}
catch (IOException ioException) {
System.err.println("Cannot open file.");
System.exit(1);
}
if (input.hasNext()) { // If there are records in the file print them, else print none found
while (input.hasNext()) // while there is more to read
{
String firstName = input.next();
String lastName = input.next();
String phoneNumber = input.next();
System.out.printf("%-13s%-13s%s%n", firstName + ",", lastName, phoneNumber); }
}
else {
System.out.printf("No records found");
}
} // end method Listing
public static void Insert() // insert a record
{
try {
String file = "MiniDB.txt";
input = new Scanner(System.in);
PrintWriter outputStream = new PrintWriter(new FileWriter(file, true) );
System.out.printf("Last Name: ");
String lastName = input.next();
System.out.printf("%nFirst Name: ");
String firstName = input.next();
System.out.printf("%nTelephone Number: ");
String phoneNumber = input.next();
outputStream.printf("%n%s %s %s", firstName, lastName, phoneNumber);
outputStream.close();
System.out.printf("%nDone.");
}
catch (IOException ioException) {
System.err.println("Cannot open file.");
System.exit(1);
}
} // end method Insert
public static void Search(); // search a record
{
}
} // end class Project
What I need help with is understanding how to create the "write" command. Currently, my code makes the changes to the text file automatically, but I need it to finalize changes only when W is inputted. I've been reading for awhile on this and I'm completely stuck. Do I need to rewrite what I have?
I was thinking about making all the changes on a temp.txt file and then if W is inputted, renaming temp.txt MiniDB.txt and overwriting that file. I would then need to delete the temp.txt file. I feel like there should be an easier way?

For a basic solution why don't you keep the database in memory then update that. When the update is complete just write the in memory version to a file

I suspect you are taking the wrong approach to solving this. If you are supposed to write the file on a command (W) then the best solution is to hold the list of numbers in memory and then write it out again when the user asks for it.
So something like:
class Entry {
private String firstName;
private String lastName;
private String phoneNumber;
}
List<Entry> entries;
When you receive a 'W' command you can iterate through the list of entries and write each one to the file.

One way is to keep your data at temp using some memory object
and write changes to your DB when you finalize .
I have modified the above code as per your requirements
Kindly check
import java.util.*;
import java.io.*;
import org.json.JSONException;
import org.json.JSONObject;
public class Project {
private static Scanner input;
static JSONObject obj = new JSONObject();
static String choice = "";
static int i = 0;
final static String file_path = "d:\\1\\MiniDB.txt";
public static void menu() throws IOException, JSONException {
System.out.println("Please choose one of the following commands:");
System.out.println("L (Listing)");
System.out.println("I (Insert)");
System.out.println("D (delete)");
System.out.println("S (search)");
System.out.println("M (modify)");
System.out.println("W (write)");
System.out.println("Q (quit with saving)");
choice = input.nextLine();
if (choice.equalsIgnoreCase("I")) {
Insert();
}
if (choice.equalsIgnoreCase("L")) {
Listing();
}
if (choice.equalsIgnoreCase("W")) {
write(obj);
}
if (choice.equalsIgnoreCase("Q")) {
i = 1;
System.out.println("End");
}
}
public static void main(String[] args) {
try {
input = new Scanner(System.in);
while (i == 0) {
menu();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void Listing() // List records from MiniDB.txt file
{
try {
File file = new File(file_path);
input = new Scanner(file);
} catch (IOException ioException) {
System.err.println("Cannot open file.");
System.exit(1);
}
if (input.hasNext()) { // If there are records in the file print them,
// else print none found
while (input.hasNext()) // while there is more to read
{
String firstName = input.next();
String lastName = input.next();
String phoneNumber = input.next();
System.out.printf("%-13s%-13s%s%n", firstName + ",", lastName,
phoneNumber);
}
} else {
System.out.printf("No records found");
}
} // end method Listing
public static void Insert() // insert a record
{
try {
System.out.println("Last Name: ");
obj.put("Last Name", input.nextLine());
System.out.println("First Name: ");
obj.put("First Name", input.nextLine());
System.out.println("Telephone Number: ");
obj.put("Telephone Number", input.nextLine());
} catch (Exception e) {
System.exit(1);
}
}
public static void write(JSONObject obj2) throws IOException, JSONException {
File file = new File(file_path);
PrintWriter outputStream = new PrintWriter(new FileWriter(file, true));
outputStream.printf("%n%s %s %s", obj.get("Last Name"),
obj.get("First Name"), obj.get("Telephone Number"));
System.out.println("changes Done.");
outputStream.close();
}
public static void Search() {
}
{
}
} // end class Project
I hope this would solve your problem.
Thank you!! Happy coding..

Related

Java method call issue, going back to main menu from a new .java class, possible array problem

First I am sorry for all the questions but I am at a loss and have spent the last week working on this. I am new to the community so please work with me while I learn the format that I need to have in place.
Okay so I am working on my final project for a class and I have been given a help document and two .txt files. I have the .txt files on the right level where they can be called from any computer. I have also gotten my code to where it calls the right array to get a new submenu to come up after selection from the main menu. From there I am having problems calling a method (showdata) to have a JOptionPane pop up with an alert that must be displayed if there is a call for it from the .txt file namely it will have (*****) in front of it. I also have to add an option for the user to go back to the main menu instead of it just closing the program but I am unsure where I can put this option. I don't know if I should add it in the default loop or in my switch statement. Any help would be great. Thanks so much.
I have now included my .txt files below.
My main code is:
import java.util.Scanner;
public class Monitor {
private static Scanner usrch = new Scanner(System.in);
/**
*
* #param args
*/
public static void main(String[] args) {
AnimalsHabitat methodCall = new AnimalsHabitat();
try {
int userChoice = mainMenu();
switch(userChoice) {
case 1:
System.out.println("Please pick the animal you would like to monitor: ");
System.out.println("");
methodCall.askForWhichDetails("animals");
System.out.println("Press 0 to go back.");
break;
case 2:
System.out.println("Please pick the habitat you would like to monitor: ");
System.out.println("");
methodCall.askForWhichDetails("habitats");
System.out.println("Press 0 to go back.");
break;
case 3:
System.out.println("Have a nice day!");
System.exit(0);
break;
default:
int loopError = 0;
while (loopError < 3) {
loopError++;
if (loopError == 3) {
System.out.println("Error in program loop, exiting program.");
System.exit(0);
}
}
}
}
catch (Exception e) {
System.out.println("Wrong input " + e.getMessage());
}
}
public static int mainMenu() {
System.out.println("Welcome to the Zoo Monitoring System!");
System.out.println("Please select what you would like to monitor: ");
System.out.println("");
System.out.println("1.) Animals");
System.out.println("2.) Habitats");
System.out.println("3.) Exit program");
int userChoice = Integer.parseInt(usrch.nextLine());
return userChoice;
}
}
My help code is:
import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class AnimalsHabitat {
private String filePath;
final private Scanner scnr;
public AnimalsHabitat() {
filePath = "";
scnr = new Scanner(System.in);
}
public void askForWhichDetails(String fileName) throws IOException {
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
String textLine = null;
ArrayList aList1 = new ArrayList();
int i = 0;
int option = 0;
boolean bailOut = false;
// Try to open file
fileByteStream = new FileInputStream(filePath + fileName + ".txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine() && bailOut == false) {
textLine = inFS.nextLine();
if (textLine.contains("Details")) {
i += 1;
System.out.println(i + ". " + textLine);
ArrayList aList2 = new ArrayList();
for (String retval : textLine.split(" ")) {
aList2.add(retval);
}
String str = aList2.remove(2).toString();
aList1.add(str);
} else {
System.out.print("Enter selection: ");
option = scnr.nextInt();
System.out.println("");
if (option <= i) {
String detailOption = aList1.remove(option - 1).toString();
showData(fileName, detailOption);
bailOut = true;
}
break;
}
}
// Done with file, so try to close it
fileByteStream.close(); // close() may throw IOException if fails
}
public void showData(String fileName, String detailOption) throws IOException {
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
String textLine = null;
String lcTextLine = null;
String alertMessage = "*****";
int lcStr1Len = fileName.length();
String lcStr1 = fileName.toLowerCase().substring(0, lcStr1Len - 1);
int lcStr2Len = detailOption.length();
String lcStr2 = detailOption.toLowerCase().substring(0, lcStr2Len - 1);
boolean bailOut = false;
// Try to open file
fileByteStream = new FileInputStream(filePath + fileName + ".txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine() && bailOut == false) {
textLine = inFS.nextLine();
lcTextLine = textLine.toLowerCase();
if (lcTextLine.contains(lcStr1) && lcTextLine.contains(lcStr2)) {
do {
System.out.println(textLine);
textLine = inFS.nextLine();
if (textLine.isEmpty()) {
bailOut = true;
}
if (textLine.contains(alertMessage)) {
JOptionPane.showMessageDialog(null, textLine.substring(5));
}
} while (inFS.hasNextLine() && bailOut == false);
}
}
// Done with file, so try to close it
fileByteStream.close(); // close() may throw IOException if fails
}
void showData() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
This is my animals.txt
Details on lions
Details on tigers
Details on bears
Details on giraffes
Animal - Lion
Name: Leo
Age: 5
*****Health concerns: Cut on left front paw
Feeding schedule: Twice daily
Animal - Tiger
Name: Maj
Age: 15
Health concerns: None
Feeding schedule: 3x daily
Animal - Bear
Name: Baloo
Age: 1
Health concerns: None
*****Feeding schedule: None on record
Animal - Giraffe
Name: Spots
Age: 12
Health concerns: None
Feeding schedule: Grazing
This is my habitats.txt:
Details on penguin habitat
Details on bird house
Details on aquarium
Habitat - Penguin
Temperature: Freezing
*****Food source: Fish in water running low
Cleanliness: Passed
Habitat - Bird
Temperature: Moderate
Food source: Natural from environment
Cleanliness: Passed
Habitat - Aquarium
Temperature: Varies with output temperature
Food source: Added daily
*****Cleanliness: Needs cleaning from algae
Does this work for you?
Monitor.java
import java.util.Scanner;
public class Monitor
{
private static Scanner usrch = new Scanner(System.in);
/**
*
* #param args
*/
public static void main(String[] args)
{
AnimalsHabitat methodCall = new AnimalsHabitat();
try
{
int userChoice = mainMenu();
switch(userChoice)
{
case 1:
System.out.println("Please pick the animal you would like to monitor: ");
System.out.println("");
methodCall.askForWhichDetails("animals");
break;
case 2:
System.out.println("Please pick the habitat you would like to monitor: ");
System.out.println("");
methodCall.askForWhichDetails("habitats");
break;
case 3:
System.out.println("Have a nice day!");
System.exit(0);
break;
default:
int loopError = 0;
while (loopError < 3)
{
loopError++;
if (loopError == 3)
{
System.out.println("Error in program loop, exiting program.");
System.exit(0);
}
}
}
}
catch (Exception e)
{
System.out.println("Wrong input " + e.getMessage());
}
}
public static int mainMenu()
{
System.out.println("Welcome to the Zoo Monitoring System!");
System.out.println("Please select what you would like to monitor: ");
System.out.println("");
System.out.println("1.) Animals");
System.out.println("2.) Habitats");
System.out.println("3.) Exit program");
int userChoice = Integer.parseInt(usrch.nextLine());
return userChoice;
}
}
AnimalsHabitat.java
import java.util.Scanner;
import java.io.IOException;
import java.io.FileInputStream;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class AnimalsHabitat
{
private String filePath;
final private Scanner scnr;
public AnimalsHabitat()
{
filePath = "";
scnr = new Scanner(System.in);
}
public void askForWhichDetails(String fileName) throws IOException
{
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
String textLine = null;
ArrayList aList1 = new ArrayList();
int i = 0;
int option = 0;
boolean bailOut = false;
// Try to open file
fileByteStream = new FileInputStream(filePath + fileName + ".txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine() && bailOut == false)
{
textLine = inFS.nextLine();
if (textLine.contains("Details"))
{
i += 1;
System.out.println(i + ". " + textLine);
ArrayList aList2 = new ArrayList();
for (String retval : textLine.split(" "))
{
aList2.add(retval);
}
String str = aList2.remove(2).toString();
aList1.add(str);
}
else
{
while(option != (i + 1))
{
System.out.print("Enter selection or enter " + (i + 1) + " to exit: ");
option = scnr.nextInt();
System.out.println("");
if (option <= i)
{
String detailOption = aList1.remove(option - 1).toString();
showData(fileName, detailOption);
}
}
break;
}
}
// Done with file, so try to close it
fileByteStream.close(); // close() may throw IOException if fails
}
public void showData(String fileName, String detailOption) throws IOException
{
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
String textLine = null;
String lcTextLine = null;
String alertMessage = "*****";
int lcStr1Len = fileName.length();
String lcStr1 = fileName.toLowerCase().substring(0, lcStr1Len - 1);
int lcStr2Len = detailOption.length();
String lcStr2 = detailOption.toLowerCase().substring(0, lcStr2Len - 1);
boolean bailOut = false;
// Try to open file
fileByteStream = new FileInputStream(filePath + fileName + ".txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine() && bailOut == false)
{
textLine = inFS.nextLine();
lcTextLine = textLine.toLowerCase();
if (lcTextLine.contains(lcStr1) && lcTextLine.contains(lcStr2))
{
do
{
System.out.println(textLine);
textLine = inFS.nextLine();
if (textLine.isEmpty())
{
bailOut = true;
}
if (textLine.contains(alertMessage))
{
JOptionPane.showMessageDialog(null, textLine.substring(5));
}
}
while (inFS.hasNextLine() && bailOut == false);
}
}
// Done with file, so try to close it
fileByteStream.close(); // close() may throw IOException if fails
}
void showData()
{
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Run example
javac AnimalsHabitat.java Monitor.java && java Monitor
Here is an example of some menu and submenu selection
package com.hnb;
public class Monitor {
public Monitor(FileParser fileParser) {
final Menu main = new Menu(fileParser.getOptions());
System.out.println("Welcome to the Zoo Monitoring System!");
MenuSelection selection = null;
Selection subselection = null;
do {
selection = main.displaySubMenu();
if(selection.isValid()){
do {
final Menu submenu = new Menu(selection.getSelection());
subselection = submenu.display();
if (subselection.isValid()) {
final Monitorable item = (Monitorable) subselection.getSelection();
System.out.println(item);
item.showAsterisk();
}
} while (!subselection.isExit());
}
} while (!selection.isExit());
}
public static void main(String[] args) {
new Monitor(new FileParser());
}
}

Why does my code write ArrayList element into my output file twice, rather than updating the ArrayList?

I just want to say thank you for taking the time to look into my question. I am currently working on an inventory interface. The issue I am having is that when I read an update file, to update my database file, this is what I get: database: abc,123,10.0,5.0,false,10 (partName,partNumber,listPrice,salePrice,onSale,quantity)
after I read in the update file:
abc,123,10.0,5.0,false,10 is first in my db followed by abc,123,20.0,10.0,true,2
how do I fix this so that it updates the string in the db file, instead of appending it to the file?
here is some of my code:
//findBp method
public static BikePart findBp(ArrayList<BikePart> bpal, BikePart bp) {
BikePart found = null;
for(BikePart b : bpal) {
if(b.getPartName().equals(bp.getPartName()) && b.getPartNumber() == bp.getPartNumber()) {
found = b;
break;
}
}
return found;
}
//sort by partName
public static void sortName(ArrayList<BikePart> bpal) {
Collections.sort(bpal, BikePart.bpNameComp);
}
//sort by partNumber
public static void sortNumber(ArrayList<BikePart> bpal) {
Collections.sort(bpal, BikePart.bpPartNumComp);
}
//readFile method
public static void readFile(String fileName, ArrayList<BikePart> bpal) {
if(fileName == null || fileName.equals("")) {
return;
}
File file = new File(fileName);
try {
Scanner read = new Scanner(file);
while(read.hasNextLine()) {
String line = read.nextLine();
String pv[] = line.split(",");
BikePart bp = BikePart.toObject(pv);
BikePart found = findBp(bpal, bp);
if(found == null) {
bpal.add(bp);
} else {
found.setQuantity(found.getQuantity() + bp.getQuantity());
found.setPartName(bp.getPartName());
found.setPartNumber(bp.getPartNumber());
found.setListPrice(bp.getListPrice());
found.setSalesPrice(bp.getSalesPrice());
found.setPartOnSale(bp.isPartOnSale());
}
}
read.close();
}
catch (FileNotFoundException e) {
System.out.println(fileName + " is not found!");
System.out.println("Enter another file name.");
String fileName2 = in.nextLine();
readFile(fileName2, bpal);
}
}
//writeFile method
public static void writeFile(String fileName, ArrayList<BikePart> bpal) {
try {
BufferedWriter outStream = new BufferedWriter(new FileWriter(fileName, true));
for(BikePart bp : bpal) {
outStream.write(bp.toString());
outStream.newLine();
}
outStream.close();
}
catch (IOException e) {
System.out.println("file not found!");
}
}
public static void main(String[] args) {
//calendar field
Calendar cal = Calendar.getInstance();
//ArrayList for DB
ArrayList<BikePart> bpal = new ArrayList<BikePart>();
readFile("DB.txt", bpal);
//user input variable
String usrIn = "";
//loop for user choice
while(usrIn != "Quit") {
//prompts user to select choice
System.out.println("Please select your option from "
+ "the following menu: ");
System.out.println("Read: Read an inventory delivery file");
System.out.println("Enter: Enter a part");
System.out.println("Sell: Sell a part");
System.out.println("Display: Display a part");
System.out.println("SortName: Sort parts by part name");
System.out.println("SortNumber: Sort parts by part number");
System.out.println("Quit: ");
System.out.println("Enter your choice: ");
//initiates usrIn
usrIn = in.nextLine();
//switch for input choice
switch(usrIn) {
case "Read":
//read method
System.out.println("Enter file name: ");
String fileName = in.nextLine();
readFile(fileName, bpal);
break;
case "Enter":
//enter method
break;
case "Sell":
//sell method
break;
case "Display":
//display method
break;
case "SortName":
//sortName method
break;
case "SortNumber":
//sortNum method
break;
case "Quit":
//quit method
writeFile("DB.txt", bpal);
System.out.println("good bye! ");
break;
}
if(usrIn.equals("Quit")) {
break;
}
}
}
I haven't filled in the rest of the code yet, because I want to fix this issue first before I move on. I just want to say thanks again for taking a look.
Because you are appending to the file:
new FileWriter(fileName, true)
That's what the true parameter does.
In order to replace data in your file, you must read it, replace the data and write the new data out.
One way to do this is as illustrated in this answer. Which is briefly outlined below:
// Read all the data
BufferedReader file = new BufferedReader(new FileReader("data.txt"));
String line;
StringBuffer inputBuffer = new StringBuffer();
while ((line = file.readLine()) != null) {
inputBuffer.append(line);
inputBuffer.append('\n');
}
String inputStr = inputBuffer.toString();
file.close();
// Replace your string code goes here.....
// Then write all the updated data back
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(inputStr.getBytes());
fileOut.close();
Regarding the duplication:
It might be a case of how you update your ArrayList. May I suggest that you print the list before writing the file to check that it is not a duplicate entry? If it is then it is not an file-writing issue but a data updating issue. Then you must ensure that you are updating the BikePart in the list instead of adding it again.

NumberFormatException when reading CSV file in java

I'm beginner in java and kinda stuck in these two problems so I'm trying to
let the program read from a CSV file line by line.
So in the file I have first row as String and the column is double.
So the problem is when it read first line It's reading the titles as double and it gives me an error.
By the way it is CSV file
The error i got are these below
Exception in thread "main" java.lang.NumberFormatException: For input string: "CLOSE" This is first error
Second error >> at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecima‌​l.java:1222) –
Third error >> at java.lang.Double.parseDouble(Double.java:510)
Forth error >>> at AlgorithmTrader.ReadInputData(AlgorithmTrader.java:63)
Fifth Error >> at AlgorithmTrader.Run(AlgorithmTrader.java:16)
Last error >> SimpleAlgorithmTradingPlatform.main(SimpleAlgorithmTradingPl‌​atform.java:15)
So the first row in the file has TIMESTAMP | Close | High | Low | open | volume and under each of those row there is numbers as double except volume has integer numbers
Your suggestion will appreciated. Thanks
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class AlgorithmTrader {
public void Run() {
ReadInputData();
}
public void ReadInputData() {
// create object of scanner class for user input
Scanner scan = new Scanner(System.in);
// declare file name for input file
String inputFileName = "";
// input from user for input file
System.out.print("Enter Input File Name: ");
inputFileName = scan.nextLine();
try {
PrintWriter pw = new PrintWriter("output.csv");// to open the file
// create a new file
File file = new File(inputFileName);
// create a new scanner object to read file
Scanner readFile = new Scanner(file);
// for each line data
String line = "";
line = readFile.nextLine();//skip the first line
while (readFile.hasNextLine()) {
readFile.nextLine();
// pass file to scanner again
readFile = new Scanner(file);
ArrayList<String> list = new ArrayList<String>();
// read stock data line by line
while (readFile.hasNextLine()) {
// read line from file
line = readFile.nextLine();
// split line data into tokens
String result[] = line.split(",");
// variables to create a Stock object
String timestamp = result[0];
double close = Double.parseDouble(result[1]);
double high = Double.parseDouble(result[2]);
double low = Double.parseDouble(result[3]);
double open = Double.parseDouble(result[4]);
int volume = Integer.parseInt(result[5]);
// store data into ArrayList
list.add(readFile.next());
pw.print(list.add(readFile.next()));
Stock stock = new Stock(timestamp, close, high, low, open, volume);
}// end of while to read file
//close readFile object
readFile.close();
pw.close();//close file
}
} catch (FileNotFoundException e1) {
System.out.println(" not found.\n");
System.exit(0);
} catch (IOException e2) {
System.out.println("File can't be read\n");
}
}
}
I have another file Stock class
public class Stock {
String timestamp;
double close;
double high;
double low;
double open;
int volume;
Stock(String t, double c, double h, double l, double o, int v) {
timestamp = t;
close = c;
high = h;
low = l;
open = o;
volume = v;
}
public void settimestamp(String t) {
this.timestamp = t;
}
public void setclose(double c) {
this.close = c;
}
public void sethigh(double h) {
this.high = h;
}
public void setopen(double o) {
this.open = o;
}
public void setvolume(int v) {
this.volume = v;
}
public String gettimestamp() {
return timestamp;
}
public double close() {
return close;
}
public double high() {
return high;
}
public int volume() {
return volume;
}
}
And The main method in another file as well
import java.text.DecimalFormat;
public class SimpleAlgorithmTradingPlatform {
public static void main(String[] args) {
DecimalFormat fmt = new DecimalFormat("#0.00"); // to get the DecimalFormat
AlgorithmTrader test = new AlgorithmTrader();
test.Run();
}
}
You are you having NumberFormatException because here
line = readFile.nextLine();//skip the first line
you are not skipping first line.
You'd better use BufferedReader instead of Scanner after getting file name. I have corrected you code a bit.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class AlgorithmTrader {
public void Run() {
ReadInputData();
}
public void ReadInputData() {
// create object of scanner class for user input
Scanner scan = new Scanner(System.in);
// declare file name for input file
String inputFileName = "";
// input from user for input file
System.out.print("Enter Input File Name: ");
inputFileName = scan.nextLine();
// create a new file
File csvFile = new File(inputFileName);
String line;
ArrayList<Stock> list = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
System.out.println("Reading file " + csvFile);
System.out.println("Skipping title of the CSV file");
// Skip first line because it is title
br.readLine();
System.out.println("Converting line to Stock");
while ((line = br.readLine()) != null) {
String result[] = line.split(",");
String timestamp = result[0];
double close = Double.parseDouble(result[1]);
double high = Double.parseDouble(result[2]);
double low = Double.parseDouble(result[3]);
double open = Double.parseDouble(result[4]);
int volume = Integer.parseInt(result[5]);
list.add(new Stock(timestamp, close, high, low, open, volume));
}
System.out.println("Done");
} catch (FileNotFoundException e1) {
System.out.println(" not found.");
System.exit(0);
} catch (IOException e2) {
System.out.println("File can't be read");
}
}
}
It would be nice to see a fictional example of the contents within your CSV file but please spare us any additional comments. ;)
It looks like your errors (and probably all of them) are most likely coming from your Stock Class. That's for another posted question however your getters and setters need attention. Some are missing as well but perhaps this is by choice.
You should be able to carry out this task with one Scanner object and one while loop. Use the same Scanner object for User input and file reading, it's reinitialized anyways.
The code below is one way to do it:
ArrayList<String> list = new ArrayList<>();
// create object of scanner class for user input
// and File Reading.
Scanner scan = new Scanner(System.in);
// declare file name for input file
String inputFileName = "";
// input from User for input file name.
System.out.print("Enter Input File Name: ");
inputFileName = scan.nextLine();
String tableHeader = "";
try {
// create a new file with PrintWriter in a
PrintWriter pw = new PrintWriter("output.csv");
File file = new File(inputFileName);
// Does the file to read exist?
if (!file.exists()) {
System.err.println("File Not Found!\n");
System.exit(0);
}
// create a new scanner object to read file
scan = new Scanner(file);
// for each line data
String line = "";
tableHeader = scan.nextLine();
String newline = System.getProperty("line.separator");
// Print the Table Header to our new file.
pw.print(tableHeader + newline);
while (scan.hasNextLine()) {
line = scan.nextLine();
// Make sure we don't deal with a blank line.
if (line.equals("") || line.isEmpty()) {
continue;
}
// split line data into a String Array.
// Not sure if there is a space after
// comma delimiter or not but I'm guessing
// there is. If not then remove the space.
String result[] = line.split(", ");
// variables to create a Stock object
String timestamp = "";
double close = 0.0;
double high = 0.0;
double low = 0.0;
double open = 0.0;
int volume = 0;
// Make sure there are enough array elements
// from our split string to fullfil all our
// variables. Maybe some data is missing.
int resLen = result.length;
if (resLen > 0) {
if (resLen >= 1) { timestamp = result[0]; }
if (resLen >= 2) { close = Double.parseDouble(result[1]); }
if (resLen >= 3) { high = Double.parseDouble(result[2]); }
if (resLen >= 4) { low = Double.parseDouble(result[3]); }
if (resLen >= 5) { open = Double.parseDouble(result[4]); }
if (resLen >= 6) { volume = Integer.parseInt(result[5]); }
}
// store data into ArrayList.
// Convert the result Array to a decent readable string.
String resString = Arrays.toString(result).replace("[", "").replace("]", "");
list.add(resString);
// Print the string to our output.csv file.
pw.print(resString + System.getProperty("line.separator"));
//Stock stock = new Stock(timestamp, close, high, low, open, volume);
}
//close file
scan.close();
pw.close();
}
catch (IOException ex ){
System.err.println("Can Not Read File!\n" + ex.getMessage() + "\n");
System.exit(0);
}
// Example to show that the ArrayList actually
// contains something....
// Print data to Console Window.
tableHeader = tableHeader.replace(" | ", "\t");
tableHeader = "\n" + tableHeader.substring(0, 10) + "\t" + tableHeader.substring(10);
System.out.println(tableHeader);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).replace(", ", "\t"));
}

Program looping infinitly

I wrote program that take command from user and perform particular functionality. However, there is something wrong with the functionality read and write input to file which cause the loop to run indefinitely.
import java.util.HashMap;
import java.util.Scanner;
public class cShell{
static String Currentpath="C:\\";
public String Current = Currentpath;
static HashMap<String, ICommand> myhashData=new HashMap<String, ICommand>();
public static void main(String[] args)
{
myhashData.put("ltf", new cITF());
myhashData.put("nbc", new cNBC());
myhashData.put("gdb", new cGDB());
myhashData.put("Tedit", new cTedit());
do
{
System.out.print(Currentpath+"> ");
String Input = null;
Scanner scan = new Scanner(System.in);
if(scan.hasNext()){
Input = scan.nextLine().trim();
}
//if(Input.equals("exit")){
// System.exit(0);
//}
if(myhashData.containsKey(Input))
{
ICommand myCommand=myhashData.get(Input);
myCommand.Execute();
}
else
{
System.out.println("Invalid Command");
}
}while(!"Input".equals("exit"));
}
}
And here is the class which provide the functionality for read and write.
import java.util.*;
import java.io.*;
//import java.lang.System.*;
public class cTedit implements ICommand{
#Override
public void Execute() {
// TODO Auto-generated method stub
System.out.println("Enter the file name to be edited");
Scanner scan = new Scanner(System.in);
String filename = scan.nextLine();
InputStreamReader cin = null;
FileWriter out = null;
try{
cin = new InputStreamReader(System.in);
out = new FileWriter(cShell.Currentpath+"\\"+filename);
System.out.println("Enter character, 'q' to quit");
char c;
do{
c = (char) cin.read();
out.write(c);
}while(c!= 'q');
}
catch(Exception e){
System.out.println("Error");
}
finally{
try{
cin.close();
out.close();
}
catch(IOException e)
{
System.out.println("File did not close");
}
}
}
}
The problem is that after the reading and writing, the program output the message "Invalid Command" which is defined inside the class cShell. Can anyone point to me where this the cause..??
The do-while loop will run forever becauses its termination condition is:
!"Input".equals("exit")
The string "Input" will never be equal to the string "exit". You may want to use the variable Input instead:
!input.equals("exit")
Note:
Try to follow Java naming conventions. Use 'mixedCase' for methods/variables and use 'CamelCase' for classes/interfaces. In other words, the variable name should be input, not Input.
Change
while(!"Input".equals("exit"));
to
while(!Input.equals("exit"));
As "Input" can never be equal to "exit" condition is always true and hence it loops infinitely.
For NPE you can add null checks
finally{
try{
if(cin != null)
cin.close();
if(out != null)
out.close();
}
catch(IOException e)
{
System.out.println("File did not close");
}
}

Error: java.util.NoSuchElementException - Scanner not behaving as desired

Scanner returning NoSuch Element Exception error. Could you explain why is this happening.
The Scanner now passes and runs fine but it didn't take the nextLine input from the second Scanner call. This may be a little tweak but could someone point out what the mistake is.
public class JavaHW1_1 {
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) throws IOException {
String pattern ;
String fileName = null;
// Method to manage user inputs
fileName = userInputFileName(userInput);
pattern = userInputPattern(userInput);
// To find the pattern in the file
// findPattern();
}
private static String userInputPattern(Scanner userInput) {
String pattern = "JollyGood";
System.out.println(". Please enter a pattern to find in the file");
while(userInput.hasNextLine()){
pattern = userInput.nextLine();
System.out.println("The pattern to be searched: "+ pattern);
}
userInput.close();
return pattern;
}
private static String userInputFileName(Scanner userInput) throws IOException {
String path = "./src";
String files, fileName;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
System.out.println("Please input the desired file name:\n");
System.out.println("Some suggestions:\n");
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile() && listOfFiles[i].getName().toLowerCase().endsWith(".txt"))
{
files = listOfFiles[i].getName();
System.out.println(files);
}
}
int userAttempt = 0;
do{
fileName = userInput.nextLine();
if(fileName.toLowerCase().endsWith(".txt")){
System.out.println("The file name entered is in correct format");
File file = new File("./src",fileName);
try {
file.createNewFile();
System.out.println("File is created. Please enter text to be written in the file. End the content with \"eof\"");
InputOutput(file.getName());
} catch (IOException e) {
e.printStackTrace();
}
userAttempt = 10;
}
else
{System.out.println("Please enter correct format file with .txt extension");
userAttempt++;}
}while (userAttempt <10);
return fileName;
}
private static void InputOutput(String fName) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("./src/" + fName));
String inputLine = null;
do {
inputLine=in.readLine();
out.write(inputLine);
out.newLine();
} while (!inputLine.equalsIgnoreCase("aaa"));
System.out.print("Write Successful");
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
in.close();
}
}
private static void findPattern() {
// TODO Auto-generated method stub
}
}
Based in this SO, you might be closing the Scanner and creating a new one to read from the System.in and it makes sense by looking at your code.
So my suggestion for you code is to receive the Scanner by parameter, something like this:
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
String pattern = userInputPattern(scan);
String test = readSomethingElse(scan);
}
private static String readSomethingElse(Scanner scan) {
System.out.println(". Read something else");
return scan.nextLine();
}
private static String userInputPattern(Scanner scan) {
String pattern = "JollyGood";
System.out.println(". Please enter a pattern to find in the file");
pattern = scan.nextLine();
System.out.println("The pattern to be searched: "+ pattern);
return pattern;
}
It could happen if you pass EOF straight into the standard input. For example (in windows):
java com.myprog.MainClass
^Z
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
....
The ^Z above represents a Ctrl-Z on windows command prompt which is an EOF signal
You need to consider your requirement and process / display error if user is provided a EOF without any prior data

Categories

Resources