Im a student learning Java and this is part of my program and it is supposed to get the length of a string but the strings are all in an array. I try to run this in eclipse and it says i get an error where it sayslength = name[x].length() can someone let me know if there is a way to fix this
public class GuessName
{
Random random = new Random();
Scanner scan = new Scanner(System.in);
String[] name = new String[10];
int x,length;
char guess1,guess2,guess3;
public void names()
{
name[0] = "MARK";
name[1] = "CHARLIE";
name[2] = "MEG";
name[3] = "KYLE";
name[4] = "JUSTIN";
name[5] = "KATARINA";
name[6] = "JOEL";
name[7] = "KEVIN";
name[8] = "MICHAEL";
name[9] = "JENNA";
name[10] = "GREG";
}
public void start()
{
x = random.nextInt(10);
length = name[x].length();
}
You have an array, as follows:
String[] name = new String[10];
The number between the [] represents the size of the array. In your example, your array has a size of 10 meaning your array has 10 indexes which are [0,9] (because indexes start at 0). The last line of your names() method is:
name[10] = "GREG";
Do you know where I'm getting at?
Also, what does your main method look like? If you're receiving a NullPointerException it probably means you are calling start() before names().
I commented out the parts that was problematic. Also, you are trying to initialize 11 names as opposed to 10. Please note that arrays index starts at 0. I don't know why you have scanner object in there but you can use this block to complete your code.
import java.util.Random;
import java.util.Scanner;
public class GuessName {
// Scanner scan = new Scanner(System.in);
String[] name = new String[10];
int x,length;
char guess1,guess2,guess3;
public GuessName()
{
name[0] = "MARK";
name[1] = "CHARLIE";
name[2] = "MEG";
name[3] = "KYLE";
name[4] = "JUSTIN";
name[5] = "KATARINA";
name[6] = "JOEL";
name[7] = "KEVIN";
name[8] = "MICHAEL";
name[9] = "JENNA";
// name[10] = "GREG";
}
public void start()
{
Random random = new Random();
this.x = random.nextInt(10);
this.length = name[this.x].length();
}
public static void main(String[] args) {
GuessName gn = new GuessName();
gn.start();
System.out.println("The name is: "+gn.name[gn.x]+" and the length is: "+ gn.x);
} }
Related
When I try to use scanner on another class I can't update the array.
private int numClients;
private int[] clients;
These are variables from my class Rooms.
public Hotel(String name, int numRooms, int numClients){
this.name = name;
this.numRooms = numRooms;
this.numClients= numClients;
this.clients = new int[numClients];
}
Of course I added setters and getters:
public String getName() {
return name;
}
public void setNaziv(String name) {
this.name = name;
}
public int getNumRooms() {
return numRooms;
}
public void setNumRooms(int numRooms) {
this.numRooms = numRooms;
}
public int getNumClients() {
return numClients;
}
public void setNumClients(int numClients) {
this.numClients = numClients;
}
When I tried to add it to test it in another class, name and numRooms change. numClients change too but array doesn't update.
Hotel h1 = new Hotel(" ", 0, 0);
String name= sc.nextLine();
h1.setName(name);
int numRooms= sc.nextInt();
h1.setNumRooms(numRooms);
int numClients= sc.nextInt();
h1.numClients(numClients);
h1.show();
This is the show method:
public void show(){
System.out.println("Name: " + this.name);
System.out.println("Rooms: " + this.numRooms);
System.out.println("Number of clients: " + this.numClients);
for(int i = 0; i < clients.length; i++) {
System.out.println(clients[i]);
}
}
Maybe there will be some typing errors I translated the var names to English for question purposes.
Once you have created the array, it's size is fixed. You can test this with a few rows:
int size = 10; // Start with size 10
int[] array = new int[size]; // Array is 10 elements long
System.out.println(size); // Prints 10
System.out.println(array.length); // Also prints 10
size = 1000; // Change size ??
System.out.println(size); // Prints 1000
System.out.println(array.length); // Still prints 10
Output:
10
10
1000
10
You also don't appear to actually set any elements in the array in your code. That would be something like
h1.getClients()[0] = 3;
Edit
When this line in your constructor is exectuted:
this.clients = new int[numClients];
The array is created with the size that numClients has right at that moment. After that, there is no relation between numClients and clients anymore.
You would need to create a new array, copy contents (if you want to preserve it) and reassign clients with the new array in order to change the size.
You can do this with Arrays.copyOf() :
int newLength = 20;
array = Arrays.copyOf(array, newLength);
System.out.println(array.length); // Prints 20!!
The constructor will run once for a single object. So, if you want to add more values in the clients array then a method is a must.
The main Class:
class Main {
public static void main(String[] args) {
Hotel hotel = new Hotel("romeo",5,10);
hotel.addClients(6);
hotel.addClients(10);
hotel.addClients(5);
hotel.show();
}
}
The Hotel Class:
class Hotel{
private int numRooms,numClients;
private String name;
private int clients[] = new int[10];
public Hotel(String name, int numRooms, int numClients){
this.name = name;
this.numRooms = numRooms;
this.numClients= numClients;
this.clients[0] = numClients;
}
The method to add Clients in the clients array:
public void addClients(int numClients){
for(int i = 0; i < clients.length; i++){
if(clients[i] == 0){
clients[i] = numClients;
break;
}
}
}
Show method output:
Name: romeo
Rooms: 5
Number of clients: 10
10
6
10
5
The Total number of clients can be found by summation of the clients array.
To make the array dynamic, the linked list data structure can be applied.
What I did to fix this without updating and making new methods is defining values with scanner and putting it into constructor.
public void test(){
Scanner sc = new Scanner(System.in);
System.out.print("Type in the name of Hotel: ");
String name= sc.nextLine();
System.out.print("Type in number of rooms: ");
int numRooms = sc.nextInt();
System.out.print("Type in the number of clients");
int numClients= sc.nextInt();
Hotel h1 = new Hotel(name, numRooms, numClients);
h1.show();
}
I'm currently taking an Introduction to Java class where we are currently on Arrays topics. We have a class lab where are suppose to create a simple array program consisting a two classes (Passenger.java and Demo.java). The array can be of any sizing (minimum 4) and we can hard code details into few elements.
So I declared the array in the Demo.java with size of 10, and I initialized/hard code 8 of the elements (leaving 2 elements un-initialized) with one of the constructor in Passenger.java. Then using a for-loop and counters I determine the number of elements is not null, and initialize the remaining element with the counter value increase by 1 (e.g. passengers[index++] = new Passenger()).
However, when I tried to call a method after initializing the newly initialized element I got java.lang.NullPointerException error. So I tested by called exact index which is 8 (passengers[8] = new Passenger()) and then calling the method again, it works.
Hence may I know which part of my code is having problem.
Note:
I cannot use ArrayList
I have viewed this initialize all variables but still get NullPointerExceptions error
Passenger Class
import java.util.Scanner;
public class Passenger {
private String title;
private String firstName;
private String lastName;
public Passenger() {
}
public Passenger(String title, String firstName, String lastName) {
this.title = title;
this.firstName = firstName;
this.lastName = lastName;
}
public void enterDetails() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your title: ")
title = keyboard.next();
System.out.print("Enter your first name: ")
firstName = keyboard.next();
System.out.print("Enter your last name: ")
lastName = keyboard.next();
}
}
Demo Class
public class Demo {
public static void main(String[] args) {
Passenger[] passengers = new Passenger[10];
passengers[0] = new Passenger("Mr", "Benjamin", "Parker");
passengers[1] = new Passenger(....);
passengers[2] = new Passenger(....);
passengers[3] = new Passenger(....);
passengers[4] = new Passenger(....);
passengers[5] = new Passenger(....);
passengers[6] = new Passenger(....);
passengers[7] = new Passenger(....);
int index = 0;
for (int i = 0; i < passengers.length; i++) {
if (passengers[i] != null)
index++;
}
passengers[index++] = new Passenger();
passengers[index].enterDetails();
}
}
Actually the problem is with index++ which is post increment which means index in incremented after new Passenger(); is allocated to passengers[8] and become 9
and you are getting passengers[index] which is passengers[9] == null
passengers[index++] = new Passenger();
passengers[index].enterDetails()
either you should use passengers[index] so that index will not be incremented
passengers[index] = new Passenger();
passengers[index].enterDetails()
or passengers[++index] so that the index will be incremented before allocation
passengerspassengers[++index] = new Passenger();
passengers[index].enterDetails()
After loop index value is 8.
passengers[index++] = new Passenger();
After this line executes Passenger Object saved on 8 index and after that index value is 9 because it is post increment. So actually this thing happen.
passengers[8] = new Passenger();
index= 8+1;
And
passengers[9] is null
and you are trying to access passengers[9].enterDetails(). Thats why you are getting Null pointer exception.
passengers[index++] = ...
passengers[index].enterDetails()
You allocate passengers[8] but then call enterDetails on passengers[9] because index was incremented.
passengers[index] = ...
passengers[index].enterDetails()
index++;
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 6 years ago.
Please forgive me as I am new to all this.
My code reads a text file of numbers and names. 3 sets of numbers after each name, each set of 3 gets put into an array. When the array gets sent to another class in the loop, the contents of the array becomes overwritten, I am assuming because it is just referencing the address of the array, not the actual values.
public void readMarksData(String fileName) throws FileNotFoundException
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
int[] marks = new int[3];
scanner.nextLine();
int i = 0;
while( scanner.hasNext() )
{
String studentName = scanner.nextLine();
while(i < 3)
{
try
{
marks[i] = scanner.nextInt();
i++;
}
catch ( InputMismatchException ex )
{
i=0;
}
}
scanner.nextLine();
storeStudentRecord(studentName, marks);
//scanner.nextLine();
i=0;
}
scanner.close();
}
Code for storing values in another class
private void storeStudentRecord(String name, int[] marks)
{
//int[] x = new int[3]
StudentRecord student = new StudentRecord(name, marks);
marksList.add(student);
}
Constructor method in other class
public StudentRecord(String nameInput, int[] marksInput)
{
// initialise instance variables
name = nameInput;
noOfMarks = 0;
marks = marksInput;
}
This has been driving me nuts for hours so any help would be greatly greatly appreciated, thank you.
You could modify the constructor so that it creates a copy of the array and uses it :
public StudentRecord(String nameInput, int[] marksInput)
{
// initialise instance variables
name = nameInput;
noOfMarks = 0;
if(marksInput!=null)
marks = Arrays.copyOf(marksInput, marksInput.length);
else
marks = null;
}
Okay. So this is the last HW assignment of the semester, I am leaving out a big part of the program because this is the only thing I can't seem to fix. I am setting up my FileInputStream and using a for loop to read values into the array as I have done in the past without problems. For some reason I am getting this exception and can't figure it out. I have looked at plenty of other threads around this exception but likewise, cant seem to figure it out. Please halp.
Here is the code, it compiles;
import java.util.*;
import java.io.*;
public class CollinDunn_1_10 {
// Declare constants
static final int MAX_EMPLOY = 30;
static final String TAB = "\t";
static final String NL = "\n";
static final double IRA_INVEST = .08;
static final double FEDERAL_WITH = .18;
static final double STATE_WITH = .045;
static final double SAVINGS = .10;
public static void main (String [] args) throws Exception {
// I/O String references
final String INPUT = "CollinDunn_1_10_Input.txt";
final String OUTPUT = "CollinDunn_1_10_Output.txt";
// Declare variables
// One-dimensional array for storing employee names
String [] names = new String [MAX_EMPLOY];
// Two-dimensional array for storing employee pay data
// [0] hours worked [1] pay rate [2] gross pay [3] net pay
// [4] savings amount [5] IRA amount [6] taxs withheld
double [][] payInfo = new double [MAX_EMPLOY][6];
// Set up I/O
FileInputStream inputDataFile = new FileInputStream(INPUT);
Scanner inputFile = new Scanner(inputDataFile);
FileWriter outputDataFile = new FileWriter(OUTPUT);
PrintWriter outputFile = new PrintWriter(outputDataFile);
// Read data from the file
readData(inputFile, payInfo, names);
// Test printing to see if values are stored - REMOVE
for (int i = 0; i < MAX_EMPLOY; i++) {
System.out.print(names[i] + TAB + payInfo[i][0] + TAB + payInfo[i][1]);
}
} // End main
// Method for reading file data into the file.
// Data is sorted as (number of hours) (pay rate) (name)
public static void readData (Scanner inputFile, double [][] payInfo, String [] names) {
for (int i = 0; i < MAX_EMPLOY; i++) {
payInfo [i][0] = inputFile.nextDouble();
payInfo [i][1] = inputFile.nextDouble();
names [i] = inputFile.nextLine();
} // End For
return;
} // End readData
} // End Class
*The fields on the text file are as so:
(hours) (pay) (name)
50.00 10.60 Light Karen L
52.00 10.80 Fagan Bert Todd
62.00 12.24 Antrim Forrest N*
The Exception and stack trace:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at CollinDunn_1_10.readData(CollinDunn_1_10.java:56)
at CollinDunn_1_10.main(CollinDunn_1_10.java:42)
You're never checking whether there is a value to retrieve before trying to retrieve it (look up Scanner.hasNextDouble). Since your for-loop goes through MAX_EMPLOY iterations, this exception will occur whenever your input file contains less than MAX_EMPLOY lines of data.
You should everytime check if your tables or your file contains right amounts of elements or if they are big enought. Code should look like:
public static void readData (Scanner inputFile, double [][] payInfo, String [] names) {
Integer payInfoLenght = payInfo.lenght;
Integer namesLenght = names.lenght;
if (MAX_EMPLOY > payInfoLenght || MAX_EMPLOY > namesLenght) {
System.out.println("Wrong size of tabels");
} else {
for (int i = 0; i < MAX_EMPLOY; i++) {
if (inputFile.hasNextDouble()) {
payInfo [i][0] = inputFile.nextDouble();
}
if (inputFile.hasNextDouble()) {
payInfo [i][1] = inputFile.nextDouble();
}
if (inputFile.hasNextLine()) {
names [i] = inputFile.nextLine();
}
}
}
}
And you don't need "return;" at the end of this method becouse this method nothing returns. It's "void" method.
So I am relatively new to the programming scene and I am confused as to why my code doesn't work. I am trying to make an arraylist of flowers and then use a random number generator to create a random number of certain flowers, and store them in the array. In my logic, I thought that I created a variable to store the numbers (ex randomRoses) and stored the number in the array so I could easily print out how many of each flower there is by just calling the arraylist and the position. (ex flowerArray[0] would print out 8 Roses) but sadly it does not.
public class Flower
{
private int randomRoses;
private int randomTulips;
private int randomOrchids;
public ArrayList <Integer> flowerArray;
public Flower()
{
r = new Random();
t = new Random();
o = new Random();
int randomRoses = (r.nextInt(10) + 0);
int randomTulips = (t.nextInt(10) + 0);
int randomOrchids = (o.nextInt(10) + 0);
flowerArray = new ArrayList<Integer>
}
public void add2Array ()
{
flowerArray.add(randomRoses); //flowerArray[0] is the # of roses
flowerArray.add(randomTulips); //flowerArray[1] is the # of tulips
flowerArray.add(randomOrchids); //flowerArray[2] is the # of orchids
}
public void printArray()
{
System.out.println(flowerArray[0]);
}
You can use the same random object, no need to create 3 instances of it for the random integer generation,
Random r = new Random();
for (int i = 0; i < 3; i++) {
flowerArray.add(r.nextInt(10));
}
System.out.println(flowerArray);
you can not do flowerArray[0] because you have an arrayList and not an array.
you can instead do: flowerArray.get(0) for getting the integer at pos zero
Here your array list is associated with a class object. When you initialize your array list you need to add your entries to the array list in the constructor itself. So when you say object.printArray() its actually returning you the empty array list, that's why you are getting 0 every time. Try This.
class Flower
{
private int randomRoses;
private int randomTulips;
private int randomOrchids;
public ArrayList<Integer> flowerArray;
public Flower()
{
Random r = new Random();
Random t = new Random();
Random o = new Random();
int randomRoses = (r.nextInt(10));
int randomTulips = (t.nextInt(10));
int randomOrchids = (o.nextInt(10));
System.out.println(randomRoses);
System.out.println(randomTulips);
System.out.println(randomOrchids);
flowerArray = new ArrayList<Integer>();
flowerArray.add(randomRoses); //flowerArray[0] is the # of roses
flowerArray.add(randomTulips); //flowerArray[1] is the # of tulips
flowerArray.add(randomOrchids); //flowerArray[2] is the # of orchids
}
public void printArray()
{
System.out.println(flowerArray.get(0));
}
}
public class Test {
public static void main(String[] args) {
Flower f = new Flower();
f.printArray();
}
}
And in array list you can get elements by using get(index) method.
This will give the output you expect.
public void printArray
{
System.out.println(flowerArray.get(0)+" Roses");
System.out.println(flowerArray.get(1)+" Tulips");
System.out.println(flowerArray.get(2)+" Orchids");
}
Also you missed a semi-colon after the statement defining the arraylist.
Make the correction:
flowerArray=new ArrayList<Integer>;
How did it compile without that semi-colon?
It is not working because your syntax for getting the ith flower is wrong.
You're using a java.util.ArrayList so the correct way to get an object from that ArrayList is by calling the get() method.
System.out.println(flowerArray.get(0));
Hope that helps.