Displaying first letter from user input - java

For example, I have a list of user input that are randomized. The user input can range between 1-10. The user input are then enqueued into a queue and dequeue to display the list of user input.
However, I want to use the user input to display the first letter of each user input. I tried creating a new variable called name1 to store the user input but it returns an error due to the name1 variable being null.
for(int i =1;i<=value ;i++){
System.out.println("Enter name #" + i+":");
String name = input.next();
String name1 = name;
myQueue.enqueue(name);
}
System.out.println("List of names: ");
for(int j=1; j <=value; j++){
System.out.println(j+". " +(myQueue.dequeue()));
}
System.out.println("Statistics:");
char firstletter = name1.charAt(0); //error: value is null
System.out.println(firstletter);

Hope this will help you
import java.util.LinkedList;
import java.util.Scanner;
class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public boolean hasItems() {
return !list.isEmpty();
}
public int size() {
return list.size();
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasItems())
list.addLast(q.dequeue());
}
}
public class myQueue {
public static void main(String[] args) {
GenQueue<Employee> empList;
empList = new GenQueue<Employee>();
GenQueue<HourlyEmployee> hList;
hList = new GenQueue<HourlyEmployee>();
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
for(int i =1;i<=n ;i++){
System.out.println("Enter a name: ");
String name = reader.next();
hList.enqueue(new HourlyEmployee(name, name));
empList.addItems(hList);
}
System.out.println("The employees' names are:");
while (empList.hasItems()) {
Employee emp = empList.dequeue();
//System.out.println(emp.firstName + " " + emp.lastName);
char firstletter = emp.firstName.charAt(1); //error: value is null
System.out.println(firstletter);
}
}
}
class Employee {
public String lastName;
public String firstName;
public Employee() {
}
public Employee(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyEmployee extends Employee {
public double hourlyRate;
public HourlyEmployee(String last, String first) {
super(last, first);
}
}

name1= name;
must be outside of the loop

I think what you did here is declared name1 outside the loop and then redeclared it inside the loop again. Remove the declaration inside the loop and write name1 = name instead.

I hope it helps you:
for(int i = 1; i <= value; i++)
{
System.out.println("Enter name #" + i + ":");
myQueue.enqueue(input.next());
}
System.out.println("List of names: ");
for(int j = 1; j <= value; j++)
{
String name = (String) myQueue.dequeue(); //pop element
System.out.println(j + ". " + name);
myQueue.enqueue(name);
}
System.out.println("Statistics: ");
for(int j = 1; j <= value; j++)
{
String name = (String) myQueue.dequeue();
System.out.println(name.charAt(0));
}

Related

Linear and Binary search in an array of objects in java

I'm creating an array of objects where the search should be by Linear method and Binary method.
The issue is how to traverse the array with the appropriate data type and compare.
public class FoodMain {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
Food[] foodlist = new Food[3];
//Initialising food objects array
for (int i = 0; i < foodlist.length; i++) {
foodlist[i] = new Food(Food.getId(), Food.getDescription(), Food.getIngredients(), Food.getSellingPrice());
}
FoodMain foodObj = new FoodMain();
foodObj.show(foodlist);
System.out.print("Enter the search value: ");
int value = sc.nextInt();
for(int j=0; j < foodlist.length; j++) {
// Error on line Incompatible operand types Food and int
if(foodlist[j] == value) {
System.out.println("The value " + value + " is at index " + j);
break;
}
else {
System.out.println("Value not in array!!!");
break;
}
}
}
screenshot of object array to be searched
Array Objects
Here is the code for Food class
package foodObjectArray;
import java.util.Scanner;
public class Food {
static Scanner sc = new Scanner(System.in);
public int id;
public String description;
public String ingredients;
public double sellingPrice;
// Food Class constructor
public Food(int id, String description, String ingredients, double sellingPrice) {
super();
this.id = id;
this.description = description;
this.ingredients = ingredients;
this.sellingPrice = sellingPrice;
}
public static int getId() {
System.out.println("Input food ID");
return sc.nextInt();
}
public static String getDescription() {
System.out.println("Input food description");
return sc.next();
}
public static String getIngredients() {
System.out.println("Enter the Ingredients");
return sc.next();
}
public static double getSellingPrice() {
System.out.println("Input food Price");
return sc.nextDouble();
}
hope that this might help in my explanation
Let's ignore all of the other problems, and just focus on your linear search. Let's assume you are searching by id.
for(int j=0; j < foodlist.length; j++) {
if(foodlist[j].id == value) {
System.out.println("The value " + value + " is at index " + j);
break;
}
else {
System.out.println("Value not in array!!!");
break;
}
}
}
The else branch will break the loop if the first item is not a match. It's not going to search the entire array. It's really is just looking at the first item in the array.
You need to remove the else branch and use a flag (boolean) or some other variable to indicate found.
int foundIndex = -1; //-1 means not found.
for(int j=0; j < foodlist.length; j++) {
if(foodlist[j].id == value) {
foundIdex = j;
break;
}
}
if (indexFound > -1)
System.out.println("Found at " + indexFound);
else
System.out.println("Not found.");
There's at least a couple of errors here.
Firstly don't you want if(foodlist[j].id == value) {? The will relieve the incompatible operands. You need to specify the field you're trying to match.
The style police will hate your code and demand you define getters and setters. But you don't have let them in without a warrant. ;)
Also when you've fixed that your code will output 'Value not in array!!!' for every item not matching the search value.
You need to move the 'not found' check outside the the for-loop. But let's take this one step at a time.

My program is printing only the last input from the ArrayList

I have another small class containing the main method that display the
invoice, but the toString method here is only displaying the last item
entered, not the three itemnames,quantities, prices and totalPrice.
I have doubts about addItemLine and toString.
Can someone see what I am missing here?
I was enable to past the lineItem class code.
import java.util.ArrayList;
import java.util.Scanner;
public class Transaction {
private ArrayList<lineItem> lineItems;
private int customerID;
private String customerName;
public Transaction (int customerID, String customerName){
this.customerID= customerID;
this.customerName= customerName;
this.lineItems= new ArrayList<>();
}
public int getcustomerID(){
return customerID;
}
public void setcustomerID(int customerID){
this.customerID = customerID;
}
public String getcustomerName(){
return customerName;
}
public void setcustomerName(String customerName){
this.customerName = customerName;
}
public ArrayList addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
}
return this.lineItems;
}
public void updateItem(String item, int quant, double pri){
lineItem l= new lineItem(item, quant, pri);
int m=0;
m= l.getQuantity();
m=m+quant;
double tot=0;
}
public double getTotalPrice(){
double totalPrice = 0;
for (int i =0;i<2; i++){
lineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem( String s, int d, double k){
lineItem o= new lineItem(s,d,k);
for (int i =0;i<2; i++){
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s= (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toString(lineItem lin) {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (int i=0; i<2;i++){
b= ("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + "
"
+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
return a + b;
}
TransactionTesting:
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
String m=""; int g=0; double r=0; int id=0; String name="";
Scanner mykey= new Scanner(System.in);
System.out.println("enter customer name:");
name= mykey.nextLine();
System.out.println("enter customer ID:");
id=mykey.nextInt();
Transaction mytrans= new Transaction(id, name);
lineItem line= new lineItem(m,g,r);
mytrans.addItemLine(line);
System.out.println(mytrans.toString(line));
}
}
Change your toString() method like this:
public String toString() {
String a="", b="";
a=("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " +
this.getcustomerName());
for (lineItem item : this.lineItems)
b += ("\n\n" + item.getItemName() + "\t" + "Qty" + item.getQuantity() + " "
+ "#" + item.getPrice() + " "+ "\t" + "$" + item.getPrice());
return a + b;
}
and from your test class call this method as the following:
System.out.println(mytrans.toString());
You don't need any argument in order to print your entire list.
Try to refactor your code a bit. It works, but it can be written better and better ;)
1) The call
System.out.println(mytrans.toString(line));
is printing out the single lineitem that is passed to it. What you probably intended was for Transaction.toString() to iterate over its list Transaction.lineItems and print each item in turn.
In fact Transaction.toString() doesn't need to take in a lineItem argument, the method should merely print out the internals of the class instance.
2) There is a similar confusion in Transacton.addItemLine(). It accepts a lineItem, prompts the user for new values, updates lineItem.. then constructs a new lineItem to store in Transaction.lineItems. It isn't actually causing a bug that I can see but you should get rid of the lineItem argument entirely; addItemLine doesn't need it.
3) Incidentally:
for (int i=0; i<2;i++){ }
loops twice, not three times. I trust you would have caught that in testing.
4) There is also a line of code near the end of addItemLine that doesn't actually do anything! Maybe you can spot that one on your own.
There are some other issues but those are the ones that leapt out at me.
Just a quick non-tested solution that may work. Something is copied from your code, something is changed because your code was wrong.
// If you create this inside the method than you'll lose everything everytime you call addItemLine
private ArrayList<lineItem> lineItems;
public void addItemLine(lineItem line){
Scanner mykey=new Scanner(System.in);
for (int i=0; i<2;i++){
String k= line.getItemName();
int m= line.getQuantity();
double d= line.getPrice();
System.out.println("enter item name:");
k = mykey.next();
line.setItemName(k);
System.out.println("enter quantity:");
m= mykey.nextInt();
line.setQuantity(m);
System.out.println("enter unit price:");
d= mykey.nextDouble();
line.setPrice(d);
line.getItemName(); line.getQuantity(); line.getPrice();
lineItems.add(new lineItem(k,m,d));
// This doesn't have to return anything, it just adds to the list
}
// No parameteres, this should build the string for the current object
public String toString() {
// String concatenation is not the best idea, StringBuilder is better
StringBuilder sb = new StringBuilder();
// If you want to print all of them then you need to iterate over the list
for (lineItem item : lineItems){
sb.append("Customer ID:" + this.getcustomerID() + "\n" + "Customer Name: " + this.getcustomerName());
for (int i=0; i<2;i++){
// Copied from your code
sb.append("\n\n" + lin.getItemName() + "\t" + "Qty" + lin.getQuantity() + " "+ "#" + lin.getPrice() + " "+ "\t" + "$" + lin.getTotalPrice());
}
sb.append("\n);
}
return sb.toString();
}
It seems that you don't understand how to create a Java object, or how to keep your application model separate from your application view.
Here's a test run of your code, after I made some changes.
Enter customer name: Gilbert
Enter customer ID: 123
Enter item name: Spinach
Enter quantity: 5
Enter unit price: .89
Customer ID: 123
Customer Name: Gilbert
Spinach Qty 5 #0.89 $4.45
Enter item name: Corn
Enter quantity: 12
Enter unit price: .29
Customer ID: 123
Customer Name: Gilbert
Corn Qty 12 #0.29 $3.4799999999999995
Enter item name:
First, let's look at your Java objects. The first Java object which you didn't include, is LineItem. Note that Java class names start with a capital letter.
package com.ggl.transaction;
public class LineItem {
private String itemName;
private int quantity;
private double price;
public LineItem(String itemName, int quantity, double price) {
this.itemName = itemName;
this.quantity = quantity;
this.price = price;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getTotalPrice() {
return price * quantity;
}
}
A Java object consists of class fields, and getters and setters for the fields.
Next, here's your Transaction class.
package com.ggl.transaction;
import java.util.ArrayList;
import java.util.List;
public class Transaction {
private List<LineItem> lineItems;
private int customerID;
private String customerName;
public Transaction(int customerID, String customerName) {
this.customerID = customerID;
this.customerName = customerName;
this.lineItems = new ArrayList<>();
}
public int getcustomerID() {
return customerID;
}
public void setcustomerID(int customerID) {
this.customerID = customerID;
}
public String getcustomerName() {
return customerName;
}
public void setcustomerName(String customerName) {
this.customerName = customerName;
}
public void addItemLine(LineItem line) {
this.lineItems.add(line);
}
public void updateItem(String item, int quant, double pri) {
LineItem l = new LineItem(item, quant, pri);
int m = 0;
m = l.getQuantity();
m = m + quant;
l.setQuantity(m);
}
public double getTotalPrice() {
double totalPrice = 0;
for (int i = 0; i < 2; i++) {
LineItem item = lineItems.get(i);
totalPrice = totalPrice + item.getTotalPrice();
}
return totalPrice;
}
public String getLineItem(String s, int d, double k) {
LineItem o = new LineItem(s, d, k);
for (int i = 0; i < 2; i++) {
if (!s.equals(o.getItemName()))
System.out.println("item not found");
else
s = (o.getItemName() + o.getQuantity() + o.getPrice());
}
return s;
}
public String toItemString(LineItem lin) {
String b = "";
String a = ("Customer ID: " + this.getcustomerID() + "\n"
+ "Customer Name: " + this.getcustomerName());
for (int i = 0; i < 2; i++) {
b = ("\n\n" + lin.getItemName() + "\t" + "Qty " + lin.getQuantity()
+ " " + "#" + lin.getPrice() + " " + "\t" + "$"
+ lin.getTotalPrice() + "\n");
}
return a + b;
}
}
I simplified your addItemLine class. Code that receives input using the Scanner class belongs in your TransactionTesting class.
I renamed your toString method to toItemString. toString is a method of the Object class. Since your method has a parameter, I renamed it to lessen any confusion.
Finally, here's your TransactionTesting class. I fixed it up so it would work. You can specify any number of line items. To stop processing, just enter a blank item name.
package com.ggl.transaction;
import java.util.Scanner;
public class TransactionTesting {
public static void main(String args[]) {
Scanner mykey = new Scanner(System.in);
System.out.print("Enter customer name: ");
String name = mykey.nextLine().trim();
System.out.print("Enter customer ID: ");
int id = Integer.valueOf(mykey.nextLine().trim());
Transaction mytrans = new Transaction(id, name);
boolean processing = true;
while (processing) {
System.out.print("Enter item name: ");
String k = mykey.nextLine().trim();
if (k.equals("")) {
processing = false;
} else {
System.out.print("Enter quantity: ");
int m = Integer.valueOf(mykey.nextLine().trim());
System.out.print("Enter unit price: ");
double d = Double.valueOf(mykey.nextLine().trim());
LineItem lineItem = new LineItem(k, m, d);
mytrans.addItemLine(lineItem);
System.out.println("\n" + mytrans.toItemString(lineItem));
}
}
mykey.close();
}
}
Remember, keep your application model (LineItem & Transaction) separate from your application view (TransactionTesting).
Simply put, in your method "addItemLine" you take data from 1 lineItem, overwrite it with some keyboard input, and the put in the list 2 other lineItem instances.
Then in the test code you print the original lineItem, which is not even in the list.
The method itself iterates on nothing, just creates twice the same string "b".
I suggest you to look at some tutorials on arrays and for loops.

constructor issues for java

Whenever I run this:
public static void searchForGerbil()
{
System.out.println("Please type in a gerbil lab ID");
Scanner keyboard = new Scanner(System.in);
String searchgerbil = keyboard.next();
for (int i = 0; i <gerbil.length; i++){
if ( searchgerbil.equals(gerbil[i].getId())){
System.out.println(gerbil);
}
else{
System.out.println("Gerbil " + searchgerbil + " doesnt exist");
}
}
}
I end up with this output when i input 123 for String searchgerbil:
[Lgerbillab.Gerbil;#42886462
Gerbil 123 doesnt exist
here is the rest of my code for reference:
Class gerbillab
package gerbillab;
import java.util.Scanner;
import gerbillab.Gerbil;
public class gerbillab{
public static int population;
public static int[] maxfood;
public static int[] foodeats;
public static int types;
public static String[] idnumber;
public static String g;
public static String gerbilId;
public static Gerbil[] gerbil;
public static String amountoffoodeaten;
public static String gerbilsearch;
public static String thisgerbil;
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
System.out.println("How many types of food do the gerbils eat?");
String f = keyboard.nextLine();
int totalF = Integer.parseInt(f);
String[] food = new String[totalF];
maxfood = new int[totalF];
for
(int a = 0; a<food.length; a++){
System.out.println("Name of food number " + (a+1));
String foodname = keyboard.nextLine();
food[a] = foodname;
System.out.println("Max amount of food " + (a+1));
String m = keyboard.nextLine();
int maximum = Integer.parseInt(m);
maxfood[a] = maximum;
}
System.out.println("How many gerbils are in the lab?");
String numberofGerbils = keyboard.nextLine();
population = Integer.parseInt(numberofGerbils);
idnumber = new String[population];
String[] nickname = new String[population];
boolean[] bite = new boolean[population];
boolean[] escape = new boolean[population];
gerbil = new Gerbil[population];
for
(int b = 0; b<idnumber.length; b++){
System.out.println("What is the id number of gerbil " + (b+1));
String idnumberx = keyboard.nextLine();
idnumber[b] = idnumberx;
System.out.println("What is the name for gerbil " + (b+1));
String nicknamex = keyboard.nextLine();
nickname[b] = nicknamex;
int[] foodeats = new int[totalF];
for
(int c = 0; c<foodeats.length; c++){
System.out.println("how much " + food[c] + " did this gerbil eat");
String amountoffoodeaten = keyboard.nextLine();
foodeats[c] = Integer.parseInt(amountoffoodeaten);
}
System.out.println("Does this Gerbil bite? Please enter True or False");
String doesitbite = keyboard.nextLine();
if (doesitbite.equalsIgnoreCase("true"))
bite[b] = true;
else{
bite[b] = false;
}
System.out.println("Does this Gerbil escape? Enter True or False");
String doesitescape = keyboard.nextLine();
if (doesitescape.equalsIgnoreCase("true"))
escape[b] = true;
else{
escape[b] = false;
}
gerbil[b] = new Gerbil(idnumberx, nicknamex, foodeats, escape[b], bite[b], maxfood);
}
while (true){
System.out.println("What would you like to know?");
String question = keyboard.nextLine();
String search = "search";
String average = "average";
String end = "end";
String restart = "restart";
if (question.equalsIgnoreCase(search)){
new gerbillab().searchForGerbil();
}
else
if (question.equalsIgnoreCase(average)){
for(int i = 0; i < idnumber.length; i++){
System.out.println(idnumber[i]);
}
for(int i = 0; i < nickname.length; i++){
System.out.println(nickname[i]);
}
for(int i = 0; i < bite.length; i++){
System.out.println(bite[i]);
}
for(int i = 0; i < escape.length; i++){
System.out.println(escape[i]);
}
}
else
if (question.equalsIgnoreCase(end)){
System.exit(0);
}
else
if (question.equalsIgnoreCase(restart)){
new gerbillab().main(args);
}
else
System.out.println("Try again");
}
}
public static void searchForGerbil()
{
System.out.println("Please type in a gerbil lab ID");
Scanner keyboard = new Scanner(System.in);
String searchgerbil = keyboard.next();
for (int i = 0; i <gerbil.length; i++){
if ( searchgerbil.equals(gerbil[i].getId())){
System.out.println(gerbil);
}
else{
System.out.println("Gerbil " + searchgerbil + " doesnt exist");
}
}
}
}
Class Gerbil
package gerbillab;
public class Gerbil {
private String idnumber;
private String nickname;
private int[] totalfood;
private String[] foodname;
private boolean escape;
private boolean bite;
private int[] foodeats;
public String gerbilsearch;
public Gerbil(String idnumberx, String gerbilName, int[] gerbilfoodeats, boolean gerbilEscape, boolean gerbilBite, int[] maxfood) {
idnumber = idnumberx;
nickname = gerbilName;
foodeats = gerbilfoodeats;
escape = gerbilEscape;
bite = gerbilBite;
totalfood = maxfood;
}
public Gerbil(String[] typefood) {
foodname = typefood;
}
public int[] getfoodeaten() {
return foodeats;
}
public Gerbil(int[] numOfFood) {
totalfood = numOfFood;
}
public int[] getAmountFood() {
return totalfood;
}
public boolean getBite() {
return bite;
}
public boolean getEscape() {
return escape;
}
public String getId() {
return idnumber;
}
public String getName() {
return nickname;
}
public void setId(String newId) {
idnumber = newId;
}
public void setName(String newName) {
nickname = newName;
}
public String[] gettypesofFood() {
return foodname;
}
}
You are trying to print the object without overriding toString you get the default value of classname suffixed with the object's hashcode. You can override your toString as mentioned below.
Another issue is your try to print the entire array instead of the indexed element it currently refers to: System.out.println(gerbil);. You would need to get the indexed element System.out.println(gerbil[i]); (I assume you would want this since you are iterating over the array)
Given that an element in your array exists with ID you provide, take cue from the following toString method (auto-generated through eclipse IDE):
Add this to your Gerbil.java
#Override
public String toString() {
return "Gerbil [idnumber=" + idnumber + ", nickname=" + nickname
+ ", totalfood=" + Arrays.toString(totalfood) + ", foodname="
+ Arrays.toString(foodname) + ", escape=" + escape + ", bite="
+ bite + ", foodeats=" + Arrays.toString(foodeats)
+ ", gerbilsearch=" + gerbilsearch + "]";
}
Change in searchForGerbil()
Replace:
System.out.println(gerbil);
With:
System.out.println(gerbil[i]);
You can try and modify the toString to display the content as you wish to.
In addition to the points PopoFibo made, there's this:
for (int i = 0; i <gerbil.length; i++){
if ( searchgerbil.equals(gerbil[i].getId())){
System.out.println(gerbil);
}
else{
System.out.println("Gerbil " + searchgerbil + " doesnt exist");
}
}
The above code probably does not do what you are hoping for. Say your gerbil array has 10 gerbils, all with different ID's. When you go through the loop, then each time you compare gerbil[i] to the ID, it will display "Gerbil ... doesnt exist" if the ID isn't equal. But this is inside the loop, so that means that if the ID equals one of the array elements, you will get one output line with a gerbil, and 9 output lines that say the gerbil doesn't exist.
You have to move the "doesn't exist" message outside the loop. One way to do that is to declare a new variable boolean found = false before the loop. In the loop, when you find it, set found = true. Then, test found after the loop is done. (You can also use break; once you've found the gerbil inside the loop, because that probably means you can stop searching.)

How to read values from an array with nested loop in java

My aim is to calculate the grade mark for several students who have taken exam for more than one subject. The student records are to be stored within an array.
Please find my code below:
When printing out student record, I was able to print all records within the outer for loop but unable to print the subjects (within the inner for loop). I am getting error "arrayoutofindex".
package Assignment;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* #author Administrator
*/
public class Assignment {
// String name;
int totalMarks;
String surname;
String firstname;
int studNo;
String subject;
Assignment(String surname, String firstname, int studNo, String subject) {
// this.name=name;
// this.totalMarks=totalMarks;
this.firstname = firstname;
this.surname = surname;
this.studNo = studNo;
this.subject = subject;
}
// public String getName(){
// return name;
// }
public String getSName() {
return surname;
}
public String getFName() {
return firstname;
}
public int getTotalMarks() {
return totalMarks;
}
public int getStudNo() {
return studNo;
}
public String getSubject() {
return subject;
}
public static boolean validSubject(String sub) {
return sub.matches("[1-5]");
}
public static void main(String[] args) {
ArrayList<Assignment> list = new ArrayList<Assignment>();
ArrayList<String> l = new ArrayList<String>();
// boolean validSub = false;
int times;
// int numTimes = 1;
// int sub=0;
// int times;
String[] subs;
String sub = "";
Scanner input = new Scanner(System.in);
System.out.print("How many students are in the class?: ");
int sNo = input.nextInt();
int count[] = new int[sNo];
String[] fname = new String[sNo];
String[] sname = new String[sNo];
int[] stud_No = new int[sNo];
// int marks[]=new int[sNo];
for (int i = 0; i < count.length; i++) {
System.out.printf("Student%2d:\n", i + 1);
System.out.print("Student Number: ");
int s_No = input.nextInt();
System.out.print("Enter Firstname:");
String f = input.next();
System.out.print("Enter Surname:");
String s = input.next();
System.out.println("Choose one from the underlisted subjects:");
System.out.println("Subjects:1. Boat Maintenance");
System.out.println("\t 2. Basic sail control");
System.out.println("\t 3. Blue-water Navigation");
System.out.println("\t 4. Chart reading");
System.out.println("\t 5. Laws & Customs of the Sea");
System.out.print("How many subjects will you want to process, Maximum of 3: ");
int subNo = input.nextInt();
int[] subj = new int[subNo];
subs = new String[subNo];
for (times = 0; times < subj.length; times++) {
System.out.printf("Subject%2d: ", times + 1);
// System.out.println("Subject: ");
sub = input.next();
subs[times] = sub;
}
// }
// System.out.print("Enter marks in test1:");
// int t1=input.nextInt();
// System.out.print("Enter marks in test2:");
// int t2=input.nextInt();
// int m=t1+t2;
fname[i] = f;
sname[i] = s;
stud_No[i] = s_No;
// subs[i] = sub;
// subj[i] = sub;
// subj[times] = sub;
// subj[times] = sub;
// marks[i]=m;
list.add(new Assignment(sname[i], fname[i], stud_No[i], subs[times]));
// subs[times] = sub;
}
// int lowest = marks[0];
// int highest = marks[0];
// int counter = count[i];
//
// for(int i=1; i< marks.length; i++)
// {
// if(marks[i] > highest)
// highest = marks[i];
// else if (marks[i] < lowest)
// lowest = marks[i];
// }
for (Assignment a : list) {
// if(a.getTotalMarks()==highest){
// System.out.println(a.getFName() + " get the highest marks");
// }
// if(a.getTotalMarks()==lowest){
// System.out.println(a.getFName() + " get the lowest marks");
// }
System.out.println(a.getFName() + " " + a.getSName());
System.out.println("Student Number: " + a.getStudNo());
System.out.println("Subjects: " + a.getSubject());
System.out.println("=================================");
// System.out.println(subs[times]);
}
}
}
you have
subs[times] = sub;
subj[times]++;
in your inner loop with condition for(times=0;times<subj.length;times++) so i guess that subs is shorter than subj and that whats giving you the exception. Check your conditions and modify it.
I guess, subs[times] = sub; should be subj[times] = sub;.
I ran you code and the error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Assignment.main(Assignment.java:113)
So what is happening in that line?
list.add(new Assignment(sname[i],fname[i],stud_No[i],subs[times + 1]));
In this way you can trace that the error comes from either sname, fname, stud_No or subs accessing something out of their range.
Now you can modify the line and rerun, to figure out what's going on. :)
ArrayOutOfBoundException will occur at line
list.add(new Assignment(sname[i],fname[i],stud_No[i],subs[times + 1]));
because times already increased to subj.length which equal to subs.length.So apply if condition here.

NullPointerException when using class constructor to set array value

I am extremely new to java and am very close to finishing a project I have been trying to finish for a long time. Whenever I try to run the code. It gives a null pointer exception as soon as the constructer is called. My code is listed below and any help would be appreciated.
Main class:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Enter the number of employees to register.");
int arraySize = Input.nextInt();
Input.nextLine();
Employee employee = new Employee(arraySize);
String namesTemp;
String streetTemp;
String cityTemp;
String stateTemp;
String zipCodeTemp;
String dateOfHireTemp;
for(int x = 0; x < arraySize; x++)
{
System.out.println("Please enter the name of Employee " + (x + 1));
namesTemp = Input.nextLine();
System.out.println("Please enter the street for Employee " + (x + 1));
streetTemp = Input.nextLine();
System.out.println("Please enter the city of Employee " + (x + 1));
cityTemp = Input.nextLine();
System.out.println("Please enter the state of Employee " + (x + 1));
stateTemp = Input.nextLine();
System.out.println("Please enter the zip code of Employee " + (x + 1));
zipCodeTemp = Input.nextLine();
System.out.println("Please enter the date of hire for Employee " + (x + 1));
dateOfHireTemp = Input.nextLine();
employee.addEmployee(x, namesTemp, streetTemp, cityTemp, stateTemp, zipCodeTemp, dateOfHireTemp);
System.out.println("The employee ID for employee " + (x + 1) + " is " + (x + 1));
}
for(int x = 0; x < arraySize; x++)
{
String info[] = employee.getEmployeeInfo(x);
System.out.println("Employee ID: " + (x + 1));
System.out.println("Name: " + info[0]);
System.out.println("Address: " + info[1]);
System.out.println("Date of Hire: " + info[2]);
}
}
}
Employee class:
public class Employee
{
private EmployeeName name;
private EmployeeAddress address;
private EmployeeDateOfHire hireDate;
public Employee(int arraySize)
{
}
public void addEmployee(int x, String name, String street, String city, String state, String zipCode, String hireDate)
{
this.name.setName(x, name);
this.address.setAddress(x, street, city, state, zipCode);
this.hireDate.addDateOfHire(x, hireDate);
}
public String[] getEmployeeInfo(int x)
{
String info[] = new String[3];
info[0] = name.getName(x);
info[1] = address.getAddress(x);
info[2] = hireDate.getDateOfHire(x);
return info;
}
}
EDIT--
Here is how I wrote my data classes. They are all written in the same format.
Name Class:
public class EmployeeName
{
private String names[];
public void setArray(int x)
{
String array[] = new String[x];
this.names = array;
}
public void setName(int x, String name)
{
this.names[x] = name;
}
public String getName(int x)
{
return this.names[x];
}
}
In the addEmployee() method
public void addEmployee(int x, String name, String street, String city, String state, String zipCode, String hireDate)
this.name.setName(x, name);
this.address.setAddress(x, street, city, state, zipCode);
this.hireDate.addDateOfHire(x, hireDate);
}
you haven't initialized name or the other fields. By default, instance fields will be initialized to null. Trying to dereference null will cause a NullPointerException.
You should initialize those fields, for example in your Constructor
public Employee(int arraySize)
{
this.name = new EmployeeName();
this.address = new EmployeeAddress();
this.hireDate = new EmployeeDateOfHire();
}
I don't know what those classes look like.
Seeing
private String names[];
public void setArray(int x)
{
String array[] = new String[x];
this.names = array;
}
public void setName(int x, String name)
{
this.names[x] = name;
}
You call setName() which would also throw a NullPointerException because you're trying to dereference names but it's null. You would have to call setArray() first but then that would fail too because if x is 0, you will create an array of size 0 but then try to access the element at index 0, which would not exist. If x was 1, you would create array of size 1 but try to access the element at index 1 (second element), which would throw an IndexOutOfBoundsException.
Seriously rethink your design. Why is this EmployeeName class so complicated? Why don't you just have a String field name. Or two fields, firstName and lastName?

Categories