I am in dire need of assistance please. I have a class called Fields and I wish to create an Array of Field objects but when I execute the code below:
static Field[] theField;
static Scanner userInput = new Scanner(System.in);
static void createFields()
{
System.out.print("Enter the number of fields required: ");
int numFields = userInput.nextInt();
theField = new Field[numFields];
for (int i = 0; i < numFields; i++)
{
System.out.print("Enter a name for field " + (i + 1) + ": ");
String name = userInput.nextLine();
theField[i].setFieldName(name);
}
}
Then I get the following output and error in the console:
Enter the number of fields required: 3
Enter a name for field 1: Exception in thread "main" java.lang.NullPointerException
at TestChart.createFields(TestChart.java:44)
at TestChart.main(TestChart.java:14)
Please can you guys help resolve the error. I have been trying since last night to no avail.
So, while you have an array of Fields, none of the Field objects have been instantiated. Put the line
Field[i] = new Field();
before you call
Field[i].setFieldName();
theField = new Field[numFields] is just creating array but array is empty so theField[i].setFieldName(name); will generate null pointer exception. You need to have the array filled by Field objects.
You've created the Field-array (theField = new Field[numFields];), but you haven't created the individual Fields yet. Let's say you have 3 items, then your array is as follows: theField = { null, null, null } resulting in a NullPointerException.
So, add this:
if(theField[i] == null)
{
theField[i] = new Field();
}
Right before this line in your for-loop:
theField[i].setFieldName(name);
Related
what the program does: The program I'm trying to create takes a name a user inputs, and finds how many characters they type, uses that information to generate a random number that acts as an ID, and then the program stores the name the user inputted earlier and the random number it generated inside of two separate arrays, and then prints out the array.
What i'm trying to do: Instead of using the scanner class in the main, I'm using it in it's own method that method is called personName().
The problem that I am facing: the problem am i facing is when I run the program I have to type the name twice, if I dont it throws me an exception.
the cause of the problem: I know what's causing the problem, I just dont know how to fix it. The problem arise when I call personName() twice in two different methods, but I need to call it twice so i can get the data from it. The first time i called it is in the id() method. I did this so i can get how many characters the name has. The second time i called it when it's in the yourArrays() method. I did this because I needed to store the name inside of an array. I called it twice by using the variable String yourName = personName(); inside the id() method and I called it again using the variable String name = personName(); inside the yourArrays(); method.
what have I tried: I tried to close the scanner but it still just throws the exception since it's still getting called twice, and since it is closed there's no way to get the data anyway.
What answer am I looking for: The answer I want is how do I stop the system from asking the user to input the name twice, or is there a way to get the name the user inputted without calling the method?
the code:
import java.util.*;
public class IdMaker {
public static void main(String[] args) {
System.out.println("Hello welcome to our new system of generating your ID!");
System.out.print("Please enter your name: ");
yourArrays(); //outputs the arrays
}
public static int randomNumber(int a) { //the method that generates the random number
Random rand = new Random();
int ID = rand.nextInt(a)+1000;
return ID;
}
public static String personName() { //the method that gets and stores the user's name
Scanner name = new Scanner(System.in);
String yourName = name.nextLine();
return yourName;
}
public static int id() { //the method that takes the user name, computes the length of the characters of the name to use for the number generator
String yourName = personName(); //personName() called once
int length = yourName.length();
int id = randomNumber(length);
return id;
}
public static void yourArrays() {// the method that takes the ID and the name and stores it into the arrays
String name = personName(); //personName() called twice
int yourId = id();
String[] nameArray = {name};
Integer[] idArray = {yourId};
for(int i = 0; i < nameArray.length; i++) {
System.out.println("the names are: " + nameArray[i] + " ");
}for(int i = 0; i < idArray.length; i++) {
System.out.println("the IDs are: " + idArray[i] + " ");
}
}
}
the output:
this is how it looks when the user have to enter it twice
Hello welcome to our new system of generating your ID!
Please enter your name: chris
chris
the names are: chris
the IDs are: 1001
the output if you dont enter the name twice
Hello welcome to our new system of generating your ID!
Please enter your name: chris
Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Random.java:388)
at IdMaker.randomNumber(IdMaker.java:14)
at IdMaker.id(IdMaker.java:34)
at IdMaker.yourArrays(IdMaker.java:41)
at IdMaker.main(IdMaker.java:7)
Rather than calling personName() again, which will cause the user to be asked for input again, id should accept a name as a parameter, and use that generate an ID:
public static int id(String name) {
int length = name.length();
int id = randomNumber(length);
return id;
}
You can then pass the name returned by yourName to id in the yourArrays method:
public static void yourArrays() {
String name = personName();
int yourId = id(name);
...
First of all, thanks for reading!
I made a class "Sportsman" that is the Superclass of "Footballer".
So I made an array of Sportsman-objects that also contains Footballer objects, no problems here (I have a pretty good idea of how inheritance works).
I can set Footballer-specific variables to the objects in the array, but when I want to print the variables I've just declared to the object i can't call get-methods because the array is a Sportsman-array and not a Footballer-array.
So here is my question: How do i print the Footballer specific variables from a Sportsman Superclass array?
Things to know:
I can't make a separate array for the subclass objects. They must be mixed!
While putting a subclass object in the arrays of superclass objects, I explicitly make it a subclass object. However, I'm not able to use subclass methods on it.
main code:
public class SportApp {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Sportsman[] sportArr = new Sportsman[10];
for(int count=0 ; count < sportArr.length ; count++)
{ System.out.println("Is the sportsman a footballer?");
String answer = input.nextLine();
System.out.println("Last name?");
String lastName = input.nextLine();
System.out.println("name?");
String name = input.nextLine();
switch (answer){
case "yes": System.out.println("Which club does he play in?");
String club = input.nextLine();
System.out.println("At what position?");
String pos = invoer.nextLine();
sportArr[count]=new Footballer(lastName,name,club,pos);
break;
default: System.out.println("What sport?");
String sport = input.nextLine();
sportArr[count]=new Sportsman(lastName,name,sport);
}
}
System.out.println("All sportsmen that don't play football:");
for(int count=0 ; count < sportArr.length ; count++)
{ if(!(sportArr[count] instanceof Footballer))
{ System.out.print("name: ");
sportArr[count].print();} }
System.out.println("All football players sorted by position:");
//Same as previous print, but with added player position and club!
for(int count=0 ; count < sportArr.length ; count++)
{ if(sportArr[count] instanceof Footballer)
{
/*what I've tried:
*System.out.println("front players:");
*if(sportArr[count].getPos()=="front") //the .getPos doesn't work because it wants to invoke it on a Sportsman where getPos doesn't exist
*{ sportArr[count].print();} //as the problem above, it doesn't see the object is also a Footballer so it does the Sportsman print()
*
*I wanted to do a regular sportArr[count].pos to print the Position but even now it doesn't recognise the object as Footballer, so I can't see pos.
*/
}
}}}
You've done a type check with instanceof in the loop, and if it succeeds, you know that you have a Footballer. So, now you have to cast the object to get the correct type:
if(sportArr[count] instanceof Footballer)
{
Footballer fb = (Footballer) sportArr[count];
// Now this should work (note the use of fb, and not using `==` with string literals):
if(fb.getPos().equals("front")) {
// etc..
}
}
newbie here
Is this the way to populate an ArrayList with objects(code below)? In the code below I've managed to read the information in the file of my choice and populate it with words. It appears in this format:
App name: Barcode Scanner
Developer name: WizardTech
Function: Scans bar-codes.
Type: Utility
Cost: 7.0
Popularity: 0
========================================================
I want to be able to get the attributes of the objects and use them like any other variable in the code. Is it possible to do this with the code I have right now?
For example, I've got an attribute named 'Cost' which belongs to the object and I want to get that attribute from the object in the ArrayList and use it for a calculation.
Here's the code:
public class c {
public static void wholeSystem3() {
boolean choice = true;
int input6 = 0;
Shop customerConfig = new Shop(new ArrayList<Customer>());
while (choice == true) {
System.out.println("Proceed to Customer creation by entering 1");
Scanner myScan1 = new Scanner(System.in);
input6 = myScan1.nextInt();
if (input6 == 1) {
System.out.println("Enter your information:");
Scanner myScan0 = new Scanner(System.in);
Customer myCustomer = new Customer();
System.out.println("Please enter your name:");
myCustomer.setCustomerName(myScan0.nextLine());
System.out.println("Please enter your address:");
myCustomer.setAddress(myScan0.nextLine());
System.out.println("Please enter your profession:");
myCustomer.setProfession(myScan0.nextLine());
System.out.println(myCustomer.getCustomerName() + " " + myCustomer.getAddress());
customerConfig.addCustomers(myCustomer);
File CustomerList = new File("CustomerList");
try {
BufferedWriter out;
out = new BufferedWriter(new FileWriter(CustomerList, true));
out.write("Customer name:" + myCustomer.getCustomerName());
out.newLine();
out.write("Customer Address:" + myCustomer.getAddress());
out.newLine();
out.write("Customer Profession:" + myCustomer.getProfession());
out.newLine();
//Close the output
out.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
System.out.println("Would you like to immediately purchase an app?");
input6 = myScan0.nextInt();
if (input6 == 1) {
String appStoreFile = "AppStore"; //"AppStore" Name of file I wish to take objects from to populate ArrayList
String line;
ArrayList testList = new ArrayList();
try {
BufferedReader input = new BufferedReader(new FileReader(appStoreFile));
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
testList.add(line);
}
input.close();
} catch (IOException b) {
System.out.println(b);
}
}
}
}
}
}
When you read the file line by line, you should parse it.
That means to turn it into a number.
Here's a link on how that works:
Convert string to float?
Pass the characters that come after "Cost:" to that method.
It should return a number that you can do calculations with.
Here's a simple program operating on one of your lines:
public class TextParser
{
public static void main(String[] args)
{
String line = "Cost: 7.0";
// this will not work, it tries to parse the whole line
//float number1 = Float.valueOf(line);
// this works and returns 7 as a number
float number2 = Float.valueOf(line.substring(6));
System.out.println("the number is: " + number2);
// you can now do calculations with it:
System.out.println(number2 + 5);
System.out.println(number2 * 12.345);
}
}
In the example, I hard coded the portion of the line that is representing a number. A better way to do this is to use regular expressions to filter out the parts of the String that could be a number. This is a lot more flexible but also a little complex and maybe a bit over the top for the beginning. But definitely look into RegEx, it is very useful.
you havent posted details about shop class but i assume that as there is customerConfig.addCustomers method, similarly there woule be customerConfig.getCustomers which you can use as follows. e.g. for first customer:
customerConfig.getCustomers().get(0).getCost();
As keyser pointed out, you posted too much code. However, from trying to discern from what you are trying to do, you are trying to add objects into your ArrayList, and then retrieve an attribute from a specific object within the ArrayList.
To add an object into the ArrayList, you can add by using the ArrayList's add method:
yourArrayListName.add(Object name);
or
yourArrayListName.add(int index, Object name);
Note that if you use the latter, you will need to keep track of whether the index you are trying to retrieve from is null or not. The former will simply add in order starting from index 0,1,2...
To retrieve the object within the ArrayList, you can use the ArrayList's get method:
yourArrayListName.get(int index).getAttribute(); // getAttribute retrieves the value you want
Note that I used a get method to get the value you wanted. It is bad programming practice to directly retrieve a value from an object. If you really wanted to, however, you can directly use the attribute variable name in place of getAttribute(), assuming it is declared public.
Here is the documentation:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
I'm having a little trouble with a simple code. It is suppose to be a program where people can add Notes that get stored in an array. I know this code is long but hopefully some can help me out.
public class NoteOrganizer {
int action = 0;
public static Note[] myArray;
public static void addNotes(int num)
{
String note;
String date;
for(int z = 0; z <= num; z++)
{
Scanner getLi = new Scanner(System.in);
System.out.println("Please enter a note (max 140 characters): \n");
note = getLi.nextLine();
System.out.println("Please enter a date:\n");
date = getLi.nextLine();
Note test = new Note();
test.id = z;
test.myNote = note;
test.date = date;
myArray[z] = test; // THE ERROR IS IN THIS LINE, NOT THE LINE MENTIONED BEFORE
}
}
public static void main(String[] args)
{
int action = 0;
int y = 0;
Scanner getLi = new Scanner(System.in);
System.out.println("Please press 1 to add notes, 2 to delete notes or 3 to view "
+ "all notes:\n");
action = getLi.nextInt();
if(action == 1)
{
System.out.println("How many notes would you like to add: \n");
int d = getLi.nextInt();
//myArray = new Note[d];
addNotes(d);
//System.out.println(myArray[0].print());
}
else if(action == 3)
{
System.out.println(Arrays.toString(myArray));
}
}
}
The error that I am getting is the
Exception in thread "main" java.lang.NullPointerException
at note.organizer.NoteOrganizer.addNotes(NoteOrganizer.java:46)
at note.organizer.NoteOrganizer.main(NoteOrganizer.java:95)
Java Result: 1
I commented which line the error was in.
Any help is greatly appreciated.
Thanks,
You haven't initalized your Note array. It seems you've commented out that line for some reason:
//myArray = new Note[d];
public static Note[] myArray;
myArray[z] = test;
You did not initialize the array, so it is still null.
Once you know the length you need (seems to be num), you can do
myArray = new Note[num];
before using the array.
(It seems you already had code to that effect, but it is commented out for some reason).
You've never set myArray to anything, so you can't write into it.
You're trying to automatically expand an array by writing to it, but that doesn't work in Java. However, an ArrayList does support writing at the end (but not any further), and reallocates its internal array as neccessary:
ArrayList<Note> myList = new ArrayList<Note>();
Then, instead of
myArray[z] = test;
use
myList.add(test);
(which will automatically append to the end of the List, wherever it is)
then read from the list as
myList.get(index)
You need initialize your array, I suggest use the class ArrayList, that is like a dynamic array.
myArray = new Note[length];
I'm writing a program that creates an object which holds to inputs from the user and stores it in an ArraySortedList. One of the requirements is to check and see if the particular object is already in the list. The trouble I'm having is whenever I input a secound set of information I get an error.
//Global variables at the top
ListInterface <Golfer> golfers = new ArraySortedList < Golfer > (20);
Golfer golfer;
//Function Variables
Scanner add = new Scanner(System.in);
Golfer tempGolfer;
String name = ".";
int score;
while(!name.equals("")) //Continues until you hit enter
{
System.out.print("\nGolfer's name (press Enter to end): ");
name = add.next();
System.out.print("Golfer's score (press Enter to end): ");
score = add.nextInt();
tempGolfer = new Golfer(name,score);
if(this.golfers.contains(tempGolfer))
System.out.println("The list already contains this golfer");
else
{
this.golfers.add(this.golfer);
System.out.println("\nYou added \'Golfer(" + name + "," + score + ")\' to the list!");
}
}
Error Message:
Exception in thread "main" java.lang.NullPointerException
at ArrayUnsortedList.find(ArrayUnsortedList.java:67)
at ArrayUnsortedList.contains(ArrayUnsortedList.java:110)
at GolfApp.addGolfer(GolfApp.java:90)
at GolfApp.mainMenu(GolfApp.java:52)
at GolfApp.main(GolfApp.java:24)
I'm almost sure it's something to do with how the variable is referenced but I'm not really sure how I could fix it, I have a lot of trouble with variable referencing.
Your golfer variable is not initalized.
try with :
this.golfers.add(tempGolfer);
regards.