Scanner inside method dont ask for input - java

I ask user to insert an item name with extension ".txt" and if the item name is coresponding to the existing itemName.txt then user need to insert the location name with extension ".txt" where he want to "transfer" it .
if everithing is ok then the content from itemName.txt will be writen into the locationName.txt
My Main looks like this :
package victor;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class Main extends Item {
public Main(String location, Integer length, Integer height, Integer depth) {
super(location, length, height, depth);
}
public static void main(String[] args) throws IOException {
List<Item> itemList = new ArrayList<>();
List<Location> locationList = new ArrayList<>();
System.out.println("Welcome to create new:");
System.out.println("Please follow the steps:");
HashMap<Integer, String> menu = new HashMap<>();
menu.put(1, "Create Location");
menu.put(2, "Create Item");
menu.put(3, "Transfer to location");
menu.forEach((key, value) -> System.out.println(key + "- " + value));
int user_choice;
Scanner userInputMenu = new Scanner(System.in);
user_choice = userInputMenu.nextInt();
switch (user_choice) {
case 1:
createLocationPlusFile(locationList);
case 2:
createItemPlusFile(itemList);
case 3:
transferItemToLocation(itemList, locationList);
}
}
}
When user input from menu - 3 , program is closing Process finished with exit code 0.
Here is my Item Class with the method I wrote:
package victor;
import java.io.*;
import java.util.List;
import java.util.Scanner;
public class Item extends Location {
private String itemName;
private Integer kg;
private Integer length;
private Integer height;
private Integer depth;
public Item(String itemName, Integer kg, Integer length, Integer height, Integer depth) {
super();
this.itemName = itemName;
this.kg = kg;
this.length = length;
this.height = height;
this.depth = depth;
}
public Item() {
}
public Item(String location, Integer length, Integer height, Integer depth) {
super();
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Integer getKg() {
return kg;
}
public void setKg(Integer kg) {
this.kg = kg;
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getDepth() {
return depth;
}
public void setDepth(Integer depth) {
this.depth = depth;
}
#Override
public String toString() {
return "Item{" +
"itemName='" + itemName + '\'' +
", kg=" + kg +
", length=" + length +
", height=" + height +
", depth=" + depth +
'}';
}
public static void createItemPlusFile(List<Item> itemList) throws NullPointerException, IOException {
int defaultLength = 80;
int defaultHeight = 205;
int defaultDepth = 120;
int defaultKg = 3500;
Scanner in1 = new Scanner(System.in);
System.out.println("Enter Item Name: ");
String itemName = in1.nextLine();
System.out.println("New Item created successfully!" + "\n" + itemName);
int inLength;
Scanner in2 = new Scanner(System.in);
System.out.println("Enter Item height: ");
int itemLength = in2.nextInt();
if (itemLength > defaultLength) {
System.out.println("Height that you added is to big, please use a height of max 205");
inLength = in2.nextInt();
} else {
System.out.println("Height inserted correctly! ");
}
int inHeight;
Scanner in3 = new Scanner(System.in);
System.out.println("Enter Item height: ");
int itemHeight = in3.nextInt();
if (itemHeight > defaultHeight) {
System.out.println("Height that you added is to big, please use a height of max 205");
inHeight = in3.nextInt();
} else {
System.out.println("Height inserted correctly! ");
}
int inDepth;
Scanner in4 = new Scanner(System.in);
System.out.println("Enter Item depth: ");
int itemDepth = in4.nextInt();
if (itemDepth > defaultDepth) {
System.out.println("Depth that you added is to big, please use a depth of max 120");
inDepth = in4.nextInt();
} else {
System.out.println("Depth inserted correctly! ");
}
int inKg;
Scanner in5 = new Scanner(System.in);
System.out.println("Enter Item kg: ");
int itemKg = in4.nextInt();
if (itemKg > defaultKg) {
System.out.println("kg that you added is to big, please use a depth of max 3500");
inDepth = in4.nextInt();
} else {
System.out.println("Kg inserted correctly! ");
}
Item item = new Item(itemName, itemKg, itemLength, itemHeight, itemDepth);
File file = new File(item.getItemName() + "CUSCAS001GRY-uk.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(item.getItemName() + "CUSCAS001GRY-uk.txt", true);
fileWriter.write(item + "\n");
fileWriter.close();
}
//this method I wrote, I expect to ask user to input the item and if item with this name exist then he insert the location where he want to "transfer" it .
public static void transferItemToLocation(List<Item> itemList, List<Location> locationList) throws IOException {
for (Item item : itemList) {
for (Location location : locationList) {
Scanner inputItemTransfer = new Scanner(System.in);
System.out.println("Insert the item you want to transfer + .txt extension!");
inputItemTransfer.nextLine();
if (inputItemTransfer.nextLine()
.equalsIgnoreCase(item + ".txt")) {
Scanner inputTransferToLocation = new Scanner(System.in);
System.out.println("Insert the location where you want to transfer the item");
inputTransferToLocation.nextLine();
if (inputTransferToLocation.nextLine()
.equalsIgnoreCase(String.valueOf(location))) {
BufferedReader bufferedReader = new BufferedReader(new FileReader(String.valueOf(inputItemTransfer)));
FileWriter fileWriter = new FileWriter(inputTransferToLocation + ".txt", true);
BufferedWriter outputStream = new BufferedWriter(fileWriter);
String str;
while ((str = bufferedReader.readLine()) != null) {
outputStream.write(str + "\n");
}
outputStream.close();
}
}
}
}
}
}
I assume that I do something wrong with the scanner .
Any help/critics are totaly appreciated

You don't need to create a Scanner object for every prompt where the User needs to input data. One Scanner object for the entire application will do just fine. Just declare the object as public static within the Main class, for example:
public class Main extends Item {
// Declare a Scanner object that can potentially be used anywhere.
public static Scanner userInput = new Scanner(System.in).useDelimiter("\\R");
public Main(String location, Integer length, Integer height, Integer depth) {
super(location, length, height, depth);
}
public static void main(String[] args) throws IOException {
// ... main() method code here ...
}
}
Then everywhere you have a prompt to the User and need to use a Scanner method to get input, use Main.userInput. instead, for example:
user_choice = Main.userInput.nextInt();
or:
String itemName = Main.userInput.nextLine();
When using Scanner#nextInt() (or any Scanner#nextXXX methods) and a Scanner#nextLine() prompt will directly follow then you will most likely need to consume the newline character from when the enter key is hit from the Scanner#nextInt() use. The nextInt() method does not consume the newline character like the nextline() method does and therefore the prompt using the nextLine() method appears to be skipped. In cases like this you would want to do:
user_choice = Main.userInput.nextInt();
Main.userInput.nextLine();
A good rule of thumb is:
If you use the Scanner#nextLine() method, then use it for everything otherwise, don't use it at all. Use the next() and nextXXX() methods instead.
If you create your Scanner as shown above (with the useDelimiter("\\R") method) then the Scanner#next() method will return that similar to what the Scanner#nextLine() method would return.
Currently, your transferItemToLocation() method is double prompting for each prompt within the method because of the way you are using the Scanner methods.
public static void transferItemToLocation(List<Item> itemList, List<Location> locationList) throws IOException {
for (Item item : itemList) {
for (Location location : locationList) {
Scanner inputItemTransfer = new Scanner(System.in);
System.out.println("Insert the item you want to transfer + .txt extension!");
inputItemTransfer.nextLine();
if (inputItemTransfer.nextLine()
.equalsIgnoreCase(item + ".txt")) {
Scanner inputTransferToLocation = new Scanner(System.in);
System.out.println("Insert the location where you want to transfer the item");
inputTransferToLocation.nextLine();
if (inputTransferToLocation.nextLine()
.equalsIgnoreCase(String.valueOf(location))) {
BufferedReader bufferedReader = new BufferedReader(new FileReader(String.valueOf(inputItemTransfer)));
FileWriter fileWriter = new FileWriter(inputTransferToLocation + ".txt", true);
BufferedWriter outputStream = new BufferedWriter(fileWriter);
String str;
while ((str = bufferedReader.readLine()) != null) {
outputStream.write(str + "\n");
}
outputStream.close();
}
}
}
}
}
I can only assume why you are doing this because you have not provided all your code which is partially why I posted a lot of the drivel about Scanner above. What you've got here is not going to work the way you think it will. As mentioned earlier, get rid of all those Scanner objects and use something similar to what is declared within the Main class (similar to what is shown at the beginning of this post). Declare String variables named inputItemTransfer and inputTransferToLocation. Place the User input into those variables respectively for each prompt and use the data contained within those variables rather than the Scanner objects, for example:
public static void transferItemToLocation(List<Item> itemList, List<Location> locationList) throws IOException {
String inputItemTransfer;
String inputTransferToLocation;
for (Item item : itemList) {
for (Location location : locationList) {
System.out.println("Insert the item you want to transfer + .txt extension!");
inputItemTransfer = Main.userInput.nextLine();
if (inputItemTransfer.equalsIgnoreCase(item + ".txt")) {
System.out.println("Insert the location where you want to transfer the item");
inputTransferToLocation = Main.userInput.nextLine();
if (inputTransferToLocation.equalsIgnoreCase(String.valueOf(location))) {
BufferedReader bufferedReader = new BufferedReader(new FileReader(String.valueOf(inputItemTransfer)));
FileWriter fileWriter = new FileWriter(inputTransferToLocation + ".txt", true);
BufferedWriter outputStream = new BufferedWriter(fileWriter);
String str;
while ((str = bufferedReader.readLine()) != null) {
outputStream.write(str + "\n");
}
outputStream.close();
}
}
}
}
}
Whether this method is now going to function properly is honestly beyond me. Without all the code or at least a minimal reproducible example it's hard to say. One step at a time I suppose.
On a side:
As mentioned in Comments, it does indeed appear that there is a lot of required data entry by a User to utilize your application which is sort of a downer and actually difficult for some. Perhaps consider a more menu based system to reduce entry requirements and make usage a more comfortable experience.
Good luck.

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());
}
}

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"));
}

How to find the frequency of names from files and store the info in an array?

Here is my NameRecord constructor class:
public class NameRecord {
String firstName;
int count;
public NameRecord(String name, int count){
this.firstName = name;
this.count = count;
}
#Override
public String toString() {
return firstName + " - " + count + " registered births.";
}
public String getFirstName() {
return firstName;
}
public int getCount() {
return count;
}
}
And here is what I have so far of the actual program:
public class Names {
public final int MAX_NAMES = 3;
NameRecord[] boyNames = new NameRecord[MAX_NAMES];
String boysFile = "data/boynames.txt";
#Override
public String toString() {
String result = "";
for (NameRecord record : boyNames)
result += record + "\n";
return result;
}
public void loadNamesFromFile() {
try {
BufferedReader stream = new BufferedReader(new FileReader("Data/boysnames.txt"));
} catch (Exception e)
{
System.out.println("File not found");
}
}
}
Basically, the program reads a file and determines if the name is on the boys list or girls list txt files, and then outputs if it is on the list, and if so how many times it was used. I am only working with boys for right now to keep confusion to a minimum. My question is, in the loadNamesFromFile method, how do I add information from the file to the boyNames array. I know the NameRecord calls for the name and the count, but I'm not sure how to retrieve that information from the file and add it to the array. I have included the top three names from the file below, the name is of course the first name and the number is the number of times it was used, or count.
Jacob 29195
Michael 26991
Joshua 24950
First of all if it is possible to have your file structure like this
Jacob;29195
Michael;26991
Joshua;24950
to make it more easy to develop the solution
and now this is how you can read the file lines and store them into your tabel
public void loadNamesFromFile() {
try {
BufferedReader stream = new BufferedReader(new FileReader("Data/boysnames.txt"));
String currentLine ="";
int i = 0;
while(curentLine = stram.readLine()) {
String [] record = currentLine.split(";");
NameRecord = name = new NameRecord(record[0], Integer.parseInt(record[1]);
boyNames[i] = name;
i++;
}
} catch (Exception e)
{
System.out.println("File not found");
}
}
First of all you should add a scanner for the file in order to read what is in the file. After that u keep reading the file and add the information untill there is no more content in the file. Besides this I would use an ArrayList of NameRecord for being more flexible with the number of names.
Im assuming that the content of your file is always the same (given your example).
public class Names {
try {
ArrayList<NameRecord> boyNames = new ArrayList<>();
public void loadNamesFromFile() {
File file = new File("Data/boysnames.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()) {
boyNames.add(new NameRecord(sc.next(), sc.nextInt()));
}
sc.close();
}
} catch(IOException e) {
System.err.println(e);
}
}
My suggestion is to read all the contents of the file i.e., all the names, in a single String variable. Then, iterate over each word and count the number of occurrences and add the info to the array. Let's use Scanner to read the file.
I presume that the length of the array boyNames[] is equal to the number of unique names in the file.
Scanner boys = new Scanner(new File("Data/boys.txt"));
int a,i,n=0,c,b;
String con = "", x; //con holds all names
//reading the names
while(boys.hasNext())
con+= boys.next()+" ";
b = con.split(" ").length; //b = total number of names in the file
for(i=0; i<b; i++){
x = con.split(" ")[i];
if(!x.equals("*")){
c = 0; a = 0;
//counting frequency of x in con
while(con.indexOf(x, a) != -1){
c++; a = con.indexOf(x, a) + x.length() + 1;
}
//adding name and frequency to array
boyNames[n++] = new NameRecord(x, c);
con = con.replaceAll(x, "*"); //removing all instances of x from con
}
}
The boyNames[] array now stores the names and their respective frequencies in the file.

Saving / Loading array of objects in Java

I'm trying to Save/Load the array of objects to/from a plain .txt file. I know very little about serialization, but I think I have correctly used it to write the Array of objects to a .txt file. The .txt file is completely unreadable (in normal english) when opened separately. Am I writing it to a file correctly? and how do I go about reading it into the program?
public class HotelObjects {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String command;
Scanner input = new Scanner(System.in);
Room[] myHotel = new Room[10];
for (int x = 0; x < myHotel.length; x++) {
myHotel[x] = new Room();
}
String roomName;
int roomNum = 0;
while (roomNum < 11) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter command : ");
command = input.next();
command = command.toLowerCase();
if (command.charAt(0) == 'v') {
viewCustomers(myHotel);
}
if (command.charAt(0) == 'a') {
addCustomers(myHotel);
}
if (command.charAt(0) == 'e') {
emptyRooms(myHotel);
}
if (command.charAt(0) == 's') {
storeData(myHotel);
}
}
}
private static void viewCustomers(Room hotelRef []) {
for (int x = 0; x < 10; x++) {
System.out.println("room " + x + " occupied by " + hotelRef[x].getName());
}
}
private static void addCustomers(Room myHotel[]) {
String roomName;
int roomNum;
System.out.println("Enter room number (0-10) or 11 to stop:");
Scanner input = new Scanner(System.in);
roomNum = input.nextInt();
System.out.println("Enter name for room " + roomNum + " :");
roomName = input.next();
myHotel[roomNum].setName(roomName);
}
private static void emptyRooms(Room[] myHotel) {
for (int x = 0; x < 10; x++ )
if (myHotel[x].getName().equals("e"))System.out.println("room " + x + " is empty");
}
private static void storeData(Room [] myHotel) {
try{
FileOutputStream fos= new FileOutputStream("C:\\Users\\Ganz\\Documents\\NetBeansProjects\\HotelObjects\\HotelObject.dat");
ObjectOutputStream oos= new ObjectOutputStream(fos);
oos.writeObject(myHotel);
oos.close();
fos.close();
}catch(IOException ioe){
}
}
}
Here is the Room class (if needed):
public class Room implements Serializable {
private String mainName;
int guestsInRoom;
public Room() {
mainName = "e";
System.out.println("made a room ");
}
public void setName(String aName) {
mainName = aName;
}
public String getName() {
return mainName;
}
}
Use ObjectInputStream and a cast to load the array back from the file. And you need to flush the stream at the end of writing to it (before closing it).
The result of writing an ObjectOutputStream is supposed to be machine-readable and not human readable. To read it back in, use:
FileInputStream fis = new FileInputStream("C:\\Users\\Ganz\\Documents\\NetBeansProjects\\HotelObjects\\HotelObject.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Hotel hotel = (Hotel) ois.readObject();
The output of an ObjectOutputStream is meant to be machine readable therefore it would not necessarily be human readable. When using closeable resources you should aim to use them within a try block prior to Java 1.7 and close the resource in the finally block of that try or if using 1.7+ a try-with-resources statement. This is to ensure that the resource is closed even in the event of an exception being thrown;
String path = "C:\\Users\\Ganz\\Documents\\NetBeansProjects\\HotelObjects\\HotelObject.dat";
try (FileInputStream fileInput = new FileInputStream(path); ObjectInputStream inputStream= new ObjectInputStream(fileInput)) {
// Cast the Object returned from the stream to a Hotel object
Hotel hotel = (Hotel) inputStream.readObject();
} catch (FileNotFoundException ex) {
// TODO: Exception handling here
} catch (IOException ex) {
// TODO: Exception handling here
}
If you don't feel the default serialized form suits your need then you can create your own. If so look up how to create a custom serialized form.

Have to Enter Input Twice for Scanner to Read it

So in this code, under the class "Run" in the method "run", the Scanner seems to not want to take in input from the fist attempt, only on the second line does it take input. I say second line because I enter input then press return twice, and enter input on the THIRD line, it reads the second line, which in this case would be nothing.
I have tried BufferedReader with the same result, so I believe I am doing something idiotic and overlooking something.
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.io.*;
class Global {
public static int stop = -1;
}
public class DataSort {
public static void main(String[] args){
Timer timer = new Timer();
Direct swit = new Direct();
Run mprog = new Run();
Help hlp = new Help();
String newline = System.getProperty("line.separator");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Scanner console = new Scanner(System.in);
System.out.println(newline);
System.out.println("Welcome to Data Sort! This Program is designed to sort information about targets discoverd by UAV and place the data in a table." + newline);
System.out.print("For help, press any key. To continue, please wait. ");
timer.schedule(swit, 3000);
try {
Global.stop = in.read();
}
catch(IOException e) {
e.printStackTrace();
}
try {
in.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
class Direct extends TimerTask {
public void run() {
Run mprog = new Run();
Help hlp = new Help();
if(Global.stop != -1){
System.out.println("Help");
hlp.run();
}
if(Global.stop == -1) {
System.out.println("Main");
mprog.run();
}
}
}
class Help {
public static void run() {
String newline = System.getProperty("line.separator");
System.out.print(newline);
System.out.println("Entering Help Mode!" + newline);
System.out.println("Entered Help Class");
//String help = console.nextLine();
}
}
class Run {
public static void run() {
/*EnterAll eall = new EnterAll();
EnterCoords ecoords = new EnterCoords();
EnterRelation erelat = new EnterRelation();
EnterColor ecolor = new EnterColor();
EnterShape eshape = new EnterShape();
Coordinates coords = new Coordinates();
Relation relat = new Relation();
Color color = new Color();
Shape shape = new Shape();
List list = new List();
Save save = new Save();
SaveAs saveas = new SaveAs();*/
String newline = System.getProperty("line.separator");
Scanner console = new Scanner(System.in);
System.out.print(newline);
System.out.println("Initializing Main Program." + newline);
System.out.println("************************** MAIN MENU *************************" + newline);
System.out.println("Enter Coords \t Enter Relat \t Enter Color \t Enter Shape"+newline);
System.out.println("Coordinates \t Relation \t Color \t \t Shape" + newline);
System.out.println("Help \t \t List \t \t Save \t \t Save As" + newline);
System.out.println("**************************************************************" + newline);
System.out.print("Enter your selection or type All to enter lines consecutively: ");
String raw = console.nextLine();
System.out.println(raw);
String select = errorCheck(raw);
if (select.equals("All")){
}
if (select.equals("Enter Coords")){
}
if (select.equals("Enter Relat")){
}
if (select.equals("Enter Color")){
}
if (select.equals("Enter Shape")){
}
if (select.equals("Coordinates")){
}
if (select.equals("Relation")){
}
if (select.equals("Color")){
}
if (select.equals("Shape")){
}
if (select.equals("Help")){
}
if (select.equals("List")){
}
if (select.equals("Save")){
}
if (select.equals("Save As")){
}
}
private static String errorCheck(String raw) {
String select = raw;
return select;
}
}
Your problem lies in
public class DataSort {...... Global.stop = in.read(); ......}
Because in.read is for reading Integer input. It does not read End of Line character. Which is why it becomes clueless after you enter selection string and hit enter.
Regards,
Ravi
#Sean, here is your solution
Comment out below lines
public class DataSort
{
.
.
.
//BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//Scanner console = new Scanner(System.in);
.
.
.
//Global.stop = in.read();
.
.
}
For Global.stop = in.read(), read from the same input read buffer(may be in the same class or somewhere else) and parse the string as you want. Don't create another input read buffer.
Regards,
Ravi

Categories

Resources