Ok this is the code for one section of my switch statement:
case 1: {
System.out.print("Member ID: ");
int key = in.nextInt();
while(members.findItemByKey(key) == -1){
System.out.print("That is an invalid member ID!\nEnter a new one: ");
key = in.nextInt();
}
System.out.print("ISBN: ");
int book = in.nextInt();
while(books.findItemByKey(book) == -1){
System.out.println("That book is not in the system.\nPlease make a new choice: ");
book = in.nextInt();
}
while(stock.findItemByKey(book) != -1){
try {
m = members.get(members.findItemByKey(key));
t = books.get(books.findItemByKey(book));
} catch (Exception e) {
e.printStackTrace();
}
if(m.checkOut(t) == true){
stock.removeItem(t);
}
}
}
Here is the method that is calling:
public int findItemByKey(int key){
for(E e: list)
{
if(e.getKey() == key){
return findItem(e);
}
}
return -1;
}
public int findItem(E item){
if (item == null){
for (int i = 0; i < numElements; i++)
if(list[i]==null)
return i;
}else {
for( int i = 0; i < numElements; i++)
if (item.equals(list[i]))
return i;
}
return -1;
}
Ok, I know there's a lot to look at here, but here's what's happening. When I enter an invalid member ID, it functions properly and keeps asking the user for a new member ID until a valid one is entered. Now when I enter a book, regardless of whether I enter a valid or invalid book, I am getting a null pointer exception thrown by this line:
if(e.getKey() == key)
books, members, and stock are all arraylists defined the same way in my code. I don't understand why I'm having this exception thrown with books and not with the members. The classes for book and member are defined the same way, both have the same getKey method within them.
Maybe there's just too much going on in this question for anyone to be able to really see what's going on. Basically I just can't understand why I get a null pointer exception with the one and not with the other.
Edit: Decided I should post the getKey() method for each class.
public int getKey()
{
return ISBN;
}
Is the one for books
public int getKey()
{
return memberId;
}
Is the one for members.
ISBN is the identifier for books and memberId is the identifier for my members. Everything looks like it's calling the same things, but it errors for books and not for members. Just don't get it.
Either this e is null or the value returned from the statement e.getKey() is null.
You have to make sure that the list doesn't contain a null element and then their keys should also be not-null.
If you want to ignore these values being null, you can do like:
if(e!=null && e.getKey()!=null && e.getKey() == key){
//statements here.
}
Related
// The section below is what raises the error, I am modifying a simple banking application i found online. I am very new to Java, about 3 days I've been dabbling in it, and thought this would be a good little activity to do to get me used to the syntax of the code and methods etc. I have been looking at this problem for about a day now and cant figure out what exactly the problem is. The only thing that would come to mind would be that the showMenu() method is possibly out of scope for the main section im referring it in, however im not to sure.
P.S. If i have missed anything out that could be of us, i apologise as i have never posted on here before!
EDIT - The new error is:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The constructor BankApplication.BankAccount(String, String) is undefined
The method showMenu() is undefined for the type BankApplication.BankAccount
at BankApplication.main(bank.java:9)
public static void main(String[] args)
{
BankAccount obj1 = new BankAccount("Ye Ma", "X Æ A-12");
obj1.showMenu();
}
//The showMenu code
void showMenu()
{
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Bank");
System.out.println("Your Customer ID is: " + cID);
System.out.println("");
System.out.println("1. To view you Bank Balance.");
System.out.println("2. To make a deposit.");
System.out.println("3. To make a withdrawel.");
System.out.println("4. To view your previous transaction.");
System.out.println("5. To exit.");
do
{
System.out.println("----------------------------------------------------------------------");
System.out.println(" Choose an option ");
System.out.println("----------------------------------------------------------------------");
System.out.println("");
option = sc.nextInt();
if(option == 1)
{
System.out.println("----------------------------------------------------------------------");
System.out.println(" Your bank balance is: " + balance);
System.out.println("----------------------------------------------------------------------");
break;
}
else if(option == 2)
{
System.out.println("----------------------------------------------------------------------");
System.out.println("How much would you like to deposit?");
System.out.println("----------------------------------------------------------------------");
int amount = sc.nextInt();
deposit(amount);
break;
}
else if(option == 3)
{
System.out.println("----------------------------------------");
System.out.println(" How much would you like to withdraw?: ");
System.out.println("----------------------------------------------------------------------");
int amount = sc.nextInt();
withdraw(amount);
break;
}
else if(option == 4)
{
System.out.println("----------------------------------------------------------------------");
System.out.println("Your previous transaction was: " + getPreviousTransaction(amount));
System.out.println("----------------------------------------------------------------------");
System.out.println("");
}
else if(option == 5)
{
System.out.println("**********************************");
System.out.println(" END OF APPLICATION ");
System.out.println("**********************************");
}
else
{
System.out.println("Invalid option, please choose a valid option.");
}
}while(option != 5);
i think you are trying to call showMenu() which is not available in BankAccount class.
Am relatively new to java so I have no idea what the problem is. In my getter settings of this class, I'm trying to evaluate if the input is of integer 1, 2 or 3, then it will return one of the previously saved setters described here. I used the same conditional statements in the setter, but the getter tells me that my method needs to return type int. What am I doing wrong? Or should I be doing this a completely different way? lol.
public class AssignmentMarks {
private String courseName;
private int assignment1 = 0, assignment2 = 0, assignment3 = 0;
public AssignmentMarks(String name, int mark1, int mark2, int mark3){
//create constructor to use variables.
this.courseName = name;
this.assignment1 = mark1;
this.assignment2 = mark2;
this.assignment3 = mark3;
}
public void setMark(int assignmentNumber, int mark) {
//assign value of the assignments
if(assignmentNumber == 1) {
mark = this.assignment1;
}else if(assignmentNumber == 2) {
mark = this.assignment2;
}else if(assignmentNumber == 3){
mark = this.assignment3;
}
}
public int getMark(int assignmentNum) {
if(assignmentNum == 1) {
return assignment1;
}else if (assignmentNum == 2) {
return assignment2;
} else if (assignmentNum == 3) {
return assignment3;
}
}
}
public int getMark(int assignmentNum) {
if(assignmentNum == 1) {
return assignment1;
}else if (assignmentNum == 2) {
return assignment2;
} else if (assignmentNum == 3) {
return assignment3;
}
// in another case
throw new Exception("Assignment must be 1, 2 or 3);
}
for setter
public void setMark(int assignmentNumber, int mark) {
//assign value of the assignments
if(assignmentNumber == 1) {
// BAD mark = this.assignment1; don't set parameter is useless
this.assignment1=mark;
}else if(assignmentNumber == 2) {
// BAD mark = this.assignment2;
this.assignment2=mark;
}else if(assignmentNumber == 3){
// BAD mark = this.assignment3;
this.assignment3=mark;
}
// in another case
throw new Exception("Assignment must be 1, 2 or 3");
}
I don't remember if you must import Exception for throwing them.
if yes put import java.lang.Exception on top of your code.
your logic can be improved using arrays, but let's walk, and after you will running...
I have this code here, to see if the items in both lists are identical:
for (final car in this.cars) {
bool found = false;
for (final car2 in garage2.cars) {
if (car2.id == car.id) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
(I previously check if the 2 list lengths are equal). Is there a way to rewrite that so that I don't have O(n2) complexity?
As an option you can override quals and hashcode methods for class Car
something like this
class Car {
int id;
// other fields
#override
bool operator ==(Object o) => o is Car && id == o.id;
#override
int get hashCode => id.hashCode;
}
and then you can use the native method listEquals, which compares for deep equality.
import 'package:flutter/foundation.dart';
bool isEqual = listEquals<Car>(cars, garage2.cars);
Here is the method I have defined that is supposed to accept a String as input and should return the number of times the char 'e' occurs as an int:
public int count_e(String input){
int count = 0;
for (int i = 0;i<input.length();i++){
char e = 'e';
if (input.charAt(i)==e){
count=count+1;
i++;
return count;
}
else{
count=count+1;
i++;
}
}
return count;
}
}
I am trying to write a JUnit test to see if I can input a string into the method and return the correct number of e's. Below is my test, and at the moment I keep getting an error saying that my method count_e is undefined for type String.
Can someone tell me why it is coming up as undefined?
#Test
public void testCount_e() {
String input= "Isabelle";
int expected= 2;
int actual=input.count_e();
assertTrue("There are this many e's in the String.",expected==actual);
}
}
You failed to pass anything to your count_e method!
How about something like:
#Test
public void testCount_e() {
String input = "Isabelle";
int expected = 2;
int actual = count_e(input);
Assert.assertEqual("There are this many e's in the String.", expected, actual);
}
For a unit test, you could probably shorten it to:
#Test
public void testCount_e() {
Assert.assertEqual("There are this many e's in the String.", count_e("Isabelle"), 2);
}
My website went down for a few days, therefore I am trying to produce some error handling while the MVC app doesnt have access to certain resources so if something doesnt become unavailable again the WHOLE THING doesnt have to go down.
At the moment a controller is trying to access viewbag.moreNewProducts that isnt available.
public ActionResult Index(string search)
{
string[] newProductLines = this.getMoreNewProducts();
string[] newNews = this.getMoreNews();
string[] newPromotions = this.getMorePromotions();
string[] fewerProductLines = this.getLessNewProducts(newProductLines);
ViewBag.moreNewProducts = newProductLines;
ViewBag.moreNews = newNews;
ViewBag.morePromotions = newPromotions;
ViewBag.lessNewProducts = fewerProductLines;
bool disableShowMore = false;
This is where I run into an error: " foreach (string line in newProductLines)"
public string[] getLessNewProducts(string[] newProductLines)
{
int charCount = 0;
int arrayCount = 0;
string[] displayProductLines = new string[6];
bool continueWriting;
if (newProductLines == null)
{
foreach (string line in newProductLines)
{
continueWriting = false;
for (int i = 0; charCount < 250 && i < line.Length && arrayCount < 5; i++)
{
string index = newProductLines[arrayCount].Substring(i, 1);
displayProductLines[arrayCount] += index;
charCount++;
continueWriting = true;
}
if (continueWriting == true)
{
arrayCount++;
}
}
string[] LessNewProducts = new string[arrayCount];
for (int d = 0; d < arrayCount; d++)
{
LessNewProducts[d] = displayProductLines[d];
}
return LessNewProducts;
}
else
{
return null;
}
}
how do I get around an if else statement so the whole thing doesnt have to crash?
Two things.
Your if (newProductLines == null) statement has the wrong condition on it. I don't believe that you want to enter that if newProductLines is null. You can inverse this condition to get the desired result(if (newProductLines != null)).
If you run into another situation later where you need to catch an error, you can always use the try-catch block to catch exceptions that you are expecting.
try
{
//code that could cause the error here
}
catch(NullReferenceException nullRefExcep)
{
//what you want it to do if the null reference exception occurs
}
if (newProductLines == null)
should be replaced with if (newProductLines != null) so you don't have to handle the code with newProductLines as null. Basically, with this condition you will always have the NullReferenceException unless you manage your exception with a try catch block.
The real question to ask yourself is:
Why would newProductLines be null?
Presumably getMoreNewProducts() found a situation where it thought it would be appropriate to return a null value.
If this is happening because the system has an error that would make your page meaningless, then you may just want to change getMoreNewProducts() so that it throws an exception when that error state occurs. Typically it's safest and easiest to debug programs that fail as soon as they run into an unexpected situation.
If this is happening because there are no new products, then you should just return an empty collection, rather than null. All your code should work just fine after that, without the need for an if/else statement: it will return an empty array for LessNewProducts, which is probably correct.
However, let's assume that there's a situation that you're anticipating will occur from time to time, which will make it impossible for you to retrieve newProductLines at that time, but which you would like the system to handle gracefully otherwise. You could just use null to indicate that the value isn't there, but it's really hard to know which variables might be null and which never should be. It may be wiser to use an optional type to represent that getMoreNewProducts() might not return anything at all, so you can force any consuming code to recognize this possibility and figure out how to deal with it before the project will even compile:
public ActionResult Index(string search)
{
Maybe<string[]> newProductLines = this.getMoreNewProducts();
string[] newNews = this.getMoreNews();
string[] newPromotions = this.getMorePromotions();
Maybe<string[]> fewerProductLines = newProductLines.Select(this.getLessNewProducts);
Disclaimer: I am the author of the Maybe<> class referenced above.
Here are some additional improvements I'd suggest:
Don't use ViewBag. Instead, create a strongly-typed ViewModel so that you can catch errors in your code at compile-time more often:
var viewModel = new ReportModel {
newProductLines = this.getMoreNewProducts(),
newNews = this.getMoreNews(),
...
};
...
return View(viewModel);
Learn to use LINQ. It will simplify a lot of your very complicated code. For example, instead of:
string[] LessNewProducts = new string[arrayCount];
for (int d = 0; d < arrayCount; d++)
{
LessNewProducts[d] = displayProductLines[d];
}
return LessNewProducts;
... you can say:
string[] LessNewProducts = displayProductLines.Take(arrayCount).ToArray();
In fact, I think your entire getLessNewProducts() method can be replaced with this:
return newProductLines
.Where(line => line.Length > 0)
.Select(line => line.Substring(0, Math.Min(line.Length, 250)))
.Take(5);