Search for accounts using for loops and if statements - java

I'm having a problem with my program. Currently, I'm making a billing account system.
Basically, I've got a great deal of the system up and running. As a feature, rather than having a user remember their position in an array, a user could carry out actions for their account by entering their account number. So, in other words, they would be prompted to enter an account number and any actions are attributed to that account.
Here is the code I have so far:
intEntry = input.nextInt();
for (count = 0; count <= ACCLIMIT; count++)
{
if (intEntry == NewAccount[count].getAccRefNo() )
{
intSelectedEntry = count;
}//end of if statement
else
{
System.out.println("Invalid ID!");
}//end of else statement
}//end of loop
System.out.println("*******Please enter the amount you wish to deposit*******") ;
valDeposit = getBalanceValidation();
parDepositAmount = Double.valueOf(valDeposit).doubleValue ();
NewAccount[intSelectedEntry].deposit(parDepositAmount);
When I run it, it crashes once I enter the ID number intEntry. It says the error is in the line of the if statement criteria, if that helps.
Please be aware I'm really new to Java, and I'd really appreciate this help explained in a simple way. (Thanks!)
Here is the error message:
Exception in thread "main" java.lang.NullPointerException
at pkgGasAccount.UsingBusinessAccount.main(UsingBusinessAccount.java:106)
Java Result: 1
Line 106 is the first line of the if statement (the criteria)

NewAccount[count] is null.
You should check that NewAccount[count] != null:
if (NewAccount[count]!= null && intEntry == NewAccount[count].getAccRefNo() )
But if you don't expect null values there, I suggest you to check why this happens.

NullPointerException is being thrown, hence I can say that your code is trying to access an array that is not defined or either pointing to a null value (default)
Since there is just one array NewAccount[], hence I would check the declaration of the same.

Related

I need the input of the user to not skip the value 100

I'm currently working on a program for an O Level project where I have chosen to make a class management system. In my method class, I have various methods which control different functions of my program, such as one which collects the name of the students or one which displays a histogram of the student's grades. However, I have discovered a flaw in one of my methods. This is the method that lists the names of the students, one by one (which are saved in an array from a method that is executed before this method) and asks for the students marks. Here, the user is able to enter any number, which is inconvenient, considering that numerical grades normally range from 0-100. I have tried the following code but I have reached a predicament. The code does in fact stop the user from entering a mark over 100, but instead of allowing the user to re-enter a correct mark, it skips over to the next student, leaving the previous student without a mark. The following is said code:
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
marks[g] = Keyboard.readInt();
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
break;
}
}
}
Help would be very much appreciated and thank you in advance :)
Apologies if my English is not very good.
You almost got it - you need to read in your while-loop instead of breaking without reading. Also a do-loop would be more appropriate for not having to set an initial invalid value.
//mark input
public void markin() {
System.out.println("=====================================");
System.out.println("Please enter the mark of the students");
System.out.println("=====================================");
for (int g = 0; g != marks.length; g++) {
System.out.println(names[g]);
do {
System.out.println("Kindly enter a number that is less than 100");
marks[g] = Keyboard.readInt();
} while(marks[g]<0||marks[g]>100);
}
}
Set marks[ g ] to a number that isn't allowed before the loop, like - 1 then check the keyboard input inside of the while loop,
(and set It there every time as long as the while loop isn't stopped,
marks[g] = Keyboard.readInt();
and don't break the loop, as the loop would end anyways when the input is valid
The valid answers has to get into the array sequentially.
Use this simple trick to reset index [g] to the previous value
then you will overwrite the marks[g] value until you get a valid one:
while(marks[g]<0||marks[g]>100){
System.out.println("Kindly enter a number that is less than 100");
g--; // Resetting index to previous value
break;
}

Android Studio If statement with || and && operator

I'm creating an application which updates users on the score of a football match either in real time or as a final result. At least one score must be inputted in order for the TextView to be updated and the relevant score to be displayed. I'm checking that at least 1 of a pair of EditText fields is not empty using the following code:
if(!(et_current.getText().toString().isEmpty())||(!(et_final.getText().toString().isEmpty()))
&& (!(et_current2.getText().toString().isEmpty())||(!(et_final2.getText().toString().isEmpty()))){
if(!(et_final.getText().toString().isEmpty()))
tv_final.setText(et_final.getText().toString());
else
tv_current.setText(et_current.getText().toString());
if(!(et_final2.getText().toString().isEmpty()))
tv_final2.setText(et_final2.getText().toString());
else
tv_current2.setText(et_current2.getText().toString());
}
I want to be able to set the correct TextView so I have another if statement inside the original if statement to see ensure the correct score is being updated.
When I run the code, I do not seem to be getting past the first if statement. Am I using the correct format or is there an better way to complete these checks?
Thanks!
For readabilities sake, get some variables going
boolean currentEmpty = et_current.getText().toString().isEmpty();
boolean current2Empty = et_current2.getText().toString().isEmpty();
boolean finalEmpty = et_final.getText().toString().isEmpty();
boolean final2Empty = et_final2.getText().toString().isEmpty();
And then your code can be much cleaner. Something like
if( (!currentEmpty || !finalEmpty) || (!current2Empty || !final2Empty)) {
if(finalEmpty) {
tv_current.setText(et_current.getText());
}
else {
tv_final.setText(et_final.getText());
}
if(final2Empty) {
tv_current2.setText(et_current2.getText());
}
else {
tv_final2.setText(et_final2.getText());
}
}
I'm not sure if that is completely correct as the requirement is not entirely clear to me, but it should atleast be a good start to follow what's going on.

How to initialize a variable in a do while loop without passing the value until the loop has closed?

I've been writing a program that requires the input of a number between 1 and 4. In order to prevent input of numbers outside the range. However the variable keeps passing to another piece of code and causing the program to fail.
This is the do while loop:
do
{
System.out.println("Please enter a quarter number 1-4: ");
quarter = scanIn.nextInt();
}while((quarter > 5 ) && (quarter < 0));
This is the piece of code that runs the variable:
for (int n = ((quarter * 3)-3); n < (quarter*3); n++)
{
String sum = fmt.format(monthSales[n]);
System.out.printf("Sales for month %d: %s\n", n+1, sum);
}
This is the error that returns when incorrect input is entered:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -6
at lab4.Lab4.main(Lab4.java:57)
I have tried limiting the scope of "quarter" to only within the loop but then the while clause does not function. How can I prevent the variable from passing until the loop has closed?
p.s. This problem is part of an assignment and therefore I must use a do while loop.
I see one thing in your code:
The "do/while" condition seems to be wrong. If your intention is, as I understood, keep asking the user until s/he informs a valid quarter between 1 and 4, the condition should be something like
do {
// ...
} while (quarterNum < 1 || quarterNum > 4);
If I suppose that quarter receives the value of quarterNum in some code in between, the second part seems to be correct and the exception should only occurs if quarter is not a valid value (-1 to be exact). Fixing the do/while condition it will not be possible any more.
I don't see where limiting variable scopes could have anything with your issue. (and I don't even see what you mean by "prevent[ing] the variable from passing until the loop has closed").
I hope I could help you.

Checking the value of a regsitry value in java script

I have a script in my installer that is checking for the existance of a registry key.
Util.showWarningMessage("Here");
Integer xx = (Integer)WinRegistry.getValue(RegistryRoot.HKEY_LOCAL_MACHINE, "Software\\Wow6432Node\\Microsoft\\VisualStudio\\11.0\\VC\\Runtimes\\x86", "Installed");
Util.showWarningMessage("Here 2");
if (xx == 1) {
Util.showWarningMessage("return 1");
}
else{
Util.showWarningMessage("here 1");
}
return true;
The script compiles, but when I run the installer I see the first 2 warning messages but not the ones within the if statement. It also seems that the script is returning false(this is a condition statement to see if a certain component is installed).
When I remove the if statement the final return reached as expected.
I would be grateful if someone could explain what is wrong
Thanks in advance
Probably xx is null and the unboxing throws an exception. Try this:
Util.showWarningMessage("xx = " + xx);
to check the value of xx.

making sure i am doing this problem correctly

this is my first programming course, and i want to make sure i am doing this problem correctly. if you could check over my work it would be greatly appreciated.
Write a method to compute and return the balance for a checking account, given the starting balance and an array of Check objects. You may assume that the Check class already exists and has a method to get the amount from a particular check object called: double getAmount()
The array is not full, and may have gaps in it – make sure you test to see if there is an object there before you try to access it! Make your code work for any length array!
The header for the method is provided for you:
public double computeBalance(double startingBalance, Check[] register) {
int i = 0; // i must be initialized and declared somewhere at least
double total = 0.0;
while ((i >= check.length) && check[i] != null) { // is >= correct? you do i++!
total = (total + getAmount(check[i])); // should you add/compute somewhere
// the given amounts
i++;
}  
System.out.println(total);
}
Forget programming for a second. If I told you "Here's the starting balance in your account." and then handed you a bunch of checks and told you to compute the ending balance, how would you do it? Once you understand that, you can start to work on the programming problem.
Some questions:
Where are you tracking the account balance?
What will happen in your loop if one of the slots in register is empty (i.e. null)?
What is this check variable in your loop? Where is it being declared? Is check really what it should be called?
The function is declared as returning double. What are you returning?
Have you tried compiling your code? What happens?
I understand that you are asking for more than for the solution itself but there are obviously better people to guide you. You can use my example as a reference to what others are explaining to you.
public double computeBalance(double startingBalance, Check[] register) {
// let's start off from the starting balance
double total = startingBalance;
// go over all elements starting from 0
for (int i = 0; i < check.length; i++) {
// make sure you did not encounter null element
if (register[i] != null) {
// increase the total by the amount of the Check
total += register[i].getAmount();
}
}
// and finally return the resulting value
return total;
}
The execution will end when you reach a gap. Use an if-statement inside the loop for the null check instead.
If you could run your code through a compiler (which it sounds like you can't, or at least aren't being encouraged to), it would tell you that it has no idea what i, check, or getAmount are.
A method body that doesn't refer to the method parameters is generally missing something -- especially if the parameter declarations were given by your instructor.
Look again at your loop condition. What is the value of i going to be at the beginning?

Categories