public class StudentSchedular {
private Student[] students=new Student[10];
private int counterStudent;
public String addStudent(int rollNumber,String name)
{
students[counterStudent++]=new Student(rollNumber,name);
return "Student added successfully";
}
public void showAllStudents()
{
for(int i=0;i<students.length;i++){
System.out.println(students[i].getRollNumber());
System.out.println(students[i].getName());
}
}
}
I know this is a noob question..but still !
Here I have omitted the other getter/setter parts and other cases where I input the values for rollnumber and name. I am trying to print the object array, but it is giving an null pointer exception. I am inputting only 2 3 values and when I try to print, it gives NPE. I know this is because of null values being in the remaining index positions, I just needed a soln to print the whole object array !
The reason why you get NullPointerException is because of private Student[] students=new Student[10];. It means that you have an Student array which has a fixed size of 10. Default Object values in Java is null. Without adding anything to the array it means you have 10 null objects in students.
If an offset in the students array is not filled yet, you will hit a null value and get an exception, because you try to invoke a method on null.
You can validate it in the loop:
for(int i=0;i<students.length;i++){
if(students[i] instanceof User) {
System.out.println(students[i].getRollNumber());
System.out.println(students[i].getName());
}
}
EDIT: This 'issue' can be avoided by using List<User> instead of User[]. But I can't decide for you if it makes more sense.
I prefer the new For loop (since Java 5).
for(Student student : this.students) {
}
The new for loop works for arrays and all iterables objects, like ArrayList. You'll get only non-null objects.
For answer your question, the best practice is:
Overriding toString() in your Student Object.
#Override
public void String toString(){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(this.rollNumber);
stringBuilder.append(this.name);
return stringBuilder.toString();
}
And at your loop, just do
System.out.println(stundents[i]);
println handles null values as you want, and code turns clean.
Your array has 10 slots. If 3 are given values, then you have 7 slots with null. You will need to either change the type of data structure you are using, or check for nulls when printing. The below code would do a null check and then print which index in the array contains the null value.
public void showAllStudents()
{
for(int i=0;i<students.length;i++)
{
if(students[i] != null) {
System.out.println(students[i].getRollNumber());
System.out.println(students[i].getName());
}
else
{
System.out.println("Array is null at index: " + i);
}
}
}
Related
So I've been trying to figure this out on my own for the past couple of hours but I'm stuck.
I have an array that has a list of a person's name, age, height (in cm). I want to create a method where I use only the person's name as a parameter and searches for the name in the array; if there is no matching name, return null.
Looks like this:
data = new data[50];
data[0] = new data("Dan", 23, 179);
data[1] = new data("David", 20, 180);
data[2] = new data("Sharon", 19, 162);
data[3] = new data("Jessica", 22, 160);
data[4] = new data("Nancy", 25, 164);
...
numberData = 30; // this is the number of people that are in this array so far
This is what I've been trying so far..
public data findData(String name) {
for (int i = 0; i < numberData; i++) {
if (name == data[i]) {
return data[i];
} else {
return null;
}
}
}
I know it isn't right, but I can't seem to find a solution. Any ideas?
array is referencing the Data class with name parameter so we should compare with name parameter not directly with reference of data and for string comparisons always go for equals() method.
public Data findData(String name) {
for (int i = 0; i < numberData; i++) {
if (name.equals(data[i].getName())) {
return data[i];
}
}
return null;
}
Since you want to compare strings you must use the equals method.
Here's an example of how can you use java 8:
public Data findData(Data[] datas, String name) {
return Arrays.stream(datas).filter(data -> data.getName().equals(name)).findAny().orElse(null);
}
In case the loop doesn't execute at least once, you're missing return value.
== compares references, equals compares Strings.
Return null just in case, there is no such element in the array.
Class names should start with a capital letter. Please write Data instead of data.
Code:
public Data findData(String name) {
for (Data d : data) {
if (name.equals(d.getName())) {
return d;
}
}
return null;
}
is what you're looking for. In the original code, null was returned if the 0th element wasn't name.
OK, the above was a quick fix and now some theory:
The pseudo code for linear search in an array:
Loop through all elements in an array. If any matches with the one you're looking for, return it.
If nothing was returned, return the indicating value (null in our case).
Look, in the original code, on the 0th element, you decided whether to return that element or a null. Also, if the loop wasn't run at least once, there was no return statement to hit.
Use equals() to compare strings,
e.g.
if(name.equals(data[i].getName())) {
statements...
}
You should use equals() to compare strings. equals() checks the actual contents of the string, == checks if the object references are equal.
And also, as mentioned above, move return null outside the loop;
You can use following code. Assuming that your data class will have getName() method which returns the name value.
public data findData(String name) {
for (int i = 0; i < numberData; i++) {
if (name.equals(data[i].getName())) {
return data[i];
}
}
return null;
}
move the return null statement out of the loop.
Oh! and yes, use the equals() method instead of ==
I am making an implementation of the ArrayList class from scratch, using just Object[] and the standard functions. I'm trying to make a "size" method, which returns an int that is the size of the Object[] array.
public class MyArraryList{
Object[] Objects = new Object[0];
public int sizeOf(Object[] o)
{
int i = 1;
while(i > 0)
{
if()
}
}
This is what I have so far. In the if statement, I essentially want to check if there's an error along the lines of "index out of range of array". I'm not sure what the syntax for this is. Can someone explain how to do this please? thanks!
You can find the length of an array using
objects.length
It would be possible to write a version of ArrayList where the length of the array is always equal to the size of the list. In this case the size method would just be
public int size() {
return objects.length;
}
Such a list would be very slow. Because arrays are fixed-length, you would have to create a new array on every addition or removal for this to work.
ArrayList does not work like this. An ArrayList has 2 fields; an Object[] and an int called size. The point is that the length of the array is often higher than the size of the list, because there are unused slots at the end of the array. If you do it this way the size method is just
public int size() {
return size;
}
The most useful thing you can do is read the source code for ArrayList to see how it works.
I essentially want to check if there's an error along the lines of "index out of range of array"
You can find the length of an array like this:
int length = 0;
try {
while (true) {
Object o = objects[length];
length++;
}
} catch (ArrayIndexOutOfBoundsException e) {
// ignore
}
However you should not use exceptions in such a way. They should be reserved for genuinely exceptional situations.
you could use a try catch with ArrayIndexOutOfBoundsException e, which was made for these kinds of instances.
http://www.tutorialspoint.com/javaexamples/exception_multiple1.htm
Hope this is not a duplicate because I already looked up some thread incl. this one, but it didn't help me.
My program is reading in some arguments that are optional by the user. They can add a rule to the game but don't have to.
I know that the rule will be containing 5 Numbers. I wanted to save them in a String Array with 5 spots so I can use them later. If the user won't enter a rule there will be a specific rule taken.
String[] rule = new String[5];
//reading in the program arguments and stuff..
//here I want to check whether the rule is taken from the user or not
//don't want to check with a boolean check
if (rule[0].equals("")) {
String[] newRule = "270-90-315-45-90".split("-");
for (int i = 0; i < newRule.length; i++) {
rule[i] = newRule[i];
}
}
Already tried this:
rule[0].equals("")
rule[0].equals(null)
rule[0].equals("null")
rule[0].matches("")
rule[0].matches("null")
rule.length == 0
rule.equals(null)
But I always get a NullPointerException or the if case will be skipped (length == 0)
Hopeyou can help me.
You didn't have tried the obvious?
if (rule[0] == null) {
Insted of using an fixed array, try using an ArrayList and add the values to the list. The ArrrayList-class will adjust the length of the list automaticly.
Example:
ArrayList<String> rules = new ArrayList<>();
if (rules.size() == 0) {
String[] newRule = "270-90-315-45-90".split("-");
//Instead of newRule.length as a comparison, use the
//number of rules with a number. Or use a foreach-loop
//if the number of rules may vary
for (int i = 0; i < 5; i++) {
rules.add(newRule[i]);
}
}
In the example you provide us with, rule[0] contains the value null which you can see yourself by adding the following line of code:
System.out.println(rule[0]==null);
returns true (try it !)
if (rule[0]==null) {
will return true and get inside the for loop if that is what you want.. See the following class which you can compile (using javac myEmpty.java) and run (using java myEmpty):
class myEmpty {
public static void main(String[] args) {
String[] rule = new String[5];
System.out.println(Arrays.toString(rule));
//reading in the program arguments and stuff..
//here I want to check whether the rule is taken from the user or not
//don't want to check with a boolean check
System.out.println(rule[0] == null);
if (rule[0] == null) {
//if ("".equals(rule[0])) {
String[] newRule = "270-90-315-45-90".split("-");
System.out.println(Arrays.toString(newRule));
for (int i = 0; i < newRule.length; i++) {
rule[i] = newRule[i];
System.out.println(rule[i]);
}
}
}
}
YOUR if if (rule[0].equals("")) { fails simply because rule[0] does not contain the value "" which you are checking for ! Keep in mind that "" and null are not the same, and use your if clauses accordingly !
So you want to change indices entered by user only.
The best way to do this would be to initialize the array with default values, then override those specified by the user.
String[] rule = "270-90-315-45-90".split("-");
// Now read "program arguments and stuff"
The NullPointerException I imagine is coming from the fact you have created an array of strings but have not initialized them with any values. They will default to null if you don't give them a value...hence the NPE.
Depending on where you are getting your input you could do something like this;
private static final String[] DEFAULT_RULES = {"270", "90", "315", "45","90" };
private static String[] rules;
public static void main(String[] args){
if(!isValidRule(args)){
// Potentially also check that the args are digits
throw new IllegalArgumentException("Must contain 5 rules");
}
rules = (args.length > 0) ? args : DEFAULT_RULES; // Used brackets on the ternary operator here for readability. Not essential.
...
}
private static boolean isValidRule(String[] rules){
return rules.length > 0 && rules.length != 5;
}
If you are working with some other non-static method thats taking the input, the same applies. You can perform your string split to get an array based on the delimiter you have specified and then do the same thing.
I don't imagine you would want to be passing around a string containing only hyphens if no rules are passed? Which is what you are hinting at by attempting to check if a string is empty after the split is performed.
Also if you want to check if the string contains characters or not use the isEmpty() method. It returns true if the length is 0 else it returns false. This already achieves what you are needlessly attempting.
In each of your tried options
rule[0].equals("")
rule[0].equals(null)
rule[0].equals("null")
rule[0].matches("")
rule[0].matches("null")
rule.length == 0
rule.equals(null)
You already assumed that your element at 0 index is not null , and calling equals() and matches() method on element at 0th index causing NullPointerException
Thrown when an application attempts to use null in a case where an
object is required. These include:
Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.
Instead try like this
if(rule[0] != null){
// Now you can call methods on your `0th` index element
}
ArrayList beds = new ArrayList(49);
public Patient getPatient(int bedNumber) {
if (beds.get(bedNumber) != null) {
return (Patient) beds.get(bedNumber);
}
else {
return null;
}
}
I'm having a problem where I can't seem to get Java to output null in a method.
Say I assign a patient to an item in the beds ArrayList, then try to get the patient at the 11th bed using the getPatient method created above, however you can't as 11 patients haven't been added. How can I make it output null when I try to do this instead of java.lang.IndexOutOfBoundsException.
First off, the compiler has nothing to do with this as it's the JVM that's showing the IndexOutOfBoundsException.
What you should do is check your bedNumber against the size of the ArrayList, not whether the ArrayList item that doesn't exist (is out of bounds) is null. So do simple int math.
i.e.,
if (bedNumber > 0 && bedNumber < beds.size()) {
// do your stuff here
} else {
// myself, I'd throw an exception here, not return null
}
You can just modify the if statement to check the size of the ArrayList.
ArrayList beds = new ArrayList(49);
public Patient getPatient(int bedNumber) {
if (bedNumber < beds.size()) {
return (Patient) beds.get(bedNumber);
}
else {
return null;
}
}
While the advice in the other answers is pretty good, one thing that's overlooked is the constructor on your [raw] ArrayList.
new ArrayList(49) will only set the initial capacity of your ArrayList before it has to resize. That doesn't impact how large the array list is at all; if you haven't added any elements into it, its size will still report 0.
Check your bounds; if they enter in a value that's larger than what you support, then reject it.
// The zeroth location in a list is the first element in it.
if(0 <= bedNumber && bedNumber < beds.size()) {
// Cast necessary since it's a raw ArrayList
// Totally avoidable if you use ArrayList<Patient>
return (Patient) beds.get(bedNumber);
} else {
return null;
}
The point here is that your beds List actually has size of zero. So beds.get(i) whatever the i be would throw that exception as it should. I think you are mistaking the way we define array in Java with defining an ArrayList
import java.util.Scanner;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan=new Scanner(System.in);
int i,j;
int count = 0;
int test=scan.nextInt();
String[] con=new String[test];
while(test>0)
{i=scan.nextInt();
j=scan.nextInt();
for(int k=i;k<=j;k++)
if(prime(k))
//***********the line below where i am getting nullpointer exception
con[count].concat(k+"\n");
test--;count++;}
for( i=0;i<con.length;i++)
System.out.printf("%s\n",con[i]);
}
private static boolean prime(int k) {
// TODO Auto-generated method stub
if(k==2)
return true;
if(k%2==0)
return false;
for(int l=3;l<=Math.sqrt(k);l=l+2)
if(k%l==0)
return false;
return true;
}
}
please somebody help me that how to get rid from this exception.
String[] con=new String[test]; creates a new String array with test elements, and assigns it to con. However, this does not create any String objects at all - you have simply created an array where all elements are null. You must ensure that con[count] actually refers to a String before calling concat() on it; you can either do this by checking if it is null and assigning "" to it before calling concat(), or you can have a separate loop that puts an empty string into each element of con.
By the way: concat() does not modify the String you call it on; it creates a new String and returns it, but you don't do anything with the return value, so it gets thrown away. You should use += instead (which also creates a new String, but it will assign the new String to the array element).
You are not initializing each element of con[]
new String[] gives you an array of null string references. You have to set them to the empty string if you want your code to work.
When you do
String[] con=new String[test];
you create a new String-array of length test. The elements in this array, however, start out being null. Therefore, you cannot call concat on them before initializing them to a string.
This means, you should initialize the string to the empty string, "", before doing calling concat on it.
In addition, strings are immutable, so concat produces a new String, rather than modifying the existing one, so you need to save the result.
This means, you all in all want something like:
while(test>0) {
i=scan.nextInt();
j=scan.nextInt();
con[count] = ""; // Initialize con[count]
for(int k=i;k<=j;k++) {
if(prime(k)) {
con[count] = con[count].concat(k+"\n");
}
}
test--;
count++;
}
Since you'r getting NullPointerException here,
con[count].concat(k+"\n");
it means that the value of con[count] is null and you are trying to call .concat( ) on the null instance.
Here, con[] is not initialized, so it takes null by default. You need to initialize the elements of con[] array i.e say to "" and then try calling the concat method.
It looks like conc[count] is null, if that's where you're getting a NullPointerException.
You should initialize it with a value.