I have a problem with this code.
the function setListSize is used to set the size of an array via user input as long as it's in the range of [1-50].
The code in the function works when not in a function but when I put the code inside the function I keep getting asked to initialize listA.
Tried to do
int [] listA = null;
but then I got Null Pointer Exception error.
int [] listA;
setListSize(listA);
public static void setListSize (int [] list) {
Scanner reader = new Scanner (System.in);
while (true) {
System.out.print("Enter array size for between [1-50]: ");
int listSize = Integer.parseInt(reader.nextLine());
if (listSize > 50 || listSize < 1) {
System.out.println("Array size must be between [1-50]");
} else {
list = new int [listSize];
break;
}
}
}
What can I do to make this work please?
Thank you for reading
You don't want to pass in the Array (note that it is an Array not a List, they are different things):
public void setListSize () {
You want to set up your member array:
listA = new int [listSize];
Before you were passing an array into the function then overwriting the reference to that array local to the function only. What you need to do is modify the reference to the array in the main object, for which either listA needs to be static (so the static method can access it) or setListSize needs to be non-static.
To make this function generic do this:
public static int[] createList() {
Scanner reader = new Scanner (System.in);
while (true) {
System.out.print("Enter array size for between [1-50]: ");
int listSize = Integer.parseInt(reader.nextLine());
if (listSize > 50 || listSize < 1) {
System.out.println("Array size must be between [1-50]");
} else {
return new int [listSize];
}
}
}
Then in your calling function just do:
listA = createList();
listB = createList();
etc.
You need to make the array static, and NOT pass it in to the function. Passing it in does indeed create the array, but it only exists during the lifetime of the function. This works:
import java.util.Scanner;
public class SetListSize {
private static int [] listA;
public static final void main(String[] igno_red) {
SetListSize.setListSize();
for(int i : listA) {
System.out.println(i);
}
}
public static void setListSize () {
Scanner reader = new Scanner (System.in);
while (true) {
System.out.print("Enter array size for between [1-50]: ");
int listSize = Integer.parseInt(reader.nextLine());
if (listSize > 50 || listSize < 1) {
System.out.println("Array size must be between [1-50]");
} else {
//Reference the array statically
SetListSize.listA = new int [listSize];
break;
}
}
}
}
Output:
[C:\]java SetListSize
Enter array size for between [1-50]: 12
0
0
0
0
0
0
0
0
0
0
0
0
public static int[] setListSize () {
...
return new int[listSize];
The problem is that passing a variable to a function will not be able to assign to that variable; in fact you are passing the value null. And have in the function a local variable list initialized with null.
You should understand what Java does inside.
When you have a method(int[] array)
And you assign something to the variable: array = new int[size], Java creates a new array and points the variable 'array' to the new array.
So if you want to assign a value a field outside the method, you should just do it. Call listA directly and assign a value to it.
Related
Here I am trying to find the max and min number entered into the array so I'm using a min and a max method(not declared yet) but I'm not quite sure how to access my array in these methods as the array userArray and array are not in the scope of the method and can't be accessed. can someone help me out?
package edu.skidmore.cs106.lab07.problem1;
import java.util.Scanner;
public class numberArray {
//Method to take user input
public int[] getUserData() {
System.out.println("How many numbers will you enter?");
Scanner keyboard = new Scanner(System.in);
// Create variable to store user's desired number of values
int totalNumbers = keyboard.nextInt();
// Declare and initialze an array
int[] userArray = new int[totalNumbers];
// Create a loop to ask for values from the user
// Within the loop, store user input in the array
for (int x = 0; x < totalNumbers; ++x) {
System.out.println("Enter number " + x);
int userInput = keyboard.nextInt();
userArray[x] = userInput;
}
return userArray;
}
public int minNumber() {
for (int y : array)
}
public static void main(String[] args) {
numberArray instance = new numberArray();
int array[] = instance.getUserData();
for (int element: array){
System.out.println(element);
}
}
}
public int minNumber(int[] userDataArray) {
// use userDataArray here
}
...
public static void main(String[] args) {
numberArray instance = new numberArray();
int[] userDataArray = instance.getUserData();
int min = instance.minNumber(userDataArray); // pass userDataArray as argument
}
I want to populate an arrayList with random numbers then print array. However I get a huge number of errors when executing the program. Any help would be appreciated.
public class methods {
//variables
int capacity;
private static ArrayList<Double> randomArray;
public methods(int capacity) {
//default constructor to initalize variables and call populateArray to
//populate ArrayList with random numbers
randomArray = new ArrayList<>(capacity);
populateArray();
}
//Method that populates Array with random numbers
private void populateArray()
{
Random rand = new Random();
for (int i=0; i<= capacity; i++)
{
double r = rand.nextInt() % 256;
randomArray.add(i,r);
}
}
//Get Array adds numbers to the string that is called in my main class and printed
public String getArray() {
String result = "";
for (int i=0; i<= capacity; i++)
{
result += String.format("%4d", randomArray);
}
return result;
}
}
//main
public class Benchmarking {
public static void main (String args[]){
Scanner scanner = new Scanner(System.in);
System.out.println("What is the capacity of your Array?");
int capacity = scanner.nextInt();
methods array1 = new methods(capacity);
System.out.println(array1.getArray());
}
After I run the program and enter the capacity it crashes. I just need to create an arrayList populate it with random numbers and print it. Here are the list of Errors I am receiving:
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.util.ArrayList
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747)
at java.util.Formatter.format(Formatter.java:2520)
at java.util.Formatter.format(Formatter.java:2455)
at java.lang.String.format(String.java:2927)
at Benchmarking.methods.getArray(methods.java:68)
at Benchmarking.Benchmarking.main(Benchmarking.java:27)
I think I am doing something fundamentally wrong with my methods.
You cannot pass randomArray (which is a java.util.ArrayList) to String.format().
You probably want to pass randomArray.get(i) instead.
Add this.capacity = capacity; into public methods() { constructor to start with. You are referencing this variable but never setting it.
I have two classes that basically function as the most simplest database, where the user is supposed to enter a string and the program adds it in the array using a class that holds all the methods. Except that when i enter the first name it gives me java.lang.ArrayIndexOutOfBoundsException: 0. I know this means that no memory is being allocated for the array but i thought i did this in my second class where there is a constructer that defines the size of the array. Im not experienced enough with arrays to fix this debug on my own. Much help would be appreicated!
import java.util.*;
public class TestDatabase {
//contant value for data base 'size' of array
public static final int constant = 10;
public static void main (String[] args){
//Database object sets the array size to constant value
Database get = new Database(constant);
//input stream
Scanner in = new Scanner (System.in);
//varaibles for the count and index; prompt
int count = 0;
int index = 0;
System.out.println("Please enter 10 names to add them to the database. Name: " + (count += 1));
//while the count is lower than or equal to 10...
while(count<=10){
//input stream equal to input
String input = in.nextLine();
//if the count equals, stop the loop
if (count == 10)
{
//breaks the loop
break;
}
//prints out the current name
System.out.print(" Name: " + (count +=1));
//adds the input to the array
get.add(index,input);
//increments index by 1
index++;
}
//prints the array
get.print();
}
}
Here is my class with my all my methods:
import java.util.*;
public class Database{
//size of array
public int _size;
//array which has a varaible size
String[] userArray = new String[_size];
//contructer for the array size
public Database(int size){
_size = size;
}
//add method which adds a value to an index of an array
public void add(int index, String name){
//the values of string is placed into some index of the array
userArray[index] = name;
}
//print method which prints the contents of the array
public void print(){
//prints array
System.out.println(Arrays.toString(userArray));
}
//sort method which sorts the array
public void sort(){
//sorts the array
Arrays.sort(userArray);
}
//find method which finds a particular string in any index
public void find(String value){
Arrays.asList(userArray).contains(value);
}
}
Your ArrayList is never instantiated properly, you need to move it into your constructor so when the new operator is called, then the arraylist is created with the size variable that is passed, so something like this:
public Database {
private String[] data;
public Database(int size){
this.data = new String[size];
}
}
With your current code, the array is created before the size is actually given, so it defaults to a size of 0.
userArray init with zero length before your constuctor set _size. Create userArray in constructor.
there next steps performed when you create class:
_size init with 0
userArray init with zero length array
_size init with size value.
Change the code as below
String[] userArray;
public Database(int size){
_size = size;
userArray = new String[_size];
}
Create a class WrapperDemo that includes a function convert2ObjAndStore that convertsan integer into an Integer object and stores the Integer object in a Vector object namedintVector.Store ānā such converted objects in intVector.Iterate the vector and receive theobject as an integer value and display it.Also include a function that swaps one Integerobject with the other and display the swapped value in the calling routine (main function enclosed in a class named WrapperMain)
I tried this but i am getting an error for converting the interger to Integer object
import java.util.*;
class WrapperDemo {
static void Convert(Integer []ob,int n) {
Vector<Integer> store=new Vector<Integer>();
for(int i=0;i<n;i++) {
store.add(ob[i]);
System.out.println(store.get(i));
}
}
}
class WrapperMain {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
int[] x=new int [20];
for(int i=0;i<n;i++) {
x[i]=sc.nextInt();
WrapperDemo.Convert(x,n);
}
}
}
As far as I can see your error is that you declare x as int[] but pass it to a method that is expecting Integer[]. This will not be autoboxed!
EDIT : To make it clearer ...
class WrapperDemo {
static void Convert(Integer []ob,int n) { // <-- type Integer[]
versus
int[] x=new int [20]; // <-- type int[] which is NOT equal to Integer[]
// and will NOT be autoboxed to Integer[]
// ...
WrapperDemo.Convert(x,n); // You give type int[] to a method that is expecting Integer[]
And as a side-note:
for(int i=0;i<n;i++) {
x[i]=sc.nextInt();
WrapperDemo.Convert(x,n); // <- You call the convertion in each iteration.
}
You call the convertion in each iteration of the filling loop. So most of the entries will be null. You might want to change that to:
for(int i=0;i<n;i++) {
x[i]=sc.nextInt();
}
WrapperDemo.Convert(x,n);
public class ApiClass{
//The below method prints only the user entered values
public void printArray(int[] a){
for(int element : a){
//ignore because this is the default value when array is created not user entered
if(element != 0)
{
System.out.print(element+"\t");
}
}
}
}
public class Client{
public static void main(String... args){
ApiClass api = new ApiClass();
int[] input = new int[5];
input[0]= 3;
input[2]= 2;
input[3] = 1;
api.printArray(input);
}
}
This is working fine but failing for the 3,2,0 or 0,0,0 or 3,0,1 any input user enters with zero
default value for primitive int type is 0 so the uninitilized elements in array will hold 0 value,
now if you check if element is not 0 then print and if you give input 3,2,0 then it will skip 0
Better to use List
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(1);
numbers.add(0);
numbers.add(3);
and now iterate the numbers
for(Integer num: numbers){
//print num, no need to check for `0` any more
}
That is not a good approach. If you have three user entries, you should make an array of length three (and not one of length five with two trailing un-used entries). There is no way to distinguish between the "default" 0 and a 0 assigned later.
Another option would be to use an Integer[], where the "default" is null, not 0 (but then you cannot distinguish between the "default" null and a null assigned later).
If you don't know the length of the array in advance, use a List<Integer> instead.
Satya:
If your problem is simply to distuingish the default 0-values from user-entered 0-values, why dont you initialize the array with a value that you know a user can never enter? (You need to make sure that this is the case).
One way is to iterate the array before and initialize, another one is to use
Arrays.fill()
Your for loop is wrong.
Should be
for(int element: a) {
if(element !=0){
System.out.println(element + "\t");
}
}
Your initial implementation never incremented the value of i.
Try with this one:
public void printArray(Integer[] a){
for(Integer element : a){
//Ignore because this is the default value when array is created not user entered
if (element != null) {
System.out.print(element.toString() + "\t");
}
}
}
public class Client{
public static void main(String... args){
ApiClass api = new ApiClass();
Integer[] input = new Integer[5];
input[0]= 3;
input[2]= 2;
input[3] = 1;
api.printArray(input);
}
}