I'm currently receiving an out of bounds issue in my array and I'm really unsure where exactly I've went wrong here. I'm really looking for a second pair of eyes over this thing as I'm going to lose my mind.
I honestly appreciate any help given.
No really: Thanks.
package com.jpmorgan.spring.csv;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CSVRead {
static void read() throws IOException {
String csvFileToRead = "profit.csv";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
String[] array = line.split(splitBy);
System.out.println("Equity & Bonds: [Instrument Type= " + array[0] + " , Name=" + array[1] + " , Quantity=" + array[2]
+ " , Buy=" + array[3] + " , Sell=" + array[4] + /*" , Coupon=" + array[5] +*/ "]");
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done reading CSV file");
}
}
This is the full CSV file.
I've tried using debug but it's not been much help.
instrument_type,name,quantity,buy_price,sell_price,coupon
Equity,AAA,123,1.01,1.10
Equity,BBBB,3,1.05,1.01
Bond,CCC,3,,,0.13
Equity,AAA,12,1.11,1.13
Bond,DD,3,,,1.24
Main class for reference.
/**
* Main class is menu driven, receives CSV input.
* This program reads, calculates and writes CSV files.
* #author David McNeill
* #version 1.0 - 17/03/1015
*/
package com.jpmorgan.spring.csv;
import java.util.Scanner;
public class CSVMain{
public static void main(String[] arg) throws Exception {
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int userChoice;
boolean quit = false;
do {
System.out.println("Please choose an option using 1 - 4"); //print text to screen
System.out.println("------------------------------------"); //print text to screen
System.out.println("1: Read 'input' CSV file"); //print text to screen
System.out.println("2: Calculate 'input' CSV file"); //print text to screen
System.out.println("3: Write calculation result to CSV file"); //print text to screen
System.out.println("4: Exit program"); //print text to screen
userChoice = in.nextInt(); //'in' equals integer
if (userChoice == 4) //when '3' is input then...
quit = true; //the program will now quit
else if (userChoice == 1) //when '1' is input then...
CSVRead.read();
else if (userChoice == 2);
//####################calculations go here#########################
//####################calculations go here#########################
//####################calculations go here#########################
else if (userChoice == 3)
CSVWrite.write();
} while (!quit);
}
}
After splitting the line you should make sure you're getting the right number of columns.
I can't tell you how to fix the potentially bad data but I can help you identify it. Just replace the inner loop with this:
int lineNum = 0;
while ((line = br.readLine()) != null) {
String[] array = line.split(splitBy);
if (array.length < 5)
throw new Exception("There's a problem with " + csvFileToRead + " on line " + lineNum + ":\n" + line);
System.out.println("Equity & Bonds: [Instrument Type= " + array[0] + " , Name=" + array[1] + " , Quantity=" + array[2]
+ " , Buy=" + array[3] + " , Sell=" + array[4] + /*" , Coupon=" + array[5] +*/ "]");
lineNum++;
}
your CSVRead has no main method.. change the call to CSVRead.read();
import java.util.Scanner;
public class CSVMain{
public static void main(String[] arg) throws Exception {
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int userChoice;
boolean quit = false;
do {
System.out.println("Please choose an option using 1 - 4"); //print text to screen
System.out.println("------------------------------------"); //print text to screen
System.out.println("1: Read 'input' CSV file"); //print text to screen
System.out.println("2: Calculate 'input' CSV file"); //print text to screen
System.out.println("3: Write calculation result to CSV file"); //print text to screen
System.out.println("4: Exit program"); //print text to screen
userChoice = in.nextInt(); //'in' equals integer
if (userChoice == 4) //when '3' is input then...
quit = true; //the program will now quit
else if (userChoice == 1) //when '1' is input then...
CSVRead.read();
else if (userChoice == 2);
//####################calculations go here#########################
//####################calculations go here#########################
//####################calculations go here#########################
} while (!quit);
}
}
CSVRead.java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CSVRead {
static void read() throws IOException {
String csvFileToRead = "profit.csv";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
String[] array = line.split(splitBy);
System.out.println("Equity & Bonds: [Instrument Type= " + array[0] + " , Name=" + array[1] + " , Quantity=" + array[2]
+ " , Buy=" + array[3] + " , Sell=" + array[4] + /*" , Coupon=" + array[5] +*/ "]");
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done reading CSV file");
}
}
OUTPUT
Please choose an option using 1 - 4
------------------------------------
1: Read 'input' CSV file
2: Calculate 'input' CSV file
3: Write calculation result to CSV file
4: Exit program
1
Equity & Bonds: [Instrument Type= instrument_type , Name=name , Quantity=quantity , Buy=buy_price , Sell=sell_price]
Equity & Bonds: [Instrument Type= Equity , Name=AAA , Quantity=123 , Buy=1.01 , Sell=1.10]
Equity & Bonds: [Instrument Type= Equity , Name=BBBB , Quantity=3 , Buy=1.05 , Sell=1.01]
Equity & Bonds: [Instrument Type= Bond , Name=CCC , Quantity=3 , Buy= , Sell=]
Equity & Bonds: [Instrument Type= Equity , Name=AAA , Quantity=12 , Buy=1.11 , Sell=1.13]
Equity & Bonds: [Instrument Type= Bond , Name=DD , Quantity=3 , Buy= , Sell=]
Done reading CSV file
ALTERNATIVELY, rename read method to main in CSVRead
class public class CSVRead {
static void main() throws IOException {
then call it like you do CSVRead.main(); in CSVMain class
Related
I'm using an arraylist to append inputs and send the arraylist elements to file. However, everytime I exit the program and run it again, the contents in the written in the file becomes empty.
ArrayList<String> memory = new ArrayList<String>();
public void fileHandling() {
try {
FileWriter fWriter = new FileWriter("notes.data");
for (int x = 0; x <= memory.size() - 1; x++) {
fWriter.write(memory.get(x) + '\n');
}
fWriter.close();
} catch (IOException e) {
System.out.println(e);
}
}
public void createNote() {
Scanner insertNote = new Scanner(System.in);
LocalDate todayDate = LocalDate.now();
LocalTime nowTime = LocalTime.now();
String timeFormat = nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
String dateTime = todayDate.toString() + " at " + timeFormat;
while (true) {
System.out.println();
System.out.println("Enter a note");
System.out.print("> ");
String note = insertNote.nextLine();
if (note == null) {
System.out.println("Invalid input! Try again");
break;
} else {
memory.add(note + " /" + dateTime);
fileHandling();
System.out.println("Note is saved!\n");
break;
}
}
I expect the program to save the contents of every input. Then if I exit and run the program again, the contents will go back to the array
Your code currently does the following:
You enter something (X) for the first time:
It gets added to the ArrayList
The ArrayList gets written into the file
Your file now contains: X
You enter something second (Y):
It gets added to the ArrayList (Which now contains: X, Y)
The ArrayList gets written into the file
Your file now contains: X + newline + Y
Your Problem is, that everytime you create a new FileWrite it overwrites your file.
This can be avoided by using the constructor like this:
FileWriter writer = new FileWriter("notes.data", true);
This sets it into the append mode and therefore keeps previous data in the file
You don't need to create a separate Scanner, in method createNote(), in order to get a "note" from the user.
It is usually better to write your code using the interface rather than the specific implementation because then you usually need to change less code if you decide to change the implementation. Hence the type for member variable memory should probably be List rather than ArrayList.
Note that ArrayList may waste memory if the list of "note"s is large. I suggest using LinkedList instead. Alternatively, use an array (rather than a List) and handle expanding the array when adding a "note" as well as reducing the array when removing a "note".
Having an infinite loop, i.e. while (true), which contains a single if-else where both the if block and the else block contain break statements, means that the loop will perform exactly one iteration. May as well remove the while loop – which means also removing the break statements.
Rather than writing the code that generates a timestamp repeatedly, you should adopt the DRY principle and extract that code into a separate method.
The file name should be a constant so as to minimize the amount of code changes you will need to do if you decide to change the file name.
By convention, text files have a filename extension of .txt whereas binary files have the .data extension.
Although you don't need to, I personally prefer to initialize class member variables in the constructor.
The below code is a SSCCE, hence I added a main method. More notes appear after the code.
package Methods;
import java.util.*;
import java.time.format.*;
import java.time.*;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileSys {
private static final String FILENAME = "notes.txt";
private static final String CREATE = "C";
private static final String DELETE = "D";
private static final String FIND = "F";
private static final String QUIT = "Q";
private static final String SHOW = "S";
private static final String UPDATE = "U";
Scanner reader;
List<String> memory;
public FileSys() throws IOException {
reader = new Scanner(System.in);
memory = new LinkedList<String>();
loadFile();
}
public void fileHandling() {
Path path = Paths.get(FILENAME);
try (BufferedWriter bw = Files.newBufferedWriter(path,
StandardOpenOption.CREATE,
StandardOpenOption.WRITE);
PrintWriter pw = new PrintWriter(bw)) {
for (String write : memory) {
pw.println(write);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public void createNote() {
String dateTime = getTimestamp();
System.out.println();
System.out.println("Enter a note");
System.out.print("> ");
String note = reader.nextLine();
memory.add(note + " / " + dateTime);
fileHandling();
System.out.println("Note is saved!");
}
public void searchNote() {
System.out.print("\nEnter note number: ");
try {
int search = reader.nextInt();
reader.nextLine();
System.out.println("\nSearch result:");
int index = memory.indexOf(memory.get(search - 1));
if (index != -1) {
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
}
else {
System.out.println("Note number-" + search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
}
public void updateNote() {
String dateTime = getTimestamp(); // ZonedDateTime.now(ZoneId.systemDefault()).format(dateTimeObj);
System.out.print("\nEnter note number to change: ");
try {
int search = reader.nextInt();
int index = memory.indexOf(memory.get(search - 1));
String updateLine;
if (index != -1) {
System.out.println("\nCurrent note: ");
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
System.out.println("\nThe updated note will be: ");
System.out.print("> ");
reader.nextLine();
updateLine = reader.nextLine();
memory.set(index, updateLine + " /" + dateTime);
System.out.print("Note has been updated successfully!\n");
}
else {
System.out.println(search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
fileHandling();
}
public void deleteNote() {
System.out.print("\nEnter note number to delete: ");
try {
int search = reader.nextInt();
reader.nextLine();
int index = memory.indexOf(memory.get(search - 1));
System.out.println();
if (index != -1) {
System.out.println("[" + (index + 1) + "]" + " " + memory.get(search - 1));
System.out.print("\nDo you want to delete this note? \n[y] or [n]: ");
char delDecision = reader.nextLine().charAt(0);
if (delDecision == 'y' || delDecision == 'Y') {
memory.remove(index);
System.out.println("Note has been deleted successfully!");
System.out.println();
}
else if (delDecision == 'n' || delDecision == 'N') {
System.out.println("Note was not deleted!");
}
else {
System.out.println("Invalid input!");
}
}
else {
System.out.println(search + " is not found in the collection!");
}
}
catch (IndexOutOfBoundsException e) {
System.out.println("The note number you have entered is invalid!");
}
fileHandling();
}
public void displayNote() {
if (memory.size() > 0) {
int counter = 0;
for (String note : memory) {
System.out.printf("%d. %s%n", ++counter, note);
}
}
else {
System.out.println("There are no notes.");
}
}
private String getTimestamp() {
LocalDate todayDate = LocalDate.now();
LocalTime nowTime = LocalTime.now();
String timeFormat = nowTime.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM));
String dateTime = todayDate.toString() + " at " + timeFormat;// ZonedDateTime.now(ZoneId.systemDefault()).format(dateTimeObj);
return dateTime;
}
private void loadFile() throws IOException {
Path path = Paths.get(FILENAME);
if (Files.isRegularFile(path)) {
memory.addAll(Files.readAllLines(path, Charset.defaultCharset()));
}
}
private void showMenu() {
String choice = "";
while (!QUIT.equalsIgnoreCase(choice)) {
System.out.println(CREATE + " - Create note");
System.out.println(DELETE + " - Delete note");
System.out.println(FIND + " - Search notes");
System.out.println(SHOW + " - Show notes");
System.out.println(UPDATE + " - Update note");
System.out.println(QUIT + " - Quit");
System.out.println();
System.out.print("Your choice: ");
choice = reader.nextLine();
if (!choice.isEmpty()) {
choice = choice.substring(0, 1);
choice = choice.toUpperCase();
switch (choice) {
case CREATE -> createNote();
case DELETE -> deleteNote();
case FIND -> searchNote();
case SHOW -> displayNote();
case UPDATE -> updateNote();
case QUIT -> System.out.println("Good bye.");
default -> System.out.println("Invalid: " + choice);
}
}
else {
System.out.println("No selection entered. Retry.");
}
}
}
public static void main(String[] args) {
try {
FileSys fs = new FileSys();
fs.showMenu();
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
Your code does not initially load memory with contents of file notes.txt so I added that in the constructor. Consequently you don't need to append to the file since you simply overwrite it with contents of memory.
The file handling is done using NIO.2 including try-with-resources – which was added in Java 7. There are more NIO.2 examples in the JDK documentation.
Whenever the code throws an unexpected exception, it is nearly always a good idea to print the stack trace.
if I want to read file from text file and store it in an array,each line goes to correct array
this is the text file
111111,34,24.5,first line
222222,53,22.0,second line
333333,,32.0,third line
44444,22,12.6,
if line is empty through exception saying "title is missing" or something like that.
a code has been made if the array length==4 then display lines in order but if length less than 4 and line is missing throw exception but when I want to put last array[3] gives me error. have a look if you can seethe error that would help
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Itry {
public static void main(String[] args) {
// TODO Auto-generated method stub
String [] splitArray = new String[4];
String line = "";
String array1, description;
int number;
double price;
// Total sales
double total = 0;
Scanner keyboard = new Scanner (System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
Scanner fileReader = null;
try {
File Fileobject = new File (filename);
fileReader = new Scanner (Fileobject);
System.out.println("\nTransactions");
System.out.println("================");
while(fileReader.hasNext())
{
// Contains stock code,Quantity,Price,Description
line = fileReader.nextLine();// Read a line of data from text file
splitArray = line.split(",");
// check to make sure there are 4 parts in splitArray
if(splitArray.length == 4)
{
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
// Extract each item into an appropriate
// variable
try {
array1 = splitArray[0];
number = Integer.parseInt(splitArray[1]);
price = Double.parseDouble(splitArray[2]);
description = splitArray[3];
// Output item
System.out.println("Sold "+String.format("%-5d", number) +
String.format("%-12s", description )+ " at "+"£"+
String.format("%-5.2f", price));
// Compute total
total += number * price;
} // end of try
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}
} //end of if
else if (splitArray[0].length()<1) {
try { splitArray[0] = splitArray[0].trim();
System.out.println(" Title is missing "+" "+splitArray[1] +""+splitArray[2]+"");
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}
}
else if (splitArray[1].length()<=1) {
try { splitArray[1] = splitArray[1].trim();
System.out.println(splitArray[0]+" "+" here is missing " +""+splitArray[2] );
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
else if (splitArray[2].length()<=1) {
try { splitArray[2] = splitArray[2].trim();
System.out.println(splitArray[0]+" "+splitArray[1] +""+" here is missing "+splitArray[3]);
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
else if (splitArray[3].length()<=1) {
try { splitArray[3] = splitArray[3].trim();
System.out.println(splitArray[0]+" "+splitArray[1] +""+splitArray[2]+"title is missing");
}
catch(NumberFormatException e)
{
System.out.println("Error: Cannot convert to number");
}}
}//end of while
System.out.printf("\nTotal sales: £"+String.format("%-6.2f", total));
}// end of try block
catch (FileNotFoundException e)
{
System.out.println("Error - File does not exist");
}
}
}
You can do it as follows:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] splitArray = new String[4];
String line = "";
String array1, description;
int number;
double price;
// Total sales
double total = 0;
Scanner keyboard = new Scanner(System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("This program will try to read data from a text file ");
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
Scanner fileReader = null;
try {
File Fileobject = new File(filename);
fileReader = new Scanner(Fileobject);
System.out.println("\nTransactions");
System.out.println("================");
int count = 1;
while (fileReader.hasNext()) {
// Contains stock code,Quantity,Price,Description
line = fileReader.nextLine();// Read a line of data from text file
try {
if (line != null && line.length() > 0) {
splitArray = line.split(",");
// check to make sure there are 4 parts in splitArray
if (splitArray.length == 4) {
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
// Extract each item into an appropriate variable
try {
array1 = splitArray[0];
number = Integer.parseInt(splitArray[1]);
price = Double.parseDouble(splitArray[2]);
description = splitArray[3];
// Output item
System.out.println(
"Sold " + String.format("%-5d", number) + String.format("%-12s", description)
+ " at " + "£" + String.format("%-5.2f", price));
// Compute total
total += number * price;
} catch (NumberFormatException e) {
System.out.println("Error in line#" + count + ": insufficient/invalid data");
}
} else {
throw new IllegalArgumentException(
"Error in line#" + count + ": insufficient/invalid data");
}
} else {
throw new IllegalArgumentException("Line#" + count + " is empty");
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
count++;
} // end of while
System.out.printf("\nTotal sales: £" + String.format("%-6.2f", total));
} catch (FileNotFoundException e) {
System.out.println("Error - File does not exist");
}
}
}
A sample run:
This program will try to read data from a text file
Enter the file name: data2.txt
Transactions
================
Sold 34 Apple at £24.50
Line#2 is empty
Sold 53 Mango at £22.00
Line#4 is empty
Error in line#5: insufficient/invalid data
Line#6 is empty
Error in line#7: insufficient/invalid data
Total sales: £1999.00
Content of data2.txt:
111111,34,24.5,Apple
222222,53,22.0,Mango
333333,,32.0,Orange
44444,22,12.6,
I have done a code, which reads a file consists a number of employees, salary, and their rankings, based on their rankings how can we add the bonus percent to their salary...
String phrases;
int salary=0;
try {
FileReader in = new FileReader("bonus.txt");
BufferedReader readFile = new BufferedReader(in);
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
double bonus;
if(phrases.contains("1")){
bonus=salary/0.03;
System.out.println("Bonus: " + bonus);
}else if(phrases.contains("2")){
bonus=salary/0.08;
System.out.println("Bonus: " + bonus);
}else if(phrases.contains("3")){
bonus=salary/0.20;
System.out.println("Bonus: " + bonus);
}
// System.out.println();
}
readFile.close();
in.close();
}catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
It outputs:
Jame 900000 1
Bonus: 0.0
Jane 60000 2
Bonus: 0.0
Don 866000 3
Bonus: 0.0
I have no idea why
If you have an employeeBonus.txt file like below.
Jame 900000 2
Jane 60000 1
Don 866000 3
I think you will have three tokens as a string so, you can use a stringtokenizer class in order to get a salary and a grade.
At the first line of file is
Jame 900000 2
and the result of encoded string was
Jame%20%20%20%20900000%092
I've finally found the content of text file was mixed with a space and tab character by URL encoding.
So, the usage of this type is as follows,
StringTokenizer stTok = new StringTokenizer(phrase, " \t");
It takes a salary and an identifier of bonus value from third and second token.
name = stTok.nextToken(); //first token
salary = Integer.valueOf(stTok.nextToken()).intValue(); //second token
grade = stTok.nextToken();
[source code]
package com.tobee.tests.inout;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class CheckBounsFromFile {
public static void main(String[] args) {
String name, phrase, grade;
double bonus = 0;
int salary = 0;
BufferedReader readFile = null;
try {
readFile = new BufferedReader(new FileReader("resource/aa/employeeBonus.txt"));
while ((phrase = readFile.readLine()) != null) {
//System.out.println(phrase);
StringTokenizer stTok = new StringTokenizer(phrase, " \t");
name = stTok.nextToken();
salary = Integer.valueOf(stTok.nextToken()).intValue();
grade = stTok.nextToken();
if(grade!= null && !grade.equals(""))
{
if (grade.equals("1")) {
bonus = salary / 0.03;
} else if (grade.equals("2")) {
bonus = salary / 0.08;
} else if (grade.equals("3")) {
bonus = salary / 0.20;
}
System.out.printf("name[%s]salary[%d]Bonus[%f] \n",name, salary, bonus);
}
}
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
finally
{
try {
readFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
[result]
name[Jame]salary[900000]Bonus[30000000.000000]
name[Jane]salary[60000]Bonus[750000.000000]
name[Don]salary[866000]Bonus[4330000.000000]
Have a nice day.
The other answers appear to not cater for the fact that your salary variable is always 0, thus, your bonus calculation, which depends on your salary value will always be 0.
Assuming that this: Jame 900000 1 is a sample line from your text file, there are various issues with your code.
The first issue is this: (phrases.equals("1"). If phrase will be equal to the text in the current line you are processing: Jame 900000 1, this statement (and the same for the other two) will never return true, thus the bonus will never be calculated.
The second issue is that you are never extracting the salary value.
You will need to replace this:
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
if(phrases.equals("1")){
With something like this:
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
String[] employeeData = phrases.split("\\t"); //This assumes that your data is split by tabs.
salary = Double.parse(employeeData[1]);
if("1".equals(employeeData[2])) {
bonus = salary * 0.03;
}
...
You check the condition with equals method but your phrases variable contains different value rather than 1,2,3 that's why you get the bonus 0.
if(phrases.contains("1")){
bonus=salary/0.03;
}else if(phrases.contains("2")){
bonus=salary/0.08;
}else if(phrases.contains("3")){
bonus=salary/0.20;
}
or you can get the last parameter with:
phrases.substring(phrases.length()-1, phrases.length())
you can get the third parameter using contains or split method.
Please check this tutorial: https://www.tutorialspoint.com/java/java_string_split.htm
And one more thing your salary is always zero (0). please correct it
I have posted full code here:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class SubClass{
public static void main(String[] args) {
String phrases;
int salary=0;
try {
FileReader in = new FileReader("bonus.txt");
BufferedReader readFile = new BufferedReader(in);
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
phrases = phrases.trim().replaceAll("[ ]{2,}", " ");
String splitStr [] = phrases.split(" ");
double bonus;
salary = Integer.parseInt(splitStr[1]);
if(splitStr[2].contains("1")){
bonus=salary/0.03;
System.out.println("Bonus: " + bonus);
}else if(splitStr[2].contains("2")){
bonus=salary/0.08;
System.out.println("Bonus: " + bonus);
}else if(splitStr[2].contains("3")){
bonus=salary/0.20;
System.out.println("Bonus: " + bonus);
}
// System.out.println();
}
readFile.close();
in.close();
}catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
}
I'm new to java and learning as I go, I'm currently working on arrays, I seem to be at a loss as to what I'm doing wrong here. I do not think it is pulling the data in the correct way, this program is suppose to read data from a text file, and ask the user for additional inputs, then display a report. I seem to be having issues with the donation output bits, as I have not gotten it to work once... The program dose compile and run, netbeans says its all green except for the bits of disabled code below for the display method. Any suggestions, comments and points in the right direction are greatly appreciated =)
Also could use some advice on getting the decimal places to line up all together for both the text file output and program display output.
The main class
import java.util.Scanner;
public class MyEventManager
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.printf("\nI will read a text file then add it with user "
+ "inputs in \norder to display and export a report detailing "
+ "an event.\n\n");
boolean startOver = false;
if (startOver == false) //enter loop
{
do
{
//ticket price
System.out.printf("What is the single ticket price for "
+ "the event? ");
double singleTicket = keyboard.nextDouble();
//maximum number of donations
System.out.printf("What is the maximum number of donations "
+ "expected for the event? ");
int maxDonations = keyboard.nextInt();
//create a new object for event class
MyEventClass myEvent = new MyEventClass(singleTicket,
maxDonations);
if (myEvent.fruityLoops == false)
do
{
myEvent.readAllData();
}
while (myEvent.fruityLoops != true);
myEvent.displayResults();
System.out.printf("\nWould you like to run program again? "
+ "[Y/N] - ");
String questionAskLoop = keyboard.next();
if ("N".equalsIgnoreCase(questionAskLoop))
{
startOver = true; //sets exit condition to end program...
}
}
while(startOver != true);
}
}
}
The second class
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
public class MyEventClass
{
private final double TICKET_PRICE;
private final int []moneyDonated;
private double totalTicketsSold;
private int DONATION_ARRAY_SIZE;
private int storedAmountDonations;
private double moneySpent;
boolean fruityLoops;
private boolean donationSuccess;
public static char amountType;
public static double amount;
public MyEventClass (double singleTicket, int maxDonations)
{
this.moneyDonated = new int[]{DONATION_ARRAY_SIZE};
this.fruityLoops = false;
this.TICKET_PRICE = singleTicket;
this.DONATION_ARRAY_SIZE = maxDonations;
this.moneySpent = 0;
}
public boolean myDonation (double donationAmount, int[] moneyDonated)
{
if (storedAmountDonations == DONATION_ARRAY_SIZE)
{
return false;
}
else
{
moneyDonated[storedAmountDonations] = (int) donationAmount;
storedAmountDonations++;
return true;
}
}
public void addNewTickets (double addedTickets)
{
totalTicketsSold += (int) addedTickets;
}
public double getTicketSales ()
{
return totalTicketsSold;
}
public double getTicketEnd ()
{
double ticketEnd = totalTicketsSold * TICKET_PRICE;
return ticketEnd;
}
public int [] getMoneyDonated (int[] moneyDonated)
{
//Calculate and return the total amount of money donated
return moneyDonated;
}
public int storedAmountDonations ()
{
return storedAmountDonations;
}
public double getMoneySpent ()
{
return moneySpent;
}
public void sortMethod (char amountType, double amount)
{
if(amount <= 0) //positive amount check
{
throw new IllegalArgumentException("Error Code B-90: Invalid amount "
+ "(not over 0) -- line: " + amountType + " " + amount
+ " ignored");
}
else if (amountType == 'T' || amountType == 't') //tickets
{
addNewTickets(amount);
}
else if (amountType == 'D' || amountType == 'd') //donations
{
myDonation(amount, moneyDonated);
if (donationSuccess == false) //checks if array is full
{
throw new ArrayIndexOutOfBoundsException ("Error code B-103: "
+ "The array is full " + amount + " will not be stored"
+ " in the array");
}
}
else if (amountType == 'E' || amountType == 'e') //amount spent
{
moneySpent += amount;
}
else
throw new IllegalArgumentException("Error Code B-113: Invalid item "
+ "type (not T, D, or E) -- line: " + amountType + " "
+ amount + " ignored");
}
public void readAllData()
{
int lineCount = 0;
Scanner keyboard = new Scanner( System.in );
System.out.printf("\nPlease input the file location: ");
String readFile = keyboard.next();
try
{
File inputFile = new File (readFile);
Scanner scanFile;
scanFile = new Scanner( inputFile );
System.out.println("Reading data file....");
while (scanFile.hasNext())
{
amountType = scanFile.next().charAt(0);
amount = scanFile.nextDouble();
lineCount++;
try
{
sortMethod(amountType, amount);
}
catch (IllegalArgumentException a)
{
System.out.printf("\nError code B-145: An error occured "
+ "while attempting to add the data from file");
}
catch (ArrayIndexOutOfBoundsException b)
{
System.out.printf("\nError code B-150: An error occured "
+ "while attempting to add to the array.");
}
}
scanFile.close();
System.out.printf("\nThe total amount of readable lines where "
+ lineCount + " lines.\n\n");
}
catch (FileNotFoundException c)
{
System.out.printf("\nError code B-160: The file " + readFile
+ " was not found!\n");
fruityLoops = false; //restart program
}
fruityLoops = true; //contuine on with program
}
public int getLowest (int[] moneyDonated)
{
int lowValue = moneyDonated[0];
for(int i=1;i < moneyDonated.length;i++)
{
if(moneyDonated[i] < lowValue)
{
lowValue = moneyDonated[i];
}
}
return lowValue;
}
public double getAverage(int[] moneyDonated)
{
int sum = moneyDonated[0];
for(int i=1;i < moneyDonated.length;i++)
sum = sum + moneyDonated[i];
double advValue = sum / moneyDonated.length;
return advValue;
}
public int getHighest (int[] moneyDonated)
{
int maxValue = moneyDonated[0];
for(int i=1;i < moneyDonated.length;i++)
{
if(moneyDonated[i] > maxValue)
{
maxValue = moneyDonated[i];
}
}
return maxValue;
}
public void displayResults()
{
double income = 0;//moneyDonated + ticketEnd;
double profits = income - moneySpent;
Scanner keyboard = new Scanner ( System.in );
System.out.printf("\nWhere is the file for the report export? ");
String reportFile = keyboard.next();
try
{
File outputFile = new File (reportFile);
Scanner scanFile = new Scanner (outputFile);
System.out.println("Generating output data file....");
try (BufferedWriter writer =
new BufferedWriter(new FileWriter(outputFile)))
{
writer.write("Event Overall Outcome:");
writer.newLine();
writer.write("Ticket Price %15.2f" + TICKET_PRICE);
writer.newLine();
writer.newLine();
writer.write("Donation Analysis:");
writer.newLine();
writer.write("Lowest donation " + getLowest (moneyDonated));
writer.newLine();
writer.write("Adverage donation " + getAverage (moneyDonated));
writer.newLine();
writer.write("Highest donation " + getHighest(moneyDonated));
writer.newLine();
writer.newLine();
writer.write("Profit/Loss Results:");
writer.newLine();
writer.write(totalTicketsSold + "Tickets sold" + getTicketEnd());
writer.newLine();
writer.write(storedAmountDonations() + " Donations "
+ Arrays.toString(moneyDonated) + " +");
writer.newLine();
writer.write(" --------");
writer.newLine();
writer.write("Total Income " + "%14.2f" + income);
writer.newLine();
writer.write("Total Expenses " + "%12.2f" + " -" + moneySpent);
writer.newLine();
writer.write(" --------");
writer.newLine();
if (profits < 1)
{
writer.write(" Event Losses " + "%13.2f " + profits);
}
else
{
writer.write(" Event Profits " + "%13.2f " + profits);
}
writer.flush();
writer.close();
}
catch (IOException d)
{
System.out.printf("\nError code B-280: There was an error "
+ "while attempting to write to " + reportFile
+ "\nThe file may be damaged!");
}
System.out.printf("\nOutput Success!");
}
catch (FileNotFoundException d)
{
System.out.printf("\nError code B-288: The file " + reportFile
+ " could not be opened! The report cannot be generated.\n");
}
System.out.printf("\nEvent Overall Outcome:");
System.out.printf("\n\n Ticket Price %15.2f", TICKET_PRICE);
System.out.printf("\n\n Donation Analysis: ");
/*System.out.printf("\n Lowest donation " + "%10.2f",
getLowest (moneyDonated));
System.out.printf("\n Adverage donation " + "%10.2f",
getAverage (moneyDonated));
System.out.printf("\n Highest donation " + "%10.2f",
getHighest(moneyDonated));*/
System.out.printf("\n\n Profit/Loss Results: ");
System.out.printf("\n " + totalTicketsSold + " Tickets sold "
/*+ "%3.2f"*/ + getTicketEnd());
System.out.printf("\n " + storedAmountDonations() + " Donations "
/* + "%3.2f"*/ + Arrays.toString(moneyDonated) + " +");
System.out.printf("\n --------");
System.out.printf("\n Total Income " + "%14.2f", income);
System.out.printf("\n Total Expenses " + "%12.2f" + " -", moneySpent);
System.out.printf("\n --------");
if (profits < 1)
{
System.out.printf("\n Event Losses " + "%13.2f \n\n", profits);
}
else
{
System.out.printf("\n Event Profits " + "%13.2f \n\n", profits);
}
}
}
This is the text file input
T 25
E 210.99
T 1
D 500.00
E 134.67
D 1
This is text file output
Event Overall Outcome:
Ticket Price %15.2f60.0
Donation Analysis:
Lowest donation 500
Adverage donation 500.0
Highest donation 500
Profit/Loss Results:
26.0Tickets sold1560.0
1 Donations [500] +
--------
Total Income %14.2f0.0
Total Expenses %12.2f -345.65999999999997
--------
Event Losses %13.2f -345.65999999999997
And lastly this is what the program displays to the screen...
run:
I will read a text file then add it with user inputs in
order to display and export a report detailing an event.
What is the single ticket price for the event? 25
What is the maximum number of donations expected for the event? 2
Please input the file location: event.txt
Reading data file....
Error code B-150: An error occured while attempting to add to the array.
Error code B-150: An error occured while attempting to add to the array.
The total amount of readable lines where 6 lines.
Where is the file for the report export? export.txt
Error code B-288: The file texport.txt could not be opened! The report
cannot be generated.
Event Overall Outcome:
Ticket Price 25.00
Donation Analysis:
Profit/Loss Results:
26.0 Tickets sold 650.0
1 Donations [500] +
--------
Total Income 0.00
Total Expenses 345.66 -
--------
Event Losses -345.66
Would you like to run program again? [Y/N] -
Just as an FYI, for my exception error codes A is the main class and B is the second class, the number the follows is the line of code the message came from. Just something I was trying to help me find my place faster...
My goal is to get the display to look like this.
Your main issue is in your second class:
this.moneyDonated = new int[]{DONATION_ARRAY_SIZE};
This is not creating an array of size DONATION_ARRAY_SIZE.
Proper syntax is:
this.moneyDonated = new int[DONATION_ARRAY_SIZE];
There are 2 critical issues above. Firstly the size of the array. You should have something like this:
this.DONATION_ARRAY_SIZE = maxDonations;
this.moneyDonated = new int[DONATION_ARRAY_SIZE];
Secondly, the donationSuccess boolean will be initialised to false. And you have this block of code:
if (donationSuccess == false) //checks if array is full
{
throw new ArrayIndexOutOfBoundsException ("Error code B-103: "
+ "The array is full " + amount + " will not be stored"
+ " in the array");
}
You never change that donationSuccess value hence that block of code will always throw that error even though it is not the case. You should rethink the way you initialise and set the donationSuccess value.
I am getting this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at JavaProject.main(JavaProject.java:70)
Here is the code:
try
{
PrintWriter writer = new PrintWriter("Gamer Report Data.txt");
writer.println("Player: " + gamerName);
writer.println();
writer.println("-------------------------------");
String[] report = gamerReport.split(gamerReport, ':');
writer.println("Game:" + ", score=" + report[1] + ", minutes played=" + report[2] + report[3]);
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
I believed it to be something related to my for loop, but I have had no luck changing it around.
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.io.PrintWriter;
public class JavaProject {
private static char[] input;
#SuppressWarnings("null")
public static void main(String[] args) {
for (int b = 1; b < 100; b++) {
// this is making the code loop 100 times
int hrs, mins;
int[] gameCount;
int[] minutesPlayed = new int[100];
String gamerName, gamerReport;
// Main data storage arrays
String[] gameNames = new String[100];
int[] highScores = new int[100];
Scanner Scan = new Scanner(System.in);
// formatting for output and input
System.out.println("////// Game Score Report Generator \\\\\\\\\\\\");
System.out.println(" ");
// user enters name and then moves to next line
System.out.println("Enter Your Name");
gamerName = Scan.nextLine();
// user is given an example of input format
System.out.println("Input Gamer Information " + "Using Format --> Game : Achievement Score : Minutes Played");
System.out.println(" ");
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
String[] splitUpReport; // an array of string
splitUpReport = gamerReport.split(":"); // split the text up on the colon
int i = 0;
// copy data from split text into main data storage arrays
gameNames[i] = splitUpReport[0];
highScores[i] = Integer.parseInt(splitUpReport[1].trim());
minutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());
// output to file
try
{
PrintWriter writer = new PrintWriter("Gamer Report Data.txt");
writer.println("Player: " + gamerName);
writer.println();
writer.println("-------------------------------");
String[] report = gamerReport.split(gamerReport, ':');
writer.println("Game:" + ", score=" + report[1] + ", minutes played=" + report[2] + report[3]);
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
}
}
public static char[] getInput() {
return input;
}
public static void setInput(char[] input) {
JavaProject.input = input;
}
}
There are two problems with your code:
1)
String[] report = gamerReport.split(gamerReport, ':');
should be
String[] report = gamerReport.split(":");
as you did with splitUpReport (not sure why you're splitting again actually).
2) Arrays are zero-indexed, so the print statement should look like this:
writer.println("Game:" + ", score=" +report[0] +", minutes played="+ report[1] + report[2]);
The error in your code is being caused by this code in the try block:
String[] report = gamerReport.split(gamerReport, ':');
You are actually trying to split the gamerReport string using itself as a regex, with a limit of 58, which is the numerical value of the colon.
The result of this split is 2 empty String elements, which correspond to the match happening before and after the regex, which is the string itself.
The ArrayIndexOutOfBounds exception is happening when you try to access the third element from this array:
To fix your problem, just define the report array as follows:
String[] report = gamerReport.split(':');
As #shmosel pointed out, you might also want to change your array indices here as well:
writer.println("Game:" + ", score=" + report[0] +", minutes played="+ report[1] + report[2]);