class Client{
String name;
Client(String name){
this.name=name;
}
Client (){
name=null;
}
}
class Cashier{
LinkedList <Client> cashierclients;
Cashier(LinkedList<Client> cashierclients){
this.cashierclients=cashierclients;
}
Cashier(){
//this.cashierclients=null;
}
}
class test{
public static void main(String args []){
LinkedList<Client> l=new LinkedList<Client>();
//i do some scans here to add the names of persons to the LinkedList l
Cashier [] cashier=new Cashier[numberofcashiers];
for(int i=0;i<numberofcashiers; i++){
cashier[i]=new Cashier();
}
Now I want to add a client to cashier[0] i do this:
cashier[0].cashierclients.addLast(l.get(0));
everything works fine but when I want to print the size of cashier[1] it returns 1 but it should return 0 because I did not add any person to cashier[1]. Any ideas as to what is wrong?
// the error happens here
cashier[1].cashierclients.size();
the program is working now and it shows the error in cashier[1] size that should return 0 instead of 1
import java.util.*;
class Client {
String name;
Client(String name) {
this.name = name;
}
Client() {
name = null;
}
}
class Cashier {
LinkedList<Client> cashierclients;
Cashier(LinkedList<Client> cashierclients) {
this.cashierclients = cashierclients;
}
Cashier() {
//this.cashierclients=null;
}
}
public class test {
public static void main(String args[]) {
LinkedList<Client> l = new LinkedList<Client>();
// i created this LinkedList to solve the nullpointerexception error
LinkedList<Client> empty =new LinkedList<Client>();
Client client1=new Client("Person1");
l.addLast(client1);
Cashier[] cashier = new Cashier[10];
for (int i = 0; i < 10; i++) {
cashier[i] = new Cashier();
}
// i did this to solve the nullpointerexception error
for(int i=0; i<10; i++){
cashier[i].cashierclients=empty;
}
cashier[0].cashierclients.addLast(l.get(0));
System.out.println(cashier[1].cashierclients.size());
//this should return zero
System.out.println(cashier[1].cashierclients.size());
}
}
The following code
for(int i=0; i<10; i++){
cashier[i].cashierclients=empty;
}
makes cashier[i].cashierclients point to the same object
so you can find
System.out.println(cashier[0].cashierclients == cashier[1].cashierclients);
equals to true
i think you shall change empty to new LinkedList()
that will fix the probelm
Related
Trying to get the return function to return the full array, but not able to do it with a for loop or without. Is there any way to get this done?
public class Teams {
String Game;
String Coach;
String Player[];
public void setPlayer(String a[])
{
for (int i = 2; i<10; i++)
{
Player[i-2] = a[i];
}
}
public String getPlayer()
{
for(int i = 0; i < 8; i++)
{
return Player[i];
}
}
}
There's nothing special about arrays - you can return the member as is:
public String[] getPlayer() {
return Player;
}
I have a class that has a constructor of the same name, and I'm trying to set all Index Array to "Open" first.
public static void main(String[] args) {
Calendar info = new Calendar();
}
class Calendar{
private String name;
Calendar[] test= new Calendar[24];
Calendar(){
for(int i = 0; i < test.length; i++){
test[i] = new Calendar();
test[i].name = "Open";
}
}
}
The problem is with the recursive calls of Calendar() constructor. Try the below code which uses another constructor for initialising test[] array:
public static void main(String[] args) {
Calendar info = new Calendar();
}
class Calendar {
private String name;
Calendar[] test= new Calendar[24];
Calendar() {
for(int i = 0; i < this.test.length; i++){
this.test[i] = new Calendar("Open");
}
}
Calendar(String name) {
this.name = name;
}
}
I get a bunch of errors when the code within the "clearPets" method is not commented out. As long as I delete that code, the program will run otherwise.
How can the problems be fixed? I've only recently learned about creating and calling methods, and this is my first time using java.util.Arrays.
The errors in the console are:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Boolean
at java.util.Arrays.fill(Unknown Source)
at rf.uhh.clearPets(uhh.java:34)
at rf.uhh.optionOne(uhh.java:39)
at rf.uhh.main(uhh.java:20)
Here is the code I have:
public class uhh {
public static void main(String[] args){
System.out.println("Select a number");
System.out.println("1");
System.out.println("2");
System.out.print("Choice: ");
Scanner scnr = new Scanner(System.in);
String numberChoice = scnr.nextLine();
if( "1".equals(numberChoice) ) {
System.out.println("You chose 1");
optionOne(new boolean[][] { {false}, {true} });
}
scnr.close();
}
public static boolean[][] adoptPets( int cats, int dogs) {
boolean[][] pets = new boolean[cats][dogs];
return pets ;
}
public static void clearPets( boolean[][]pets) {
Arrays.fill(pets, false);
}
public static void optionOne(boolean[][] center) {
clearPets(center);
boolean[][] dogFaceMan = adoptPets(10, 10);
dogFaceMan[1][1] = true;
}
}
You are passing a 2D array into a method (Arrays.fill) that expects a 1D array.
Try this:
public static void clearPets( boolean[][]pets) {
for(int i = 0; i < pets.length; i++) {
Arrays.fill(pets[i], false);
}
}
I'm getting this error from my code:
Exception in thread "main" java.lang.NullPointerException
at MainClass.main(MainClass.java:20)
Could anyone identify the error, I think it has something to do with initializing my array?
MainClass.java
public class MainClass {
public static void main(String[] args) {
//dummy vars to simulate user input
double price = 2.75;
//declare an array of wincalcs
WinCalc[] staging1;
staging1 = new WinCalc[100];
for (int x=0; x<staging1.length; x++ ) {
staging1[x].price = price;
staging1[x].quantity = x+1;
staging1[x].calcTotal();
}
}
}
WinCalc.java
public class WinCalc {
public double price;
public double quantity;
public double total;
public WinCalc () {
price= 0;
quantity = 0;
total = 0;
}
public void calcTotal() {
this.total = price * quantity;
}
}
You forgot to create the objects
for (int x=0; x<staging1.length; x++ ) {
staging1[x] = new WinCalc();
// ...
}
When you allocate your array, it is initially populated with null entries. In order for it to contain actual objects, you must manually populate will newly allocated objects:
WinCalc[] staging1;
staging1 = new WinCalc[100];
for(int n = 0; n < 100; n ++)
{
stanging1[n] = new WinClac();
}
This is because all objects in java are references which by default point to nowhere.
Update your code with this:
public class MainClass {
public static void main(String[] args) {
//dummy vars to simulate user input
double price = 2.75;
//declare an array of wincalcs
WinCalc[] staging1;
staging1 = new WinCalc[100];
for (int x=0; x<staging1.length; x++ ) {
staging1[x] = new WinCalc();
staging1[x].price = price;
staging1[x].quantity = x+1;
staging1[x].calcTotal();
}
}
Cases that we get NullPointerException are accessing/modifying the field of null object or accessing/modifying the slot of null as if it were an array or taking the length of null as if it were an array.
//Let us have a Person class
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public String toString(){
return "[Name->"+ getName() +" ,Age->"+getAge()+"]";
}
}
//The main class simulate collection of persons using array
import java.util.Arrays;
public class ListOfPersonIn {
public static void arrayManipulation()
{
Person[] persons=new Person[3]; // Array of Person to conatain 3 persons
Person titi=new Person("Titi", 35);
Person beti=new Person("Beti", 10);
Person nati=new Person("nati", 18);
// Display list of persons
for(Person person:persons){
System.out.println(person.toString());
}
//Double array size, copy the old value to the new array and add new persons
Person[]newPersons=copyArraySize(persons);
System.out.println("Loop through a new Array ");
for(Person person: newPersons){
System.out.println(person.toString());
}
}
// Private method to resize array, copy the old array to the new array and add new list of persons
private static Person [] copyArraySize(Person [] persons)
{
Person[]newPersons=Arrays.copyOf(persons, persons.length*2);
// newPersons[persons.length]=new Person("meti", 50); in this case we get NullPointerException because the new array has length 6 but only 4 data is populated the reaming 2 indices are not populated i.e newArray[4] and newArray[5] are null value so it raised NullPointerException. Not to get NullPointerException just populate all array indices with data
for(int i=persons.length;i< newPersons.length;i++){
newPersons[i]=new Person("meti", 50);//duplicate data, array can’t maintain uniqueness like set
}
return newPersons;
}
public static void main(String[] args) {
arrayManipulation();
}
}
In Java, the output of s is 0. I do not understand why and would it be possible to somehow get the correct value of s (1000 here)?
public static void main(String args) {
int s = 0;
List<Integer> list = getList(s);
System.out.println("s = " + s);
}
public static List<Integer> getList(int s) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 1000; i++) {
list.add(i); s++;
}
}
In C# there were out descriptors to indicate that the variable is going to change if I'm not mistaken..
I'm not going to get the list.size() in general!
In Java, all method arguments are passed by value, i.e. copy. So, changes to the copy are not visible to the caller.
To address your second question, you can just use list.size() on the caller side.
I see two ways
1) Make 's' as static variable and move it to class level
2) Create class with getter/setter for list and int and return the object for getList call
public static MyWrapperObj getList(int s) {
......
return wrapperObj
}
class MyWrapperObj
{
private List<Integer>;
private countS;
....
//getter/setters.
}
Java doesn't allow for passing parameters by reference - but you could wrap it in an object like this:
class IntHolder {
private int s;
IntHolder(int s){
this.s = s;
}
public void setS(int s){
this.s = s;
}
public int getS(){
return s;
}
public void increment(){
s++;
}
}
class Test{
public static void main(String[] args) {
IntHolder s = new IntHolder(0);
List<Integer> list = getList(s);
System.out.println("s = " + s.getS());
}
public static List<Integer> getList(IntHolder s) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 1000; i++) {
list.add(i); s.increment();
}
return list;
}
}
In java, arguments passed to methods are passed by value.. you will need to make s a global or instance variable in order to modify it in other methods. This is just the way java works. e.g.
public class Test{
private int s;
public Test(){
s=0;
increment();
//print now will be 1000.
}
private void increment(){
s = 1000;
}
}