I have made a program that takes a user's input for start number, end number, and an increment. This is added to a Range (linked-list). I want to add a number that the user inputted to this Range and put the inputted number in between each number.
Main:
public class PDEMain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a start number: ");
Integer startNum = input.nextInt();
System.out.print("Enter end number: ");
Integer endNum = input.nextInt();
System.out.print("Enter increment: ");
Integer increment = input.nextInt();
Range obj = new Range(startNum, endNum, increment);
obj.display();
System.out.print(" Enter 1 for take:\n "
+ "Enter 2 for drop:\n "
+ "Enter 3 for repeat:\n "
+ "Enter 4 for interpose: ");
Integer number = input.nextInt();
if(number == 1) {
obj.take();
}
if(number == 2) {
obj.drop();
}
if(number == 3) {
obj.repeat();
}
if(number == 4) {
obj.interpose();
}
}
}
Range:
public class Range implements Cloneable {
private Integer data; // holds the data
private Range link; //holds the link
private Range head; //refers to head of linked list
private Integer startValue;
private Integer endValue;
private Scanner input;
public Range(Integer data, Range link) {
this.data = data;
this.link = link;
}
public Range(Integer data, Range link, Range head) {
this.data = data;
this.link = link;
this.head = head;
}
public Range(Integer start, Integer end,Integer increment) {
if(start == null) {
startValue = 0;
}
if(increment == null) {
if(start < end) {
increment++;
} else {
increment--;
}
}
for (int i = start; i <= end; i+= increment) {
addNodeAfter(i);
}
}
public Integer getData() {
return data;
}
public void setData(Integer data) {
this.data = data;
}
public Range getLink() {
return link;
}
public void setLink(Range link) {
this.link = link;
}
public Range getHead() {
return head;
}
public void setHead(Range head) {
this.head = head;
}
I have the following code for this interpose method:
public void interpose() {
System.out.println("What number would you like to interpose? ");
Integer answer = input.nextInt();
Range cursor = head;
for (int i = 0; i <= answer; i++) {
System.out.print(cursor.getData() + " ");
this.link = new Range(answer, this.link);
cursor = cursor.getLink();
}
System.out.print("New Range: ");
display();
modify();
anotherRange();
}
I get a NullPointerException at Integer answer = input.nextInt();
Any tips on why I get this Exception and also if my logic is correct?
Try to add Scanner class into interpose() method like this:
Scanner input = new Scanner(System.in);
Integer answer = input.nextInt();
Related
I can write the function to delete at position I choose. But I have problems when I write the function to delete the employee by input of the employee's name. I still have the same problem with the search function. Use case 7, 8 in menu to perform delete and search function. Can anybody help me with my code?
Here's my source code:
import java.util.Scanner;
import java.io.Serializable;
/* Class Node */
class Employee implements Serializable{
int ID;
String name;
String address;
Employee(int emp_ID, String emp_name, String emp_address){
ID = emp_ID;
name = emp_name;
address = emp_address;
}
public void print(){
System.out.println(ID);
System.out.println(name);
System.out.println(address);
}
#Override
public String toString() {
return ID + "-" + name + "-" + address;
}
}
class Node
{
protected Employee emp;
protected Node link;
public Object name;
public Node in;
/* Constructor */
public Node()
{
link = null;
emp = null;
}
/* Constructor */
public Node(Employee e,Node n)
{
emp = e;
link = n;
}
/* Function to set link to next Node */
public void setLink(Node n)
{
link = n;
}
/* Function to set data to current Node */
public void setData(Employee e)
{
emp = e;
}
/* Function to get link to next node */
public Node getLink()
{
return link;
}
/* Function to get data from current Node */
public Employee getData()
{
emp.print();
return null;
}
}
/* Class linkedList */
class linkedList
{
protected Node start ;
protected Node end ;
public int size ;
/* Constructor */
public linkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isEmpty()
{
return start == null;
}
/* Function to get size of the list */
public int getSize()
{
return size;
}
/* Function to insert element at the begining */
public void insertAtStart(Employee e)
{
Node nptr = new Node(e,null);
nptr.setLink(start);
if(start == null)
{
start = nptr;
nptr.setLink(start);
end = start;
}
else
{
end.setLink(nptr);
start = nptr;
}
size++ ;
}
/* Function to insert element at end */
public void insertAtEnd(Employee e)
{
Node nptr = new Node(e,null);
nptr.setLink(start);
if(start == null)
{
start = nptr;
nptr.setLink(start);
end = start;
}
else
{
end.setLink(nptr);
end = nptr;
}
size++ ;
}
/* Function to insert element at position */
public void insertAtPos(Employee e , int pos)
{
Node nptr = new Node(e,null);
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink() ;
ptr.setLink( nptr );
nptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size++ ;
}
/* Function to delete element at position */
public void searchByName(){
}
public void deleteByName(){
}
public void deleteAtPos(int pos)
{
if (size == 1 && pos == 1)
{
start = null;
end = null;
size = 0;
return ;
}
if (pos == 1)
{
start = start.getLink();
end.setLink(start);
size--;
return ;
}
if (pos == size)
{
Node s = start;
Node t = start;
while (s != end)
{
t = s;
s = s.getLink();
}
end = t;
end.setLink(start);
size --;
return;
}
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink();
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size-- ;
}
/* Function to display contents */
public void display()
{
System.out.print("\nEmployee Management= ");
Node ptr = start;
if (size == 0)
{
System.out.print("empty\n");
return;
}
if (start.getLink() == start)
{
System.out.print(start.getData()+ "\n");
return;
}
System.out.print(start.getData()+ "" + "\n");
ptr = start.getLink();
while (ptr.getLink() != start)
{
System.out.print(ptr.getData()+ "" + "\n");
ptr = ptr.getLink();
}
System.out.print(ptr.getData()+ "\n");
}
}
/* Class CircularSinglyLinkedList */
public class CurrilarLinkedList
{
public static void main(String[] args)
{
int ID = 0;
String name = null;
String address = null;
Employee emp = null;
Scanner scan = new Scanner(System.in);
/* Creating object of linkedList */
linkedList list = new linkedList();
System.out.println("Circular Singly Linked List Test\n");
char ch;
/* Perform list operations */
do
{
System.out.println("\nCircular Singly Linked List Operations\n");
System.out.println("1. insert at begining");
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");
System.out.println("7. delete by name");
System.out.println("8. search by name");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.print("Please input an Employee \n");
Scanner myScanner = new Scanner(System.in);
System.out.println("Please input an Employee ID");
ID = myScanner.nextInt();
myScanner.nextLine();
System.out.println("Please input an Employee Name");
name = myScanner.nextLine();
System.out.println("Please input an Employee Address");
address = myScanner.nextLine();
emp = new Employee(ID,name,address);
list.insertAtStart(emp);
break;
case 2 :
System.out.print("Please input an Employee \n");
myScanner = new Scanner(System.in);
System.out.println("Please input an Employee ID");
ID = myScanner.nextInt();
myScanner.nextLine();
System.out.println("Please input an Employee Name");
name = myScanner.nextLine();
System.out.println("Please input an Employee Address");
address = myScanner.nextLine();
emp = new Employee(ID,name,address);
list.insertAtEnd(emp);
break;
case 3 :
System.out.println("Enter position");
int pos = scan.nextInt() ;
System.out.print("Please input an Employee \n");
myScanner = new Scanner(System.in);
System.out.println("Please input an Employee ID");
ID = myScanner.nextInt();
myScanner.nextLine();
System.out.println("Please input an Employee Name");
name = myScanner.nextLine();
System.out.println("Please input an Employee Address");
address = myScanner.nextLine();
emp = new Employee(ID,name,address);
if (pos <= 1 || pos > list.getSize() )
System.out.println("Invalid position\n");
else
list.insertAtPos(emp, pos);
break;
case 4 :
System.out.println("Enter position");
int p = scan.nextInt() ;
if (p < 1 || p > list.getSize() )
System.out.println("Invalid position\n");
else
list.deleteAtPos(p);
break;
case 5 :
list.isEmpty();
case 6 :
System.out.println("Size = "+ list.getSize() +" \n");
break;
case 7:
System.out.println("Enter the name of employee you want to delete:");
myScanner = new Scanner(System.in);
name = myScanner.nextLine();
case 8:
System.out.println("Enter the name of employee you want to search:");
myScanner = new Scanner(System.in);
name = myScanner.nextLine();
default :
System.out.println("Wrong Entry \n ");
break;
}
/* Display List */
list.display();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}
I can't figure out what is wrong with my if else statements telling it which statement to run and what is wrong with the insert statement. It keeps going straight back to insert no matter what i type.
import java.util.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.*;
import javax.lang.model.element.*;
public class Node {
public static Node head;
static String data;
static Node next;
static Node q = new Node("", null);
static String inputline;
static int y = 0;
static int count = 0;
static Node current = new Node(q.data, q);
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) {
BuildList();
}
public Node() {
data = "";
next = null;
}
public Node(String x, Node n) {
data = x;
next = n;
}
public static void BuildList() {
try { //match
System.out.println("Please Choose A Command To Execute From The Following List:");
System.out.println("-----------------------------------------------------------");
System.out.println("$insert");
System.out.println("$delete m n");
System.out.println("$print m n");
System.out.println("$line m");
System.out.println("$search String");
System.out.println("$done");
System.out.println(
"Please NOTE: m and n are line number parameters for editing and String is a word");
System.out.println("-----------------------------------------------------------");
inputline = in.readLine();
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
while (!array[0].equals("$done")) //each statement tells it which method to run
{
if (array[0].equals("$insert")) {
Insert();
} else if (array[0].equals("$delete")) {
Delete();
} else if (array[0].equals("$print")) {
Print();
} else if (array[0].equals("$line")) {
Line();
} else if (array[0].equals("$search")) {
Search();
} else {
System.out.println("You have entered an incorrect command");
}
System.out.println("Please enter a command");
inputline = in.readLine();
}
System.out.println("The program is done");
} catch (Exception e) {
System.out.println("Error --" + e.toString());
}
}
public static void Insert() throws IOException {
System.out.println(
"Please Enter The Desired Text (Note: enter $$ when you wish to terminate insert command)");
while (!inputline.equals("$$")) {
inputline = in.readLine();
Node p = new Node(inputline, null);
q.next = p;
q = p;
y++;
}
}
public static void Delete() {
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
q = head.next;
int lower = Integer.parseInt(array[1]);
int upper = Integer.parseInt(array[2]);
lower--;
if (lower > upper) {
System.out.println("Wrong, first number must be the smaller line number");
} else
for (count = 1; count < y; count++) {
if (lower <= count) {
while (lower <= upper) {
q.next = q.next;
current = q;
lower++;
}
current = q;
break;
} else {
q = q.next;
}
}
}
public static void Print() {
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
q = head;
if (array.length > 1) {
int lower = Integer.parseInt(array[1]);
int upper = Integer.parseInt(array[2]);
if (lower > upper) {
System.out.println("Wrong, first number must be the smaller line number");
} else {
for (count = 1; count <= y; count++) {
if (lower <= count) {
while (lower <= upper) {
System.out.println(q.data);
q = q.next;
lower++;
}
break;
} else {
q = q.next;
}
}
}
} else {
while (q != null) {
System.out.println(q.data);
q = q.next;
}
}
}
public static void Line() {
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
q = head.next;
int line_number = Integer.parseInt(array[1]);
for (count = 1; count <= y; count++) {
if (line_number == count) {
System.out.println(q.data);
current = q;
break;
} else {
q = q.next;
}
}
}
public static void Search() {
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
if (data.contains(array[1])) {
System.out.println(q.data);
} else if (!data.contains(array[1])) {
System.out.println("Word Not Found");
}
}
}
After
System.out.println("Please enter a command");
inputline = in.readLine();
in the while loop, you need to split it into the array again:
array = inputline.split(" ");
otherwise you never change the value of array[0].
I'm making a program where I can add an Integer sequence to a Range. I'm having trouble adding this values to the Range. It should run the method addNodeAfter, but it does nothing.
Then when I want to display the Range I get a NullPointerException one this line:
for (int i = 1; i <= manyNodes; i++){
Any tips?
Main:
public class PDEMain {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a start number: ");
Integer startNum = input.nextInt();
System.out.print("Enter end number: ");
Integer endNum = input.nextInt();
System.out.print("Enter increment: ");
Integer increment = input.nextInt();
Range obj = new Range(startNum, endNum, increment);
System.out.println(obj);
obj.display();
}
}
Range:
public class Range implements Cloneable {
private Integer data; // holds the data
private Range link; //holds the link
Range head; //refers to head of linked list
private Integer manyNodes;
private Integer startValue;
private Integer endValue;
private Scanner input;
public Range(Integer data, Range link){
this.data = data;
this.link = link;
}
public Range(Integer data, Range link, Range head) {
this.data = data;
this.link = link;
this.head = head;
manyNodes++;
}
public Range(Integer start, Integer end,Integer increment){
if(start == null){
startValue = 0;
}
if(increment == null){
if(start < end){
increment++;
}else{
increment--;
}
}
for (int i = start; i <= end; i+= increment){
addNodeAfter(i);
System.out.println(i);
}
}
public Integer getData() {
return data;
}
public void setData(Integer data) {
this.data = data;
}
public Range getLink() {
return link;
}
public void setLink(Range link) {
this.link = link;
}
public Range getHead() {
return head;
}
public void setHead(Range head) {
this.head = head;
}
public void addNodeAfter(Integer element){
this.link = new Range(element, this.link);
}
public void display(){
Range cursor = head;
for (int i = 1; i <= manyNodes; i++){ // NPE on this line
System.out.print(cursor.getData() + " ");
cursor = cursor.getLink();
}
System.out.println("");
}
}
You have defined manyNodes as an Integer, not an int. This means that its default value is null, not 0, and you never set the value anywhere in your code.
When you try to loop using it as the control variable in your display() method, the JVM is going to throw an NPE when it tries to unbox the null.
A quick fix would be to change the type to int:
private int manyNodes;
This will solve the immediate NPE, but still not display anything, since you never actually increment manyNodes in the constructor you're calling. This means that the for-loop in your display() method falls through and never actually prints any of the data.
I would recommend getting rid of head and manyNodes altogether, and re-writing your display() method along the lines of:
public void display() {
Range cursor = getLink();
while (cursor != null) {
System.out.print(cursor.getData() + " ");
cursor = cursor.getLink();
}
System.out.println("");
}
Note that this will output the data "backwards" because of the way you add things in this constructor:
public static void main(String[] args) throws Exception {
Range obj = new Range(1, 10, 1);
obj.display(); // prints 10 9 8 7 6 5 4 3 2 1
}
You might want to take a look at an existing linked-list implementation to get a better idea how they are normally written.
I am doing a project in Java and I need to create a queue method.
Every time someone is added to a room, they need to be added to the queue.
I nee to create my own queue object in your program and write methods within the object to add to queue and take from queue.
Every time a customer is added to a room it should use the
queue object method to add the customer’s name to the queue.
When the user selects to display the names of the last 3 customers the code should remove them from the queue one by one (first in first out) and display them as they are removed.
The queue should be based on an array and hold 7 items.
When the queue items reach the end of the array they should be added to the start or the array.
If the queue becomes full then an error message should be displayed and the oldest queue item should be automatically removed and displayed.
This is the main body:
package hotelcoursework2;
import java.util.*;
public class HotelCourseWork2 {
public static void main(String[] args) {
Room[] myHotel = new Room[10];
Queue mq = new Queue();
int guests = 0;
String roomName = null;
int roomNum = 0;
String letter = "";
for (int i = 0; i < myHotel.length; i++) {
myHotel[i] = new Room();
}
do {
System.out.println("Press E to display empty rooms");
System.out.println("Press A to add customers to room");
System.out.println("Press V to view all rooms ");
System.out.println("Press D to delete customers from rooms");
System.out.println("Or enter 1 to add to queue, 2 to take from queue or 3 display queue");
System.out.println("Press S to save");
System.out.println("Press L to load");
System.out.println("Press X to exit");
System.out.println("Enter a Letter: ");
Scanner scan = new Scanner(System.in);
letter = scan.next();
if (letter.equals("A")) {
add(myHotel, roomNum, roomName, guests);
mq.addqueue();
}
if (letter.equals("V")) {
view(myHotel);
}
if (letter.equals("E")){
empty(myHotel);
}
if(letter.equals("D")){
delete(myHotel, roomNum);
mq.takequeue();
}
if (letter.equals("S")){
}
if(letter.equals("3")){
mq.displayqueue();
}
} while (letter.charAt(0) != 'X');
System.out.println("Exit successfull");
}
private static void add(Room myHotel[], int roomNum, String roomName, int guests) {
Scanner input = new Scanner(System.in);
System.out.println("Enter room number (0-9) or 10 to stop:");
roomNum = input.nextInt();
if (roomNum == 10) {
System.out.println("Exit successful");
System.exit(0);
}
System.out.println("Enter name for room " + roomNum + " :");
roomName = input.next();
myHotel[roomNum].setName(roomName);
System.out.println("Enter how many guests: ");
guests = input.nextInt();
myHotel[roomNum].setGuestsInRoom(guests);
System.out.println("Add customers to queue: ");
for (int i = 0; i < 10; i++) {
System.out.println("Customer " + myHotel[i].getName() + " has been allocated to room " + i
+ " with " + myHotel[i].getGuestsInRoom() + " guests. ");
}
}
private static void view(Room myHotel[]) {
for (int i = 0; i < 10; i++) {
System.out.println("room " + i + " occupied by " + myHotel[i].getName() );
}
}
private static void empty(Room myHotel[]) {
for (int i = 0; i < 10; i++) {
if (myHotel[i].getName().equals("no-one")) {
System.out.println("room " + i + " is empty");
}
}
}
private static void delete(Room myHotel[], int roomNum){
Scanner input = new Scanner(System.in);
System.out.println("Enter room number you want to delete a customer from: ");
roomNum = input.nextInt();
myHotel[roomNum].setName("no-one");
}
}
This is the class I have created for the queue but now I am stuck.The queue should be first in first out.
package hotelcoursework2;
import java.util.Scanner;
public class Queue {
// be careful - this queue can go over the end of the array
//the array should be used in a circular way
private static String qitems[] = new String[7];
private static int front = 0, end = 0;
static void addqueue() {
Scanner input = new Scanner(System.in);
System.out.print("Enter someone to the queue :");
qitems[end] = input.next();
end++;
}
static void takequeue() {
if (end > front) {
System.out.println("Person remove :" + qitems[front]);
front++;
} else {
System.out.println("Empty queue");
}
}
static void displayqueue() {
System.out.println("Queue display: ");
for (int look = front; look < end; look++) {
System.out.print(" " + qitems[look]);
}
System.out.println("");
}
}
So basically you want to know how to implement a simple queue.
Unless you have to, using an array is more complicated because you have to deal with resizing the array and moving its contents about.
The simplest queue structure is a linked list, like this:
public class Queue<T>
{
private Node head;
private Node tail;
public void add(T value)
{
if (head == null)
{
head = new Node(null, value);
tail = head;
}
else
{
tail = new Node(tail, value);
}
}
public T peek()
{
return head == null ? null : head.value;
}
public T take()
{
if (head == null)
{
return null;
}
else
{
T value = head.value;
head = head.next;
return value;
}
}
#Override
public String toString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[");
Node current = head;
while (current != null)
{
stringBuilder.append(current.value).append(",");
current = current.next;
}
return stringBuilder.replace(stringBuilder.length() - 1, stringBuilder.length(), "]").toString();
}
private class Node
{
private Node next;
private T value;
public Node(Node previous, T value)
{
this.value = value;
if (previous != null)
{
previous.next = this;
}
}
}
}
This class keeps reference to the head and tail Nodes adjusting references in the Node chain when new values are added and modifying the head reference when values are taken.
I am new to programming and I'm starting to create a simple calculator in Java, but I keep getting an error on the line
for (int i = 0; i < user_input.length(); i++)
The error says:
Exception in thread "main" java.lang.NullPointerException
How can I fix this problem?
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.util.Scanner;
public class stringCalculator
{
public static ArrayList<String> input = new ArrayList<String>();
public static ArrayList<String> calcOperators = new ArrayList<String>();
public static ArrayList<Integer> calcOperands = new ArrayList<Integer>();
public static String user_input;
public static String first;
public static int int1;
public static String char1;
public static int int2;
public static String next;
}
public static void input()
{
Scanner user_input = new Scanner(System.in);
int1 = user_input.nextInt();
char1 = user_input.next();
int2 = user_input.nextInt();
next = user_input.nextLine();
}
public void calcOperators()
{
for (int i = 0; i < user_input.length(); i++)
{
if (char1 == "+")
{
calcOperators.add(char1);
}
else if (char1 == "-")
{
calcOperators.add(char1);
}
else if (char1 == "char1")
{
calcOperators.add(char1);
}
else if (char1 == "/")
{
calcOperators.add(char1);
}
}
public void calcOperands()
{
for (int i = 0; i < user_input.length(); i++)
{
if (int1 == 1 || int2 == 1)
{
calcOperands.add(1);
}
else if (int1 == 2 || int2 == 2)
{
calcOperands.add(2);
}
else if (int1 == 3 || int2 == 3)
{
calcOperands.add(3);
}
else if (int1 == 4 || int2 == 4)
{
calcOperands.add(4);
}
else if (int1 == 5 || int2 == 5)
{
calcOperands.add(5);
}
else if (int1 == 6 || int2 == 6)
{
calcOperands.add(6);
}
else if (int1 == 7 || int2 == 7)
{
calcOperands.add(7);
}
else if (int1 == 8 || int2 == 8)
{
calcOperands.add(8);
}
else if (int1 == 9 || int2 == 9)
{
calcOperands.add(9);
}
else if (int1 == 0 || int2 == 0)
{
calcOperands.add(0);
}
}
}
}
public class Main
{
public static void main(String[] args)
{
stringCalculator c = new stringCalculator();
c.input();
c.calcOperators();
c.calcOperands();
}
}
I am kind of confused in here why you have
public static String user_input
and then
Scanner user_input = new Scanner(System.in);
int1 = user_input.nextInt();
char1 = user_input.next();
int2 = user_input.nextInt();
next = user_input.nextLine();
And finally you are using the same var name for strings and ints in loops:
for (int i = 0; i < user_input.length(); i++)
for (int i = 0; i < user_input.length(); i++)
I would highly recommend refactoring this code.
.....
private ArrayList<String> input = new ArrayList<String>();
private ArrayList<String> calcOperators = new ArrayList<String>();
private ArrayList<Integer> calcOperands = new ArrayList<Integer>();
private String user_input;
private String first;
private String next;
private String char1;
private int integer2;
private int integer1;
}
public static void input()
{
Scanner input = new Scanner(System.in);
int int1 = input.nextInt();
int int2 = input.nextInt();
string str = input.next();
string nxt = input.next();
setInteger1(int1);
setInteger2(int2);
setStringFirst(str);
setStringNext(...);
....
// And so on
}
private void setInteger1(int int1) {
this.integer1 = int1;
}
private Integer getInteger1() {
return this.integer1;
}
private void setInteger2(int int2) {
this.integer2 = int2;
}
private Integer getInteger2() {
return this.integer2;
}
private void setStringFirst(String fst) {
this.first = fst;
}
private String getStringFirst() {
return this.first;
}
// And so on. Create all get and set methods for each global variable and for future
// reference do not use variable names that are the same as method, names
// and try to use more meaningful variable names. In fact, if you look at
// Java naming conventions it would do you good.
Could you also tell us perhaps what these loops are meant to do? As I don't really understand what is this? Do you want to iterate over an array of "things" and match each operation to given array element? Or do you just want a single element to match one of the operations?
Side note: Class names should be capitalized:
public class StringCalculator
==================================================================================
OK, I have made a simple program that allows you to add a string into an array and then display it. It is based on what you were doing although you will see it is structured differently. This should give you a head start and allow you to implement this further and finish whatever you are doing.
public class Thing {
private String operator;
private void getUserInput() {
Scanner input = new Scanner(System.in);
if(input.hasNextInt()) {
System.out.println("I have entered an integer: " + input.nextInt());
}
else {
setOperator(input.nextLine());
addOperators();
System.out.println("I have entered a string: " + getOperator());
}
displayThing();
}
private ArrayList<String> addOperators() {
ArrayList<String> operatorsList = new ArrayList<String>();
if(getOperator().equals("+")) {
operatorsList.add(operator);
}
if(getOperator().equals("-")) {
operatorsList.add(operator);
}
else {
operatorsList.add(getOperator());
}
return operatorsList;
}
private void displayThing() {
System.out.println(addOperators());
}
public static void main(String[] args) {
Thing program = new Thing();
program.getUserInput();
}
// Setters and getters
private void setOperator(String operator) {
this.operator = operator;
}
private String getOperator() {
return this.operator;
}
}
You have declared the public static String user_input; which is used in a for loop and not initialised, so thus the exception. Initialise it in your input method, like this.user_input=user_input.nextLine().
You have a static String named user_input defined as:
public static String user_input; // This is null and what the for loop is reading
Set a value to that string when you're using your Scanner... which you shouldn't have also named user_input.