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.
Related
First off here is the code with the appropriate descriptions for each command. (Note: the last line is what gives the code error and what I need help fixing).
What is happening on the last line of the code pertains to my question. how is the 'fullName' variable going to be changed to uppercase when it already has an input inside it. how do I go about replacing it later in the code? Thank you
import java.util.Scanner; // Needed for the Scanner class
public class NumericTypes {
public static void main (String [] args) {
//TASK #2 Create a Scanner object here
//Reading from system.in
Scanner keyboard = new Scanner(System.in);
//prompt user for first name
System.out.println("Enter your first name: ");
//scans the next input as a double
String firstName = keyboard.nextLine();
//prompt user for last name
System.out.println("Enter your last name: ");
//scans the next input as a double
String lastName = keyboard.nextLine();
//concatenate the user's first and last names
String fullName = (firstName + " " + lastName);
//print out the user's full name
System.out.println(fullName);
//task 3 starts here
//get first initial from variable 'fullName'
char firstinitial = fullName.charAt(0);
System.out.println("the first initial is: " + firstinitial);
//use the 'toUpperCase' method to change fullName variable to caps
// and store into the fullName variable
String fullName = fullName.toUpperCase()
}
}
You are trying to create the variable fullName which already exists. Change the variable name to something else.
String upperFullName = fullName.toUpperCase();
or omit the declaration
fullName = fullName.toUpperCase();
If you are getting an error, change
String fullName = fullName.toUpperCase()
to
fullName = fullName.toUpperCase();
First off, you didn't write a semicolon ; at the end of the statement.
Second, you can't declare two variables with the same name, which you were doing here. Removing String from this sentence changes the value of the variable fullName.
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);
I'm trying to write a program that needs to stop when the target of £500 has been met. I have to use a DO WHILE loop to do this.
It needs to record how many donations it receives before it reaches £500, also it needs to record the name of the person with the highest donation given and what the largest donation was.
I cannot get the program to update the name of the person with the highest donation. The code I have so far is below. Please tell me where I am going wrong.
I have a red line coming up under 'namemax' when I try to call it at the end outside of the loop, saying 'not initialized'
enter codeimport java.util.Scanner;
/**
* Created by IntelliJ IDEA.
* Date: 11/02/2015
* Time: 15:45
* UPDATE COMMENT ABOUT PROGRAM HERE
*/
public class DoWhile
{
public static void main(String[] args)
{
Scanner keyboard= new Scanner(System.in);
final double TOTAL=500;
String name,namemax;
double donation, donationTotal=0,currentMax=0;
int howManyDonation=0;
do
{
System.out.println("Please enter your name below");
name = keyboard.next();
System.out.println("");
System.out.println("Please enter the amount you would like to donate below");
donation = keyboard.nextDouble();
howManyDonation++;
donationTotal = donationTotal+donation;
if(donation>currentMax)
{
currentMax=donation;
namemax=name;
}//if
}//doWhile
while(donationTotal!=TOTAL);
System.out.println("The total number of donations is " + howManyDonation);
System.out.println("The largest donation was " + currentMax);
System.out.println("The name of the person with the largest donation is " + namemax);
}//main
}//class
here
Just change this line
String name,namemax;
into this:
String name,namemax = null;
Furthermore, change this
while(donationTotal != TOTAL);
into this:
while(donationTotal < TOTAL);
You have a pretty simple problem here. You are updating namemax inside of an if loop only. That means that as far as the code is concerned, there is a possible situation in which it could never be assigned. In practice, because of what you are doing, that can't actually happen but the compiler doesn't understand that.
To fix it,
change
string name,namemax;
to
string name;
string namemax = "";
That should take care of it.
it gives at least one sutuation where namemax not will be set. So you have to initialize the string.
Simply change
String name,namemax ;
To
String name,namemax = null;
or
String name,namemax = "";
The compiler can't guarantee that you'll actually set the namemax before you exit the loop. You should initialize namemax to the empty string to fix this problem.
I'm doing an assignment for class. For some reason the program completely skips the part where the variable name is supposed to be typed in by the user. I can't think of any reason why it's behaving this way, since the rest of my code that is after the cardType part (which asks for things such as String and int types work fine and in order.
System.out.println("Enter the card information for wallet #" +
(n+1) + ":\n---\n");
System.out.println("Enter your name:");
String name = scan.nextLine();
name = capitalOf(name);
System.out.println("Enter card type");
String cardType = scan.nextLine();
cardType = capitalOf(cardType);
You probably need to consume the end of the last line you read prior to trying to get the user name :
scan.nextLine(); // add this
System.out.println("Enter the card information for wallet #" +
(n+1) + ":\n---\n");
System.out.println("Enter your name:");
String name = scan.nextLine();
name = capitalOf(name);
System.out.println("Enter card type");
String cardType = scan.nextLine();
cardType = capitalOf(cardType);
It is behaving this way because I am quite sure you used the same scanner object to scan for integers/double values before you used it to scan for name.
Having said that does not mean you have to create multiple scanner objects. (You should never do that).
One simple way to over come this problem is by scanning for strings even if you are expecting integers/doubles and cast it back.
Scanner scn = new Scanner(System.in);
int numbers = scn.nextInt(); //If you do this, and it skips the next input
scn.nextLine(); //do this to prevent skipping
//I prefer this way
int numbers = Integer.toString(scn.nextLine());
String str = scn.nextLine(); //No more problems
I am getting this message:
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:454)
at java.lang.Integer.parseInt(Integer.java:527)
at fdc.programming.VendingMachine.InsertMoney(VendingMachine.java:70)
at fdc.programming.VendingMachineDriver.main(VendingMachineDriver.java:30)
Java Result: 1
I had been trying to work out, how to do a validate loop so that only positive integers can be accepted and I gave up for now, but I did not change anything and put everything back as it was before messing around. Now when I try to enter a number it gives the above error but there are no errors in Netbeans that I can use to figure out what is wrong! Please be aware that I have only done one basic module in Java for college ;)
My code is:
public class VendingMachine
{
String sinsertMoney, sinsertMoney2; // Money inserted value for parsing into int
String productName; // Name of product
int insertMoney, insertMoney2; // Money inserted by customer (int = pence)
int price; // Price of products on sale
int changeLeft; // Change left from inserted money after selection
int again; // variable for deciding program repeat
DecimalFormat pence = new DecimalFormat("#p"); // Format display output for pence
public void InsertMoney() {
String soption; // Variable for machine operation
productName = " Nothing";
insertMoney = 0; // Default inserted money initialised to zero
insertMoney2 = 0; // Default additional inserted money initialised to zero
price = 0; // Initialising money variables
// Vending machine welcome dialog
soption = JOptionPane.showInputDialog(
"============================================"
+ "\nWelcome to the College Vending Machine!"
+ "\n============================================"
+ "\n\nOptions: i for insert money, s for select item, q for quit."
+ "\n\n============================================");
if ("q".equals(soption)) { // If user chooses q: quit
JOptionPane.showMessageDialog(null, "Have a Nice Day!");
System.exit(0); // terminate application
}
if ("i".equals(soption)) { // if user chooses i: insert money
JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
insertMoney = Integer.parseInt(sinsertMoney); // Parsing for calculations
}
if ("s".equals(soption)) { // if user chooses s: select item
}
}
I can't see where you've declared sinsertMoney but it looks like you've forgotten to assign the result of your call to JOptionPane.showInputDialog to something, hence why that value is still null when you try to parse it.
Try this:
sinsertMoney = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
insertMoney = Integer.parseInt(sinsertMoney);
You need to get the entered value in sinsertMoney like:
sinsertMoney = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n=============================");
And also implement null check on the sinsertMoney for cancel operation and empty strings.