NullPointerException from array created in a method - java

I'm currently doing a simple university project about the arrays.
In my project I initialize and fill an array by using a method called "setArray", but when the program returns on the main method in which I try to print the array's content, it returns a NullPointerException.
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num[] = null;
String command;
setArray(in, num);
for(int i = 0; i < num.length ; i++)
{
System.out.println(num[i]);
}
}
private static void setArray(Scanner in, int[] num)
{
System.out.println("Type the array size: ");
int dim = in.nextInt();
num = new int[dim];
System.out.println("Size: " + num.length);
System.out.println("Type the numbers' variability: ");
int var = in.nextInt();
int ran;
for(int i = 0; i < num.length ; i++)
{
ran = (int) (Math.random() * var);
num[i] = ran;
System.out.println(num[i]);
}
}

Have a look at this question about whether Java is Pass By Reference
Your code would be better off like this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num[] = null;
String command;
num = setArray(in);
for(int i = 0; i < num.length ; i++)
{
System.out.println(num[i]);
}
}
private static int[] setArray(Scanner in)
{
System.out.println("Type the array size: ");
int dim = in.nextInt();
int[] numToReturn = new int[dim];
System.out.println("Size: " + numToReturn.length);
System.out.println("Type the numbers' variability: ");
int var = in.nextInt();
int ran;
for(int i = 0; i < numToReturn.length ; i++)
{
ran = (int) (Math.random() * var);
numToReturn[i] = ran;
System.out.println(numToReturn[i]);
}
return numToReturn;
}

if you see your code you are declaring a local variable num in your setArray(scanner in,int[] num) method which is not visible in main function nor it is same as that you declared in main function .
The variable array num in the main function is different from that in setArray() function.

Related

how to insert in two dimensional array?

i'am new injava , in this problem i will insert a numbers of strings in a array , but the compiler give me this probleme :
PhoneNumber.java:29: error: incompatible types: String cannot be converted to boolean
while(test[i][j])
^
1 error
public class PhoneNumber{
public static void check_number(String[][] numbers, int n)
{
int i,j;
for(i = 0; i < n; i++)
{
for(j = 0; j < numbers[i].length; j++)
{
if(numbers[i][j] == "4" || numbers[i][j] == "5")
{
System.out.println("Done");
}
}
}
}
public static void main(String[] args)
{
String[][] test = new String[100][100];
Scanner number = new Scanner(System.in);
int n,i,j;
System.out.println("enter the number of numbers");
n = number.nextInt();
for(i = 0 ; i < n; i++)
{
System.out.println("enter the number " + i + 1);
j = 0;
while(test[i][j])
{
test[i][j] = number.nextLine();
j++;
}
}
check_number(test,n);
}
}
Here's the basic approach for a 1D String array with notes included:
import java.util.Scanner;
public class PhoneNumber{
public static void check_number(String[] numbers, int n)
{
for(int i = 0; i < n; i++)
{
System.out.println(numbers[i]);
//the String class method equals is best for comparison:
if(numbers[i].equals("4") || numbers[i].equals("5"))
{
System.out.println("Done");
}
}
}
public static void main(String[] args)
{
Scanner number = new Scanner(System.in);
int n;
System.out.println("enter the number of numbers");
n = number.nextInt();
//clean the scanner buffer after input especially with Int -> Line
number.nextLine();
//size your array after getting user input
String[] test = new String[n];
for(int i = 0 ; i < n; i++)
{
//parenthesis needed to get correct output for i + 1
System.out.println("enter the number " + (i + 1));
test[i] = number.nextLine();
}
check_number(test,n);
}
}

How to solve error: type Integer is not visible

I have created an ArrayList but when I try to access an element in it, I keep getting the error type Integer is not visible. With a Scanner named in, I read input from a file and create an array, then an ArrayList:
int n = in.nextInt();
int[] curr = new int[n];
for (int i = 0; i < n; i++) {
curr[i] = in.nextInt();
}
ArrayList<Integer> order = new ArrayList<>();
for (int item: curr) order.add(item);
However, when I try to access elements in order by creating an int variable called idx and running order.get(idx), I keep getting the above error. How do I fix this?
Thanks,
Satya
You can try with this code:
private static Scanner in = new Scanner(System.in);
public static void main(String args[]) {
System.out.print("array length = ");
int n = in.nextInt();
int[] curr = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("item"+i+" = ");
curr[i] = in.nextInt();
}
ArrayList<Integer> order = new ArrayList<>();
for (int item: curr) order.add(item);
System.out.print("idx = ");
int idx = in.nextInt();
if (idx<order.size()){
System.out.println(order.get(idx));
} else {
System.out.println("idm out of bounds...\n" +
"result with modulo length of list:");
System.out.println(order.get(idx%order.size()));
}
}
You can also try with this code.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] curr = new int[n];
for (int i = 0; i < n; i++) {
curr[i] = in.nextInt();
}
ArrayList<Integer> order = new ArrayList<>();
for (int item : curr)
order.add(item);
int size = order.size();
while (true) {
System.out.print("index= ");
int idx = in.nextInt();
if (idx < size) {
System.out.println(order.get(idx));
break;
}
System.out.println("Error : indexOutofBoundException");
System.out.println("Try again!");
}
}

Why does my method that I am trying to call to inside main not work?

minGap(array); is not being recognized. I don't know what I have done wrong, but I am sure it is a super simple fix. Trying to figure out if it is something to do with the data type being used or if it has something to do with the arrangement of the line " " added. Any hints?
package Lab8;
import java.util.*;
import java.util.Scanner;
public class Question_One {
public static void main(String args[]) {
int length;
Scanner input = new Scanner(System.in); //scanner to input any size array user wants
System.out.println("Please enter the numbers for the array.");
length = input.nextInt();
String[] array = new String[length];
for(int i = 0;i <length;i++) { //counter logic
System.out.println("How many integers are in the array?"+(i+1));
array[i] = input.nextLine();
}
System.out.println("Enter the numbers for the array (individually):");
for(int i = 0;i <length;i++) { //counter logic
System.out.print(array [i]);
array[i] = input.nextLine();
}
input.close();
minGap(array);
}
private static int minGap(int a[], int gapMin) {
int []gap = new int[a.length];
//a
for (int i=0;i<a.length-2;i++) {
if (gapMin>gap[i]) {
gapMin=gap[1];
}
}
return gapMin;
}
}
I believe you wanted a method to find the minimum gap. As such, you should not be passing that into the method. Your logic is also a bit off, you want to take the minimum value after gapMin>gap[i] (not a hardcoded gap[1]). So you could do,
private static int minGap(int a[]) {
int gapMin = Integer.MAX_VALUE;
int[] gap = new int[a.length];
for (int i = 0; i < a.length; i++) {
if (gapMin > gap[i]) {
gapMin = gap[i];
}
}
return gapMin;
}
or (if you're using Java 8+)
private static int minGap(int a[]) {
return Arrays.stream(a).min().getAsInt();
}
Then you need to actually save that value or print it. That is, change
minGap(array);
to (just print it)
System.out.println(minGap(array));
And you need an array of int (not a String[]).
int[] array = new int[length];
for(int i = 0; i < length; i++) {
System.out.printf("Please enter integer %d for the array%n", i + 1);
array[i] = input.nextInt();
}

Insertion Sort - Invalid Method Declaration

I was making a Insertion Sort Program that accepts (Int, Double, String) .. But i can't call a method , it say's invalid method declaration , i can't figure out what the real problem is.....................................
import java.util.*;
import java.util.Scanner;
public class MyInsertionSort
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter anything you want: ");
String insertionSort = in.nextLine();
int num=Integer.parseInt(insertionSort);
String array[] = new String [num];
for (int i = 0; i < array.length; i++)
{
System.out.print("Input the Number at array index "+i+": ");
array[i] = in.nextLine();
}
}
insertionSort(input);
private static void printNumbers(int[] input)
{
for (int i = 0; i < input.length; i++)
{
System.out.print(input[i] + ", ");
}
System.out.println("\n");
}
public static void insertionSort(int array[])
{
int n = array.length;
for (int j = 1; j < n; j++)
{
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) )
{
array [i+1] = array [i]; i--;
}
array[i+1] = key;
printNumbers(array);
}
}
}
You need to call insertionSort(input); in your main method. Just move your method call to 1 line up.
Your declared the method as
public static void insertionSort(int array[])
instead of
public static void insertionSort(int[] array)

Array Guessing game - How to set and get an array?

I am trying to create a guessing game where the user enters a name and is
prompted to pick a number 5 times. I am trying to store the numbers in an array and use set and get methods to print out the attributes of the array. I have achieved this for the name but I am unable to set and get the array.
import java.util.Scanner;
public class StudentStore
{
private String n1;//store's the player's name
//private int [] s10; //stores the player's score
private int i;
private int noOfPlayers = 5;
private int[] s10 = new int[noOfPlayers];
Scanner kboardIn = new Scanner(System.in);
private int index;
int newInt = 0;
public StudentStore(String n1, int [] s10, int i )
{
this.n1 = n1;
this.s10[i] = s10[i];
this.setName(n1);
//this.i = i;
this.setScore(s10,i);
//this.index = index;
// PlayerScore.incNumberScores();
}
public void setScore( int []s10, int i)
{
//takes an integer score, sets variables and checks topScore
this.s10[i] = s10[i];
//this.checkAndSetTopScore();
}
public int [] getScore()
{
return this.s10;
}
public void setName(String n1)
{
this.n1 = n1;
}
public String getName()
{
return this.n1;
}
}
import java.util.Scanner;
public class StudentTester
{
public static void main(String args[])
{
Scanner kboardIn = new Scanner(System.in);
int noOfStudents;
System.out.print("Enter the number of students: ");
noOfStudents = kboardIn.nextInt();
//int[] noOfStudents;
//noOfStudents = new int[100];
StudentStore[] student1 = new StudentStore[noOfStudents];
//int s1 = 0;
int noOfPlayers = 5;
int[] s10 = new int[noOfPlayers];
//s10 = 0;
String n1 = "something";
int i = 0;
for (int index = 0; index < student1.length; index++)
student1[index] = new StudentStore(n1, s10, i);
for (int index = 0; index <= student1.length; index++)
{
System.out.print("What is name of student no "+(index+1)+" ?");
n1 = kboardIn.next();
student1[index].setName(n1);
System.out.print("What is mark for student no "+(index+1)+" ?");
for(i=0; i < noOfPlayers; i++)
{
s10[i] = kboardIn.nextInt();
student1[index].setScore(s10, i);
System.out.println("This is it" + s10[i]);
}
System.out.println(student1[index].getScore( ));
System.out.println(student1[index].getName());
System.out.println(index);
System.out.println(s10[index]);
System.out.println(i);
//System.out.println(s10[]);
}
for (int index = 0; index < student1.length; index++)
System.out.println("\nTotal Mark for " + student1[index].getName()+ " is\t" + student1[index].getScore());
}
}
It seems like you want to know how to loop over arrays. This is how you could achieve it:
String[] strings = {"hi","yo","test"};
for(String s : strings){
System.out.println(s);
}
System.out.println(student1[index].getScore()); you are getting the array, but printing an array will not give stored values in array. You should iterate over the array and print seperatly all values.
Thanks for the reply's. In the program System.out.println(student1[index].getScore()) is not printing a number. It is printing [I#137c6OD. I am not sure how to iterate over the array, but I will look up how to do it. Thanks a lot

Categories

Resources