Have to Enter Input Twice for Scanner to Read it - java

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

Related

Scanner inside method dont ask for input

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.

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

Reading and modifying the text from the text file in Java

I am have a project that need to modify some text in the text file.
Like BB,BO,BR,BZ,CL,VE-BR
I need make it become BB,BO,BZ,CL,VE.
and HU, LT, LV, UA, PT-PT/AR become HU, LT, LV, UA,/AR.
I have tried to type some code, however the code fail to loop and also,in this case.
IN/CI, GH, KE, NA, NG, SH, ZW /EE, HU, LT, LV, UA,/AR, BB
"AR, BB,BO,BR,BZ,CL, CO, CR, CW, DM, DO,VE-AR-BR-MX"
I want to delete the AR in second row, but it just delete the AR in first row.
I got no idea and seeking for helps.
Please
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
public class tomy {
static StringBuffer stringBufferOfData = new StringBuffer();
static StringBuffer stringBufferOfData1 = stringBufferOfData;
static String filename = null;
static String input = null;
static String s = "-";
static Scanner sc = new Scanner(s);
public static void main(String[] args) {
boolean fileRead = readFile();
if (fileRead) {
replacement();
writeToFile();
}
System.exit(0);
}
private static boolean readFile() {
System.out.println("Please enter your files name and path i.e C:\\test.txt: ");
filename = "C:\\test.txt";
Scanner fileToRead = null;
try {
fileToRead = new Scanner(new File(filename));
for (String line; fileToRead.hasNextLine()
&& (line = fileToRead.nextLine()) != null;) {
System.out.println(line);
stringBufferOfData.append(line).append("\r\n");
}
fileToRead.close();
return true;
} catch (FileNotFoundException ex) {
System.out.println("The file " + filename + " could not be found! "+ ex.getMessage());
return false;
} finally {
fileToRead.close();
return true;
}
}
private static void writeToFile() {
try {
BufferedWriter bufwriter = new BufferedWriter(new FileWriter(
filename));
bufwriter.write(stringBufferOfData.toString());
bufwriter.close();
} catch (Exception e) {// if an exception occurs
System.out.println("Error occured while attempting to write to file: "+ e.getMessage());
}
}
private static void replacement() {
System.out.println("Please enter the contents of a line you would like to edit: ");
String lineToEdit = sc.nextLine();
int startIndex = stringBufferOfData.indexOf(lineToEdit);
int endIndex = startIndex + lineToEdit.length() + 2;
String getdata = stringBufferOfData.substring(startIndex + 1, endIndex);
String data = " ";
Scanner sc1 = new Scanner(getdata);
Scanner sc2 = new Scanner(data);
String lineToEdit1 = sc1.nextLine();
String replacementText1 = sc2.nextLine();
int startIndex1 = stringBufferOfData.indexOf(lineToEdit1);
int endIndex1 = startIndex1 + lineToEdit1.length() + 3;
boolean test = lineToEdit.contains(getdata);
boolean testh = lineToEdit.contains("-");
System.out.println(startIndex);
if (testh = true) {
stringBufferOfData.replace(startIndex, endIndex, replacementText1);
stringBufferOfData.replace(startIndex1, endIndex1 - 2,
replacementText1);
System.out.println("Here is the new edited text:\n"
+ stringBufferOfData);
} else {
System.out.println("nth" + stringBufferOfData);
System.out.println(getdata);
}
}
}
I wrote a quick method for you that I think does what you want, i.e. remove all occurrences of a token in a line, where that token is embedded in the line and is identified by a leading dash.
The method reads the file and writes it straight out to a file after editing for the token. This would allow you to process a huge file without worrying about about memory constraints.
You can simply rename the output file after a successful edit. I'll leave it up to you to work that out.
If you feel you really must use string buffers to do in memory management, then grab the logic for the line editing from my method and modify it to work with string buffers.
static void onePassReadEditWrite(final String inputFilePath, final String outputPath)
{
// the input file
Scanner inputScanner = null;
// output file
FileWriter outputWriter = null;
try
{
// open the input file
inputScanner = new Scanner(new File(inputFilePath));
// open output file
File outputFile = new File(outputPath);
outputFile.createNewFile();
outputWriter = new FileWriter(outputFile);
try
{
for (
String lineToEdit = inputScanner.nextLine();
/*
* NOTE: when this loop attempts to read beyond EOF it will throw the
* java.util.NoSuchElementException exception which is caught in the
* containing try/catch block.
*
* As such there is NO predicate required for this loop.
*/;
lineToEdit = inputScanner.nextLine()
)
// scan all lines from input file
{
System.out.println("START LINE [" + lineToEdit + "]");
// get position of dash in line
int dashInLinePosition = lineToEdit.indexOf('-');
while (dashInLinePosition != -1)
// this line has needs editing
{
// split line on dash
String halfLeft = lineToEdit.substring(0, dashInLinePosition);
String halfRight = lineToEdit.substring(dashInLinePosition + 1);
// get token after dash that is to be removed from whole line
String tokenToRemove = halfRight.substring(0, 2);
// reconstruct line from the 2 halves without the dash
StringBuilder sb = new StringBuilder(halfLeft);
sb.append(halfRight.substring(0));
lineToEdit = sb.toString();
// get position of first token in line
int tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
while (tokenInLinePosition != -1)
// do for all tokens in line
{
// split line around token to be removed
String partLeft = lineToEdit.substring(0, tokenInLinePosition);
String partRight = lineToEdit.substring(tokenInLinePosition + tokenToRemove.length());
if ((!partRight.isEmpty()) && (partRight.charAt(0) == ','))
// remove prefix comma from right part
{
partRight = partRight.substring(1);
}
// reconstruct line from the left and right parts
sb.setLength(0);
sb = new StringBuilder(partLeft);
sb.append(partRight);
lineToEdit = sb.toString();
// find next token to be removed from line
tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
}
// handle additional dashes in line
dashInLinePosition = lineToEdit.indexOf('-');
}
System.out.println("FINAL LINE [" + lineToEdit + "]");
// write line to output file
outputWriter.write(lineToEdit);
outputWriter.write("\r\n");
}
}
catch (java.util.NoSuchElementException e)
// end of scan
{
}
finally
// housekeeping
{
outputWriter.close();
inputScanner.close();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
inputScanner.close();
e.printStackTrace();
}
}

Random selected strings

I have a text file and i am trying to convert every line into an ArrayList. Then i have to take a random line from this text.file and display it on new JOptionPane.
I am trying to implement it in the for-loop but it always appears only the first line from my text.file. Thank you very much and here is my code.
public void actionPerformed(ActionEvent e) {
ArrayList<String> allQuestions = new ArrayList<String>();
ArrayList<String> allRandomSelectedQuestions = new ArrayList<String>();
File file = new File("C:/Users/User/Documents/NetBeansProjects/SummerExamProject/src/Questions2.txt");
int numberOfRandomQuestions = 16;
try {
//Read line by line from the file
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
// System.out.println(line);
JOptionPane.showMessageDialog(null, line.replace("/", "\n"));
scan.close();
allQuestions.add(line);
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
for(int i = 0; i < numberOfRandomQuestions; i++){
Random randNum = new Random();
int randQuestionIndex = randNum.nextInt(numberOfRandomQuestions);
String randomQuestion = allQuestions.get(randQuestionIndex);
allRandomSelectedQuestions.add(randomQuestion);
}
}
This line...
scan.close();
Is inside your while loop, so it closes the file after reading a line the first time it goes through the loop.
Moving it to after the loop (i.e. after the close culry-brace) ought to fix it.
The problem is this: scan.close();. You are closing your scanner in the same loop you are using for reading. Moving it outside the loop body should solve the problem.
Call close method after the while loop. What is happening that, you close after the first line. so the while loop stops after only one time.
while (scan.hasNextLine()) {
String line = scan.nextLine();
//System.out.println(line);
JOptionPane.showMessageDialog(null, line.replace("/", "\n"));
allQuestions.add(line);
}
scan.close();
Try this. Hope it helps.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class StackTest {
public static void main(String[] args) {
actionPerformed();
}
public static void actionPerformed() {
ArrayList<String> allQuestions = new ArrayList<String>();
File file = new File("D:/me/test.txt");
int numberOfRandomQuestions = 10;
try {
// Read line by line from the file
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String line = scan.nextLine();
allQuestions.add(line);
}
scan.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
for (int i = 0; i < numberOfRandomQuestions; i++) {
Random randNum = new Random();
int randQuestionIndex = randNum.nextInt(numberOfRandomQuestions);
System.out.println();
String randomQuestion = allQuestions.get(randQuestionIndex);
JOptionPane.showMessageDialog(null, randomQuestion.replace("/", "\n"));
}
}
}

Categories

Resources