Set a value to an object array - java

public class Jeux {
public static void main(String [] args) {
int nPlayer= 0;
String name;
boolean ok = false;
Player[] groupe = null;
do {
try {
System.out.print("How many player: ");
nPlayer= Clavier.lireInt();
ok = true;
} catch(NumberFormatException e) {
System.out.println("ERROR, enter a number");
}
} while(!ok);
groupe = new Player[nPlayer];
System.out.println(groupe.length);
for(int i=0; i<groupe.length; i++){
try{
System.out.print("Enter the name of the player " + (i + 1));
name = Clavier.lireString();
groupe[i].setNom(name);
} catch(NullPointerException e) {
System.out.println(e.getMessage());
}
}
}
}
why can't I set the name for groupe[i] --> groupe[i].setNom(nom);. I get an exception.
I try to create multiple object without knowing the length of the array.
Maybe there's other possibility with array list and other method but im in school and we didn't see other method for the moment.

You need to instantiate each Player object in addition to instantiating the array which holds them:
name = Clavier.lireString();
groupe[i] = new Player(); // replace this with actual constructor
groupe[i].setNom(name);
Your code is catching a NullPointerException which is precisely what I would expect from your current code.

Related

java - read file and create array

I have to follow a specific format and use scanner. I know there are better methods, but this is a requirement and I am new to java and trying to figure this out. There is a file with customer name, birth date, and other information. I need to count the number of entries in the file, then the file needs to create an array based on the number of file entries and convert the array to a string array. There is more code I need to do, but I am stuck on this part. The try/catch has to be used.
public class Customers {
//////// MAIN ////////
public static void main(String[] args) {
File file = new File("customers.txt");
int numEntries = countCustomers(file);
Person[] customers = readIntoArray(file, numCustomers);
int min = locateBirthdate(customers);
System.out.println("Birthdays this month: " + customer[mon].getBirthdate());
}
//* Counts customers in the file.//
public static int countCustomers(File f) {
int i = 0;
try {
Scanner scan = new Scanner(f);
while (scan.hasNextLine()) {
i++;
scan.nextLine();
}
} catch (Exception e) {
System.out.println("Check filename.");
}
return i;
}
//read data into array and convert into string array
public static Customer[] readIntoArray(File f, int num) {
//num = countCustomers(f);
num = 0;
try {
Scanner input = new Scanner(f);
Customer[] birth = new Customer[num];
String[] strBirth = new String[num];
while (num < countCustomers(f)) {
strBirth[num] = input.nextLine();
birth[num] = makeCustomer(strBirth[num]);
num++;
System.out.println(num);
}
} catch (Exception e) {
System.out.println("Error");
}
return null;
Ok. I have several comments.
First - do you really need 'strBirth' array? Looks like you only write elements but not read from the array.
Second - 'readIntoArray' method always returns null.
Also, you count customers twice, but only one is enough.
Then, do you really need an array with customers? Since you use an array, you need to know exactly the count of customers and therefore you need to scan the file twice. If you use ArrayList, you need to scan file only one time.
I have fixed the issues in the code below.
public class Customers {
//////// MAIN ////////
public static void main(String[] args) {
File file = new File("customers.txt");
Person[] customers = readIntoArray(file, numCustomers);
int numEntries = customers.length;
int min = locateBirthdate(customers);
System.out.println("Birthdays this month: " + customer[mon].getBirthdate());
}
public static Person[] readIntoArray(File f, int num) {
List<Customer> customers = new ArraList<>();
try {
Scanner input = new Scanner(f);
String[] strBirth = new String[num];
while (scan.hasNextLine()) {
customers.add(makeCustomer(scan.nextLine()));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return customers.toArray(Person[]::new);
}

using get and set methods to pass an array between two classes (java)

In my class ReadInput, i read a file containing integers separated by space one by one and put them into inputArray. I then want to use inputArray (and its size) in my class B and i'm attempting to do that with get and set methods but I guess i'm not using them correctly and can't pinpoint my error. Can anyone help? Thanks
import java.io.*;
import java.util.*;
public class ReadInput
{
String INPUT_FILE_NAME = "pages.dat"; // filename
private int [] inputArray;
private int size;
public ReadInput()
{
Scanner fileIn=null; //(Initialization keeps compiler happy)
try { // open file
fileIn = new Scanner(new FileInputStream(INPUT_FILE_NAME));
} catch (FileNotFoundException e) {
System.out.println("Input file "+INPUT_FILE_NAME+" not found. ");
System.exit(1);
}
while (fileIn.hasNextLine())
{
String word = fileIn.next();
size++;
}
inputArray = new int [size];
//test to see that it gives correct size
System.out.println(size);
fileIn.close(); // close file
try { // open file
fileIn = new Scanner(new FileInputStream(INPUT_FILE_NAME));
} catch (FileNotFoundException e) {
System.out.println("Input file "+INPUT_FILE_NAME+" not found. ");
System.exit(1);
}
int i=0;
while (fileIn.hasNextLine())
{
inputArray[i] = fileIn.nextInt();
i++;
}
fileIn.close();
}
public int [] getinputArray()
{
return inputArray;
}
public void setinputArray(int [] inputArray)
{
this.inputArray = inputArray;
}
public int getSize()
{
return size;
}
public void setsize(int size)
{
this.size = size;
}
}
public class B
{
ReadInput in = new ReadInput();
int [] inputs;
public B()
{
}
//this method does not work and gives an error
public void method()
{
System.out.println("in FIFO: " + in.getSize());
for(int j=0; j< inputs.length; j++)
System.out.print(inputs[j] + " ");
}
}
In B's constructor, you need to call in.initializeArrays() and in.getJobs().
Right now, in.getSize() is 0 since that's the default value of ReadInput.size. In addition, in.getInputArray() will be null since that is the default value of ReadInput.inputArray.
Alternatively, you could remove ReadInput.initializeArrays() and ReadInput.getJobs() and simply move the code into a zero-argument constructor for ReadInput, like so:
class ReadInput {
// previous fields: size, inputArray, etc.
public ReadInput() {
// code for setting size and populating inputArray from the file
}
// other methods: getJobs, etc.
}
If you do this, then you should be set. You're already calling ReadInput's constructor through your ReadInput in = new ReadInput(); line, so that line should then populate in's data.
In B's constructor, I don't see you calling
in.initializeArrays
or
setinputArray(int [] inputArray)
anywhere to actually set the array before getting the size.

Cant figure out the null pointer exception

Please help me figure out the null pointer exception. I am not able to understand which variable or object is null.and hoe do i fix it ?
package coll.org;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Scanner;
public class SnakeAndladder1 {
ArrayList<String> name1=new ArrayList<String>(); //an array to store players names
public int throwdice() //to calculate the dice value
{
return (int)(Math.random()*6)+1;
}
public int ladder(int curscore)
{
Hashtable ld = new Hashtable();
ld.put(15,30);
ld.put(45,71);
ld.put(25,62);
ld.put(81,91);
ld.put(9,39);
Object v=ld.get(curscore);
return (int)v;
}
public int snake(int curscore)
{
Hashtable ld = new Hashtable();
ld.put(29,11);
ld.put(81,48);
ld.put(30,6);
ld.put(92,71);
ld.put(58,19);
Object v=ld.get(curscore);
return (int)v;
}
public boolean Game (String name1){
int score=0;
String name;
int v=0;
name=name1.toString();
System.out.println("Click y to roll dice");
Scanner in2=new Scanner(System.in);
String yes=in2.nextLine();
if(yes.equalsIgnoreCase("y"))
{
v=throwdice();
System.out.println("dice value:"+v);
}
score=score+v;
if(score==100)
{
System.out.println("User:"+name+"got"+v+".Winner!!!");
return false;
}
if (score>100)
{
score=score-v;
System.out.println("Current score of"+name+"is"+score);
return true;
}
int s1=ladder(score);
if(s1==score)
{
score=snake(score);
System.out.println("Current score of"+name+"is"+score);
return true;
}
else
{
score=s1;
System.out.println("Current score of"+name+"is"+score);
return true;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int l=0;
boolean flag=true;
System.out.println("Enter the number of players:");
Scanner in=new Scanner(System.in);
int n=in.nextInt();
System.out.println("Enter Players names in order:");
ArrayList<String> name1=new ArrayList<String>(); //an array to store players names
for (int i=0;i<n;i++)
{
Scanner in1=new Scanner(System.in);
String name2=in1.nextLine();
name1.add(name2);
}
SnakeAndladder1 players[];
players = new SnakeAndladder1[n];
while(flag)
{
while(l<n)
{
flag = players[l].Game(name1.get(l)); //----Error occuring here.Its a null pointer
} exception
}
}
}
the stack trace is :
Enter the number of players:
3
Enter Players names in order:
raghav
kishan
sr
Exception in thread "main" java.lang.NullPointerException
at coll.org.SnakeAndladder1.main(SnakeAndladder1.java:107)
The following initializes the array with n nulls:
players = new SnakeAndladder1[n];
To avoid the NPE, you need to create the objects before calling Game() on them.
SnakeAndladder1 players[];
players = new SnakeAndladder1[n];
Add this after above:
for(int i = 0; i < players.length; i++)
{
players[i] = new SnakeAndladder1();
}
This will initialize an object at each element of the array.
The n in your case is a null, since you're getting the value from the user. So it won't create the array as a finite array. They're all nulls.
Try to initialize the number first from the user and then initialize the array.

null pointer exception prob in my coding

I am always getting nullPointerException on line validateCarPlate(nStr) in the main method and on line if(y.matches(rex)). How should i edit to remove the nullPointerException?
import javax.swing.*;
import java.lang.Exception;
public class Q2{
public static void main(String[]args){
boolean loop = true;
while(loop){
String nStr = JOptionPane.showInputDialog("Enter car plate number: ");
try{
validateCarPlate(nStr);
}
catch(InvalidCarPlateException e){
}
}
}
public static void validateCarPlate(String y)throws InvalidCarPlateException{
String rex = "[a-zA-Z]{3}[0-9]{1,4}";
if(y.matches(rex)){
computeCheckDigit(y);
}else{
throw new InvalidCarPlateException();
}
}
public static void computeCheckDigit(String x){
char [] arr = new char[x.length()];
for(int i=0; i<x.length();i++){
arr[i] = x.charAt(i);
}
Looks like
String nStr = JOptionPane.showInputDialog("Enter car plate number: ");
this returns null
change the code like this
public static void main(String[]args){
boolean loop = true;
while(loop){
String nStr = JOptionPane.showInputDialog("Enter car plate number: ");
if(nStr != null)
{
try{
validateCarPlate(nStr);
}
catch(InvalidCarPlateException e){
}
}
}
}
Since, javadocs for JOptionPane#showInputDialog() says Shows a question-message dialog requesting input from the user I think you forgot to give a input.
change you method like that
public static void validateCarPlate(String y)throws InvalidCarPlateException{
String rex = "[a-zA-Z]{3}[0-9]{1,4}";
if(y == null){
// put some message to handle that exception such as
// JOptionPane.showMessageDialog(null,"Some Message");
}else if(y.matches(rex))
computeCheckDigit(y);
}else{
throw new InvalidCarPlateException();
}
}
Also put the code of computeCheckDigit(y); method.
If you click the Cancel button, JOptionPane.showInputDialog will return a null. You can check the return value before passing nStr to validateCarPlate. If a null returned, just drop this nStr and continue the loop (or break it according to your requirement).

Reading a text file line by line and storing an object in the array

The code I've currently created stores the first line of the text file, creates a new Vehicle object and puts it in the array at the first position of null, and stores the same line in every null value in the array. I need it to be able to:
Store the contents of the first line, then store a new Vehicle object in the first place in the array that is null. Then repeat until there are no more lines.
I believe it is a problem with my for loop.
Note - I am required to use Array instead of ArrayList
public void addVehicle(Vehicle[] Honda) throws FileNotFoundException
{
if(canAddVehicle() == true)
{
for(int i = 0; i < vehicles.length; i++)
{
if(vehicles[i] == null)
{
Scanner reader = new Scanner(file);
Honda[i] = new Vehicle();
Honda[i].readRecord(reader);
vehicles[i] = Honda[i];
reader.close();
}
}
System.out.println("Vehicle Added!");
}
else
{
System.out.println("You can not add more than 4 vehicles.");
}
}
Vehicle class:
public void readRecord(Scanner reader)
{
setMake(reader.next());
setModel(reader.next());
setYear(reader.nextInt());
setvin(reader.next());
setValue(reader.nextDouble());
setMilesDriven(reader.nextInt());
setLastOilChange(reader.nextInt());
}
Data file:
Hyundai Sonata 2010 ABC236347NM2N2NW2 18455.34 8765 7567
Chevy Blazer 1998 1234H32343LMN3423 29556.65 38559 38559
//EDIT\
Constraits: I cannot create any new public methods or constructors, and I cannot have any additional class level data
You're looping within the readRecord method, even though that's meant to only store one object, isn't it?
It's possible that you can just remove the while loop - although that then relies on the addVehicle caller knowing how many entries are in the file.
It seems more likely that you should have a method to read everything from a file, populating a List<Vehicle> and returning it. For example:
public List<Vehicle> readVehicles(String file)
{
Scanner reader = new Scanner(file);
List<Vehicle> vehicles = new ArrayList<Vehicle>();
try
{
while (reader.hasNextLine())
{
vehicles.add(Vehicle.readFromScanner(reader));
}
}
finally
{
reader.close();
}
return vehicles;
}
// In vehicle
public static Vehicle readFromScanner(Scanner scanner)
{
String make = reader.next();
String model = reader.next();
int year = reader.nextInt();
String vin = reader.next();
// Don't use double for currency values
BigDecimal value = reader.nextBigDecimal();
int milesDriven = reader.nextInt();
// Shouldn't this be some sort of date type?
int lastOilChange = reader.nextInt();
// I'll assume you have a constructor like this
return new Vehicle(make, model, year, vin, value, milesDriven,
lastOilChange);
}
Found my solution!
public boolean addVehicle(Vehicle[] Honda) throws FileNotFoundException
{
boolean found = false;
int position = 0;
if(canAddVehicle() == true)
{
for(int i = 0; i < vehicles.length && !found; i++)
{
if(vehicles[i] == null)
{
position = i;
found = true;
}
}
Scanner reader = new Scanner(file);
while(reader.hasNext())
{
Honda[position] = new Vehicle();
Honda[position].readRecord(reader);
vehicles[position] = Honda[position];
position++;
}
reader.close();
return true;
}
return false;
}

Categories

Resources