Why does this code throw an exception? - java

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.

Related

Split method creates empty elements in Java Array

I have the following String "Make Me A SandWich"
Someone decided to troll me and replace the spaces with a random number of LOL.
so now the string is "LOLMakeLOLLOLLOLMELOLALOLSandWich"
My goal is to revert this change.
I tried to create a string array with split method but this caused "empty" elements inside of the array that has a value but when I try to log it, it doesn't show anything. It's also not equal to ""
Public class MyClass{
public static void main(String[] args) {
String trollText = "MakeLOLLOLLOLMELOLALOLSandWich";
String[] array = trollText.split("LOL");
if (array[1]=="")System.out.print("it's an empty string");
if (array[1]==" ")System.out.print("it's a space sign");
if (array[1]==null)System.out.print("it's equal to nothing");
if (array[1]==' '+"")System.out.print("I don't know what's that");
else System.out.print(array[1]+"<-- This is an element and it has a value");
}
}
I consider the problem solved if someone tells me what array[1] equals to.
Knowing the value will give me something to compare to when copying the elements into a new array.
When comparing two strings in java, you cannot use == operator which compares object references. You need to use array[1].equals("")
Also, if you simply want to replace all occurrences of a string, you can do following
trollText.replaceAll("LOL", " ")
Here is my solution. skipping empty or " " string and appending notEmpty values to new StringBuilder() and finally print it.
import java.util.Arrays;
public class LOL_problem {
public static void main(String[] args) {
String trollText = "MakeLOLLOLLOLMELOLALOLSandWich";
StringBuilder sb = new StringBuilder();
String[] array = trollText.split("LOL");
//System.out.println(Arrays.toString(array));
for (String str : array) {
if (!str.equals("")) sb.append(str+" ");
}
System.out.println(sb.toString().trim());
}
}
We should use equals(String str) method to check if strings are equals instead of '==' which does object reference check.
To replace all the occurrence, you can use trollText.replaceAll method as below.
public class MyClass{
public static void main(String[] args) {
String trollText = "MakeLOLLOLLOLMELOLALOLSandWich";
String result = trollText.replaceAll("LOL", " ");
System.out.println(result);
}
}
To compare Strings in Java, use:
String.equals("text");
This will return true if the Strings are identical and false if not.

Java arrays - How to go through List and set specific value

First i add new Popotnik in List popotnik depending on how big it is, which is working fine - function prostaMesta. Then i want to go through list popotnik and set popotnik value depending on where it is in for, but value of i will always be 0 everytime it is being called. Also i have break there as i only want to set one popotnik at the time. How should i increment (i) while having some sort of break in there?
Also if(popotnik.get(i) == null){} is not being called, but values inside popotnik are null(s)
private List<Popotnik> popotnik = new ArrayList<Popotnik>();
public void prostaMesta(List<Popotnik> popotnik, int sedez){
stanovanje.setPostle(sedez);
for(int i=0; i<stanovanje.getPostle(); i++){
popotnik.add(new Popotnik());
}
System.out.println(popotnik);
}
public void dodajPotnika(List<Popotnik> popotnik, Popotnik popotnik2){
for(int i=0; i<popotnik.size(); i++){
if(popotnik.get(i) == null){
setPopotnik(popotnik, i);
popotnik.set(i, popotnik2);
break;
}
}
System.out.println(getPopotnik());
}
public void setPopotnik(List<Popotnik> popotnik, int i){
this.popotnik = popotnik;
}
public List<Popotnik> getPopotnik(){
return popotnik;
}
Main class:
List<Popotnik> alPopotnik = new ArrayList<Popotnik>();
if(x.equals("p")){ //inside of a loop when prostaMesta() is being called
potovanje.prostaMesta(alPopotnik, sedez);
}
`if(x.equals("d")){` //inside of a loop when dodajPotnika() is being called
System.out.println("Vnesi ime: ");
String ime = skener.next();
Popotnik popotnik = new Popotnik(ime);
potovanje.dodajPotnika(alPopotnik, popotnik);
}
The if(popotnik.get(i) == null) is never true because objects on the list are not null. You initialize them in the for loop in prostaMesta.
If you have some fields inside the Popotnik class then they are null, but object itself is not.
You would need to do something like popotnik.get(i).getName() == null.
Besides, if you only want to add a number at the end of popotnik's name then it isn't necessary to initialize a list with empty objects.
You could just add objects to list using a different constructor.
For example popotnik.add(new Popotnik("Popotnik"+(popotnik.size()+1))).
It's not pretty but I think initialization like this here is not necessary.

Printing an object array gives null pointer exception

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);
}
}
}

Why am I getting extra stuff when looping through methods?

Okay not sure what is going on. I am using Java Reflection and iterating and inspecting methods of a particular class. Below is the following code I am using:
public void test(){
Class useCases = Car.class;
Method[] methods = useCases.getMethods();
Integer[] numbers = {2, 5};
String[] numberStrings = {"2", "5"};
for(int i=0; i<methods.length; i++){
try {
System.out.print(methods[i].getName());
Method method = useCases.getMethod(methods[i].getName(), new Class[]{String.class, Integer.class});
Object returnV = method.invoke(new Car(), numberStrings[i], numbers[i]);
System.out.print(returnV.toString() + "\n");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Car Class:
public String getNumber(String number, Integer times){
return times == 2 ? number : null;
}
public String getNumber1(String number, Integer times){
return times == 5 ? number : null;
}
It loops through fine printing out the first two methods and the return value fine, but then it continues and prints out a wait() and not sure why and I am getting the following error:
java.lang.NoSuchMethodException: sample.Car.wait(java.lang.String,
java.lang.Integer)
Any help as to why the loop does not end with just printing and returning the values for the only two methods in that Car class.
getMethods returns all public methods available for class, including the ones inherited like wait() toString() which as you see don't accept (String, Integer) arguments, which is why
useCases.getMethod(methods[i].getName(), new Class[]{String.class, Integer.class});
is not able to find wait(String, Integer).
To get only methods declared in Car class use getDeclaredMethods instead.
BTW: instead of
System.out.print(returnV.toString() + "\n");
which will throw NullPointerException on returnV.toString() if returnV will be null use
System.out.println(returnV); // also you don't need to explicitly add `\n`,
// use println will add used by current OS line
// separator for you automatically
Every Class is implicitly extending Object, so you get all methods containing in Object too.

Checking if String Array is filled or empty

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
}

Categories

Resources