Hey guys I am doing a project for school and am having a little trouble, I have a variable "reservationNumber" and im attempting to check if the number the user inputs is in the array, if not it returns a string saying the number was not found. It is working fine and displays the correct info when there is a valid input but when an invalid input is detected it gives a null.pointer.exception error. I tried writing it so that if the number is not detected the private method returns -1, then when I call the tickerInformation method, if that the variable 'ticket' returns -1 then it returns "invalid reservation number". This is where is error is being raised and only occurs when I enter an invalid number please help.
public void ticketInformation(String reservationNumber)
{
int ticket = searchArray(reservationNumber);
if (ticket == -1)
{
System.out.println("The reservation number entered was n0t found");
}
else
{
System.out.print("\n" + ticketSale[ticket].toString());
}
}
private int searchArray(String reservationNumber)
{
for (int i = 0; i < ticketSale.length; i++)
{
if (ticketSale[i].getReservationNumber().equals(reservationNumber))
{
return i;
}
}
return -1;
}
ticketSale[i].getReservationNumber().equals(reservationNumber) has an issue. Share the declaration and init for array "ticketSale". If ticketSale array is for abstract data type then why equal is called with String?
You didn't post the whole code but I think that when you enter invalid number as reservation number, it does not assigned to the related object's instance variable. So getReservationNumber() might be returning null.
Add a null check,
private int searchTicketSales(String reservationNumber) {
int reservationNumberIndex = -1;
for (int i = 0; i < ticketSale.length; i++) {
if (null != ticketSale[i].getReservationNumber() && ticketSale[i].getReservationNumber().equals(reservationNumber)) {
reservationNumberIndex = i;
break;
}
}
return reservationNumberIndex;
}
Best Regards,
Rakesh
Add a regex to validate that your input is a valid number "\\d+":
public void ticketInformation(String reservationNumber)
{
String regex = "\\d+";
if(!reservationNumber.matches(regex))
{
System.out.println("The reservation number entered was n0t found");
}
int ticket = searchArray(reservationNumber);
if(ticket == -1)
{
System.out.println("The reservation number entered was n0t found");
}
else
{
System.out.print("\n" + ticketSale[ticket].toString());
}
}
You might want to validate searchArray, particularly if it is not used interdependently from ticketInformation().
Related
i have sorted an array with double value
Arrays.sort(banding);
then i want to setText with the highest value that have specific String value "CUKUP". If it's not "CUKUP" than it's must be "LEBIH" and i don't want any "LEBIH" String value as an output
if (banding[6].getKetTotal().equals("CUKUP")) {
untungtertinggi.setText(Double.toString(banding[6].harga));
} else if (banding[6].getKetTotal().equals("LEBIH")) {
if (banding[5].getKetTotal().equals("CUKUP")) {
untungtertinggi.setText(Double.toString(banding[5].harga));
}
}else if (banding[5].getKetTotal().equals("LEBIH")) {
if (banding[4].getKetTotal().equals("CUKUP")) {
untungtertinggi.setText(Double.toString(banding[4].harga));
}
}else if (banding[4].getKetTotal().equals("LEBIH")) {
if (banding[3].getKetTotal().equals("CUKUP")) {
untungtertinggi.setText(Double.toString(banding[3].harga));
}
}else if (banding[3].getKetTotal().equals("LEBIH")) {
if (banding[2].getKetTotal().equals("CUKUP")) {
untungtertinggi.setText(Double.toString(banding[2].harga));
}
}else if (banding[2].getKetTotal().equals("LEBIH")) {
if (banding[1].getKetTotal().equals("CUKUP")) {
untungtertinggi.setText(Double.toString(banding[1].harga));
}
}else if (banding[1].getKetTotal().equals("LEBIH")) {
if (banding[0].getKetTotal().equals("CUKUP")) {
untungtertinggi.setText(Double.toString(banding[0].harga));
}
}
this coding is still wrong because when all arrays have String value "CUKUP" it doesn't put the highest double value as an output
It is not clear what is supposed to be output if the checks fail, so I'm guessing 0.0, but it could be adjusted.
The approach, if I followed the OP's logic, can be condensed to a loop, reducing the amount of checking. The specific object type of the array banding was not specified, so I haphazardly used Banding as the object type -- that is probably not exactly correct.
NOTE: the assumption is that the array is properly sorted.
Arrays.sort(banding);
setText(banding);
void setText(Banding[] banding) {
final int loc = banding.length - 1;
// if the highest is what we want, set and return
if (banding[loc].getKekTotal().equals("CUKUP")) {
untungtertinggi.setText(Double.toString(banding[loc].harga));
return;
}
// we run until one before the start of the array, as we check for the
// previous value; if we meet the criteria of [i] being LEBIH, and [i - 1]
// being CUKUP, then we set the value and return
for (int i = loc; i > 0; --i) {
if (banding[i].getKekTotal().equals("LEBIH") &&
banding[i - 1].getKetTotal().equals("CUKUP")) {
untungtertinggi.setText(Double.toString(banding[i - 1].harga));
return;
}
}
// no specific value found
untuntertinggi.setText(Double.toString(0.0));
}
I am trying to loop through an array twice, once to create an array of Objects, and then during the creation of the array, check to make sure the address does not exist already in an another array. This is for a Java II class. I've overridden the default equals function to be a comparative one, checking the streetAddress field to see if they match.
The issue I'm trying to avoid is, that first, I create a NewspaperSubscriber object, then I check to make sure it doesn't already exist, however it will always exist if it's already been created! I'm trying to find a way in my second for loop (incrementing on y) to skip whatever element i'm currently processing in it's parent loop (incrementing on x).
Working on it for a while now, having a hard time with my exception. I don't want to modify my NeswpaperSubscriber class, as it needs to compare NeswpaperSubscriber.String to NewspaperSubscriber.String, not NewspaperSubscriber.String to String. Thoughts?
import javax.swing.*;
import java.util.Scanner;
public class Subscribers {
static int x, y;
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
NewspaperSubscriber[] subscribers= new NewspaperSubscriber[5];
for (x = 0; x < subscribers.length; ++x) {
System.out.println("x = " + x);
String userEntry;
int subscriberType;
String address;
userEntry = JOptionPane.showInputDialog(null, "Please select the type of \n" +
"subscribers you want to enter: \n" +
"\t1 - Seven Day\n" +
"\t2 - Weekday\n" +
"\t3 - Weekend");
subscriberType = Integer.parseInt(userEntry);
if (subscriberType == 1) {
address = addressEntry();
subscribers[x] = new SevenDaySubsriber(address);
checkAddress(subscribers, subscribers[x]);
} else if (subscriberType == 2) {
subscribers[x] = new WeekdaySubscriber(addressEntry());
} else {
subscribers[x] = new WeekendSubscriber(addressEntry());
}
}
StringBuffer outString = new StringBuffer();
for (x = 0; x < subscribers.length; ++x) {
outString.append("\n#" + (x + 1) + " ");
outString.append(subscribers[x].toString());
}
JOptionPane.showMessageDialog(null, " Our available subscribers include: \n" + outString);
}
public static String addressEntry() {
String enteredAddress = JOptionPane.showInputDialog(null, "Please enter address");
System.out.println(enteredAddress);
return enteredAddress;
}
public static void checkAddress(NewspaperSubscriber[] subscribers, NewspaperSubscriber newSub) {
for (y = 0; y < subscribers.length && y !=x; ++y) {
System.out.println("x = " + x);
System.out.println();
System.out.println("y = " + y);
System.out.println();
if (subscribers[y].equals(newSub)) {
JOptionPane.showMessageDialog(null, "That address already exists!");
} else {
}
}
}
}
//From base class Newspaper subscriber
public boolean equals(NewspaperSubscriber otherSubscriber) {
boolean result;
if (streetAddress == otherSubscriber.streetAddress)
result = true;
else result = false;
return result;
}
my results!
x = 0
123
x = 1
123
x = 2
123
x = 3
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Subscribers.main(Subscribers.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Process finished with exit code 1
So basically I recognize the following questions:
Question 1
I'm trying to find a way in my second for loop (incrementing on y) to skip whatever element i'm currently processing in it's parent loop (incrementing on x).
Just don't insert the new element before doing the check. Hence, you want to swap these two lines:
subscribers[x] = new SevenDaySubsriber(address);
checkAddress(subscribers, subscribers[x]);
To fulfill the odd requirements of your instructor you could pass the index where you insert the new subscriber to your checkAddress method and just skip it. However this restriction itself is very strange (to not call it bad design).
public static void checkAddress(NewspaperSubscriber[] subscribers, NewspaperSubscriber newSub, int skipIndex) {
for (int y = 0; y < subscribers.length; ++y) {
if (y != skipIndex && subscribers[y].equals(newSub)) {
JOptionPane.showMessageDialog(null, "That address already exists!");
}
}
Question 2
Working on it for a while now, having a hard time with my exception.
The Exception occurs at the line
subscriberType = Integer.parseInt(userEntry);
You closed (cancelled) the popup window which makes JOptionPane.showInputDialog(...) return null. This is obviously not a valid Integer, which is why you get the mentioned Exception.
Note
In your method NewspaperSubscriber.equals(...) you should use String.equals(other) rather than ==. For more information see here.
The purpose of this project is to make a pokedex that adds and holds all the pokemon passed in by user input. When the user inputs a pokemon that is already stored in the pokedex the word "duplicate" is supposed to be printed to the console. The word duplicate is printed even though there are no actual duplicates within the object array. Here is my output from the console :
Welcome to your new PokeDex!
How many Pokemon are in your region?: 3
Your new Pokedex can hold 3 Pokemon. Let's start using it!
List Pokemon
Add Pokemon
Check a Pokemon's Stats
Sort Pokemon
Exit
What would you like to do? 2
Please enter the Pokemon's Species: red
Duplicate
Now here is all the code used that could possibly be making this error
import java.util.Scanner;
public class Project4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to your new PokeDex!");
System.out.print("How many Pokemon are in your region?: ");
int size = input.nextInt();
Pokedex pokedex = new Pokedex(size);
System.out.println("\nYour new Pokedex can hold " + size + " Pokemon. Let's start using it!");
int choice = 0;
boolean done = false;
while (!done) {
System.out.println("\n1. List Pokemon\n2. Add Pokemon\n3. Check a Pokemon's Stats" + "\n4. Sort Pokemon\n5. Exit");
System.out.print("\nWhat would you like to do? ");
choice = input.nextInt();
switch (choice) {
case 1:
String[] pokemonList = pokedex.listPokemon();
if (pokemonList == null)
System.out.println("Empty");
else
for (int i = 0; i < pokemonList.length; i++) {
System.out.println((i + 1) + ". " + pokemonList[i]);
}
break;
case 2:
System.out.print("\nPlease enter the Pokemon's Species: ");
String species = input.next();
pokedex.addPokemon(species);
break;
}
}
}
}
In the following class I have the actual method that adds the pokemon and the constructor for Pokedex
public class Pokedex {
Pokemon[] pokedex;
String pokeArray[];
public Pokedex(int size) {
pokedex = new Pokemon[size];
pokeArray = new String[size];
}
public boolean addPokemon(String species) {
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++) {
if (pokedex[i] == null) {
pokedex[i] = stuff;
}
else if (i < pokedex.length && pokedex[i] != null) {
System.out.println("Max");
}
if (pokedex[i].getSpecies().equalsIgnoreCase(species)) {
System.out.print("Duplicate");
break;
}
}
return false;
}
}
Sorry for the mass amounts of code I just need help tracing where this unexpected result is coming from.
The reason it's doing that is because of this bit of code here:
public boolean addPokemon(String species)
{
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++)
{
if (pokedex[i] == null)
pokedex[i] = stuff;
else if (i < pokedex.length && pokedex[i] !=null)
System.out.println("Max");
if(pokedex[i].getSpecies().equalsIgnoreCase(species))
{
System.out.print("Duplicate");
break;
}
}
return false;
}
The problem is just a little bit of syntax missing. In your for loop, you check to see if
A) there are any empty spots in the array
B) if every element in the array up to the user inputted size is full
and C) if any element in the array matches the one we're trying to add.
The problem you're encountering is because your C is an if instead of an else if. Because A sees the index is null, it assigns the new Pokemon to the Pokedex. Then because C is an if instead of an else if, it runs after you assign the new Pokemon and sees the Pokemon we just added and says it's a duplicate. Changing it to an else if would fix this.
Also, since there was no break; in A, it would assign every element of the array to the first one entered, causing any further additions to call Max. I edited the code and this is what I had that worked for me:
public boolean addPokemon(String species)
{
Pokemon stuff = new Pokemon(species);
for (int i = 0; i < pokedex.length; i++)
{
if(pokedex[i] !=null && pokedex[i].getSpecies().equalsIgnoreCase(species))
{
System.out.println("Duplicate");
break;
}
else if (pokedex[i] == null)
{
pokedex[i] = stuff;
break;
}
else if(i + 1 == pokedex.length)
{
System.out.println("Max");
break;
}
}
return false;
}
Also, out of curiosity, why is the addPokemon() function a boolean? You return a value (albeit arbitrarily) and then never do anything with that value. You could just make it a void, have it return nothing, and it would work just as fine.
I hope everyone is doing okay. I'm still new to this developer stuff, and although I find it really interesting I'm beginning to see how it can get tedious if you don't keep track of what you are doing. Im working on an update for a mock ATM program. The new version reads from a .txt file to validate account information. Once it is validated you can either check the balance, deposit money, withdrawal money, or log out. Once you do your transaction, the program is suppose to update the old .txt file with the updated balance for that account. I finally got everything to work like it is suppose to, but when I go back and check the updated .txt file, that particular account was updated but the rest of the strings in the file were updated to null and I can't figure out why and what is causing my program to do that. I have a feeling that the problem is in the upDate method and I'm overlooking something. Below you can see my source code and below the output of what I am getting. Any explanation about the logic behind this error would be greatly appreciated.
import java.util.*;
import java.io.*;
public class ATM2 {
public static Scanner kbd = new Scanner(System.in);
/*
* This method reads the number of lines in the .txt file
* and returns the array size.
*/
public static int arraySize () {
int result = 0;
try
{
Scanner lineReader = new Scanner(new FileReader("ATMData.txt"));
int lineCount=0;
while(lineReader.hasNextLine())
{
String size;
size = lineReader.nextLine();
lineCount++;
}
lineReader.close();
return lineCount;
}
catch(FileNotFoundException e)
{
System.out.println("ERROR: FILE NOT FOUND");
return result;
}
}
//Method searches .txt file and returns String
//array with all account info.
public static String[] acctLine(int size){
String[] validAccounts = null;
try
{
Scanner lineReader = new Scanner(new FileReader("ATMData.txt"));
int lineCount=0;
String [] acctNums= new String[size];
while(lineReader.hasNextLine())
{
String lineInfo;
lineInfo = lineReader.nextLine();
acctNums[lineCount]=lineInfo;
lineCount++;
}
lineReader.close();
return acctNums;
}
catch(FileNotFoundException e)
{
System.out.println("ERROR: FILE NOT FOUND");
return validAccounts;
}
}
//Method updates the txt file with new acct information.
public static void acctUpdate (String[] validAccount, String fileName){
try
{
PrintWriter newFile = new PrintWriter(new FileWriter(fileName));
for(int i=0; i<validAccount.length; i++){
newFile.println(validAccount[i]);
}
newFile.close();
}
catch(Exception e){
System.out.println("ERROR: FILE NOT PRINTED");
}
}
/*The checkID method determines if acctNum is a valid account number
* and pwd is the correct password for the account. If the account information
* is valid, the method returns the current account balance, as a string.
* If the account information is invalid, the method returns the string "error"
*/
public static String checkID(String acctNum, String pwd, String [] validAccounts)
{
String result = "ERROR";
String acctString = "ERROR";
boolean foundIt = false;
for(int i=0; i<validAccounts.length; i++) //Loop compares the input data with array data.
{
acctString = validAccounts[i];
if (acctNum.equals(acctString.substring(0, acctString.indexOf(" "))) &&
pwd.equals(acctString.substring(acctString.indexOf(" ")+1,acctString.lastIndexOf(" ")))){
foundIt = true;
result = acctString.substring(acctString.lastIndexOf(" ") + 1);
}
}
if (foundIt) //If it's true it returns the acct. balance.
{
return result;
}
else
{
System.out.println("ERROR: INVALID ACCOUNT TYPE");
}
return result;
}
/* This method finds the array index of the desired account string.
* and returns the the index of the line
*/
public static int arrayIndex(String acctNum, String pwd, String [] validAccounts)
{
int accountPos=0;
Boolean foundIt = false;
//loop searches for the index of the array.
for(accountPos=0; accountPos<validAccounts.length && !foundIt; accountPos++)
{
if (acctNum.equals(validAccounts[accountPos].substring(0, validAccounts[accountPos].indexOf(" "))) &&
pwd.equals(validAccounts[accountPos].substring(validAccounts[accountPos].indexOf(" ")+1, validAccounts[accountPos].lastIndexOf(" "))))
{
foundIt = true;
}
}
return accountPos;
}
/*Method creates menu options and returns
*the choice selected by the user.
*/
public static int menu()
{
int menuChoice;
do
{
System.out.print("\nENTER TRANSACTION TYPE: CHOOSE 1-4."
+ " \n 1. Display Balance"
+ "\n 2. Deposit\n 3. Withdraw\n 4. Log Out\n");
menuChoice = kbd.nextInt();
if (menuChoice < 1 || menuChoice > 4){
System.out.println("error");
}
}while (menuChoice < 1 || menuChoice > 4);
return menuChoice;
}
/*Method displays the balance to the screen.
*/
public static void displayBalance(double balance)
{
System.out.printf("\nYOUR NEW BALANCE IS: $%.2f\n", balance);
}
/*Method calculates the deposit going in to account.
Returns the total deposit.
*/
public static double deposit(double orgBal, double depAmt)
{
return orgBal + depAmt;
}
/*Method that calculates the balance after the withdraw.
* returns a double with the amount withdrawn.
*/
public static double withdraw(double orgBal, double wdrlAmt)
{
if (wdrlAmt > orgBal)
{
return orgBal;
}
else
{
return orgBal-wdrlAmt;
}
}
public static void main(String[] args) {
String accNum, pass, fileName="ATMData.txt", origBal = "ERROR";
String acctInfo;
int count = 0, menuOption = 0, acctPos;
double depositAmt, withdrawAmt, currentBal;
String [] validAccounts =acctLine(arraySize());
/*loop that will count the number of login attempts
*you make and will exit program if it is more than 3.
*as long as oriBal equals an error.
*/
do{
System.out.println("PLEASE ENTER YOUR ACCOUNT NUMBER: ");
accNum = kbd.next();
System.out.println("ENTER YOUR PASSWORD: ");
pass = kbd.next();
origBal = checkID(accNum, pass, validAccounts);
count++;
acctPos = arrayIndex(accNum, pass, validAccounts)-1;
if (count >= 3 && origBal.equals("ERROR:")){
System.out.print("MAX LOGIN ATTEMPTS REACHED.");
System.exit(0);
}
else if (!(origBal.equals("ERROR"))){
System.out.println("\nYOUR CURRENT BALANCE IS: $ "+ origBal);
}
else
System.out.println(origBal);
}while(origBal.equals("ERROR"));
currentBal=Double.parseDouble(origBal);
/*this loop will keep track of the options that
*the user inputs in for the menu. and will
*give the option of deposit, withdraw, or logout.
*/
while (menuOption != 4)
{
menuOption=menu();
switch (menuOption)
{
case 1:
displayBalance(currentBal);
break;
case 2:
System.out.print("HOW MUCH DO WISH TO DEPOSIT: $ ");
depositAmt = kbd.nextDouble();
currentBal = deposit(depositAmt, currentBal);
displayBalance(currentBal);
break;
case 3:
System.out.print("HOW MUCH DO YOU WISH TO WITHDRAW: $ ");
withdrawAmt = kbd.nextDouble();
if (withdrawAmt > currentBal)
System.out.println("ERROR: YOU DON'T HAVE ENOUGH FUNDS TO COMPLETE"
+ " TRANSACTION."
+ " ENTER TRANSACTION TYPE: CHOOSE 1-4");
currentBal = withdraw(currentBal, withdrawAmt);
displayBalance(currentBal);
break;
case 4://Last option logs user out after it updates the ATMData.txt
acctInfo = accNum + " " + pass + " " + String.valueOf(currentBal);
validAccounts[acctPos]=acctInfo;
acctUpdate(validAccounts, fileName);
System.out.println("LOGOUT SUCCESSFULL.");
System.exit(0);
break;
default:
}
}
}
}
And this is what the .txt looked like before source code update. The only thing updated is the one line.
null
null
null
null
null
null
null
null
null
null
417927608 ;6FYE5l`LPX# 4101.13
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Because we are passing by reference we only needed to declare the original array in the main program once. .
7560640 6Z[NVoee1S6 4424.43
04569505 f:H>wAr#<URH 4211.42
528859 ][[79_W?]=:< 724.26
973335820 Si>G7QMp?>e 3207.28
79154675 Y>vfTYwHm0J 3327.47
5554284 6n[^PwZUZlH 1028.66
58773836 28vcgSpwA01 3131.02
95873039 #4XwrN`T9 2598.28
1034703 n#HKk`mTar2Z 1176.75
10192851 X>ATvaR:qT 3857.89
417927608 ;6FYE5l`LPX# 3401.13
143260 s2UgJtSHYFmn 378.68
34729802 rh\<3rmk7Dm< 255.48
277791753 BR2=siCDi 345.75
1014748 PK?KTMjA63e 1196.16
496714922 M1=I`ve;Wjw 501.26
654156 AB`6cvO0ql: 4310.51
898250859 t^D90Nw?Ii 3876.05
971750 [9q_5AuLlJ 135.97
796678134 KwV^03p:WW=< 3453.65
39482807 C5?H?b9UplL 4109.48
401599 MvHL7Yv07bW 4356.96
8321377 Jc:<_ke9B: 930.90
152773 VQ6\[2k:uoj 3265.93
624426519 kralkKKEia3 4858.39
650002 Km2t\R3>3#G 1470.78
004509766 _0S`1qb^V 1332.24
0274647 WDhg3\p]w 3147.50
974502771 Q4GT<_s3D9CK 4464.22
281866 c_1F]#RpV^ 2952.03
381121 rOo?CiA[kwTs 4555.21
1549064 F7^eh=njp\r 430.24
841319 IBe^GTLGv 4050.76
6499423 tW9>r[s_<\ 1418.09
8579740 cdB12UrLU 2905.74
33581232 <os4;WcEqb 2455.32
725175174 nWjIeFLK3E 3118.08
592410029 RqgPT382p2Lk 3863.32
08274516 DDr?^vuNQ 1630.37
808471 Ow:8udlBrYP 2590.05
769854 0`lpWGrMkrG 2643.59
3591827 MmThLS1DdL5 2715.30
9001605 \n;rMknh7C 4074.83
10345766 N>^qBqhk?39J 539.43
504385 j0Rq=li0c^ 253.77
362335041 >^VN5oh?OSR 324.19
5728008 QZ>BZhGEv 4441.67
26102273 1XCWR;W?^b\ 4203.51
3317249 dmjLKbgZ? 1958.44
793249 5J>ApQZAB 1906.46
536461203 CP5U:f5\d[_p 3742.25
030298042 VBtHo909;QM 986.28
6111228 mmPgiDMALt 1348.95
621992 r7UmSJ\9j 1440.22
310072768 B1ccagCH3 4755.56
819894803 IXfcY9PZG1 4399.39
362945795 5LAdX_s^G 3624.28
99929088 `oHijc^J0u 4507.69
821671 s#OV>NYlacV 4125.72
72368663 Mi?wTcZ_#I 2845.24
22692406 uT05^2plu 2530.73
343817 pB;Glu5sVb7P 2168.28
5138360 877<cT4T;t 1562.15
You never write the previous account data into validAccounts. When you run String [] validAccounts = new String[arraySize()]; all of the string instances get set to null and only get changed when you update an account. What you need to do is when you start your program, read the existing text file into that String array and then just change the entries you need to. When you are done, write the String array to the file.
In your main method
String[] validAccounts = new String[arraySize()];
which means you have an array of NULL values, you need to assign the values data here rather than in another method, as when you pass the array you are passing a reference to this array rather than the data itself
so in arrayIndex
validAccounts = acctLine(arraySize()); will put the data in this method and when it returns this data is discarded.
You need to assign the data ONCE then pass this around without writing over it in methods
e.g. in main
String[] validAccounts = new String[arraySize()];
should be
String[] validAccounts = acctLine(arraySize());
You don't need to read it again in arrayIndex or checkID.
So read it once and store it, pass this data to the method and read from this data rather than a new file read
a simple example is this - you'll see the a = new int.... does not change a in original method, but assignment does in doesSomething
public static void main(String[] args) {
int[] a = {1,2,3};
doesNothing(a);
for (int i: a)
System.out.print(i);
doesSomething(a);
for (int i: a)
System.out.print(i);
}
static void doesNothing(int[] a) {
a = new int[]{4,5,6};
}
static void doesSomething(int[] a) {
a[0] = 7;
a[1] = 8;
a[2] = 9;
}
public void two(final BeanForm[] captureddata)
{
for (BeanForm form : captureddata)
{
if (form.getCyclicType() != null)
{
logger.info("The Cyclic Type is"+ form.getCyclicType().value());
}
if (form.getTicketType() != null)
{
logger.info("The Ticket Type is"+ form.getTicketType().value());
}
}
}
The above code works fine, but the output what I can see in the log file is (In case the length of the BeanForm is 2 )
11/Nov/2011 20:15:51 - The Cyclic Type is DTI
11/Nov/2011 20:15:51 - The Ticket Type is MMTS
11/Nov/2011 20:15:51 - The Cyclic Type is DTI
11/Nov/2011 20:15:51 - The Ticket Type is MMTS
I just wanted to know whether it is possible to get the array details also, like to which array this data belongs to
For example
The array[1] Cyclic Type is DTI
The array[2] Cyclic Type is SAG
Just use an external count:
public void two(final BeanForm[] captureddata)
{
int count = 0;
for (BeanForm form : captureddata)
{
if (form.getCyclicType() != null)
{
logger.info(count + " The Cyclic Type is"+ form.getCyclicType().value());
}
if (form.getTicketType() != null)
{
logger.info(count + " The Ticket Type is"+ form.getTicketType().value());
}
count++;
}
}
or as a normal for loop
public void two(final BeanForm[] captureddata)
{
for (int i=0; i<captureddata.length; i++)
{
BeanForm form = capturedata[i];
if (form.getCyclicType() != null)
{
logger.info(i+ " The Cyclic Type is"+ form.getCyclicType().value());
}
if (form.getTicketType() != null)
{
logger.info(i+ " The Ticket Type is"+ form.getTicketType().value());
}
}
}
If you mean the index into the loop - no. You'd need to do that explicitly:
for (int i = 0; i < capturedData.length; i++)
{
BeanForm form = capturedData[i];
// Now you have both form and i.
}
One possible approach is to maintain a counter in the for-loop and you can use the counter along with the array[], something like:
int i=0;
for-each loop
{
//print array[i]
//increment i
}
public void two(final BeanForm[] captureddata)
{
for (i = 0; i < captureddata.length(); i++) {
BeanForm form = captureddata[i]
if (form.getCyclicType() != null)
{
logger.info("The array["+i+"] Cyclic Type is"+ form.getCyclicType().value());
}
if (form.getTicketType() != null)
{
logger.info("The array["+i+"] Ticket Type is"+ form.getTicketType().value());
}
}
}
agree with Matthew's solution
, simply use another counting number and make an increment at the end of the loop.
however, in the log file, do mind whether you wish to start with the "array[0]" or "array[1]"