Abraham Cho Abraham Cho - 1 year ago 76
Java Question

How to repeatedly store data in linked lists?

I have a program where I want to continue adding in an integer and string in a linked list. However when I print out the linked list it only prints out the last entered values and not the previous ones. So If I entered 3 Sally and then entered 6 Bob the linked list only prints out 6 bob. I want to be able to print out everything in the linkedlist no just the last entered.

public class Texteditor {

* @param args the command line arguments
static int myInt;
static String myString;

public Texteditor(int a, String s){
myInt = a;
myString = s;
public String toString(){
return myInt + " " + myString;
public static void main(String[] args) {
LinkedList<Texteditor> myLL = new LinkedList<Texteditor>();

int isExit = 0;
System.out.println("Hello Welcome to Your Personal Texteditor! ");
System.out.println("There are many options you can do with this text editor");
System.out.println("1. If you enter a line number with no text, the line number will be deleted.");
System.out.println("2. If you enter LIST alone the editor will print everything in the list with line number.");
System.out.println("3. If you enter RESEQUENCE the line numbers will be resequenced to start at 10.");
while(isExit ==0) {
// myLL = new LinkedList<Texteditor>();
System.out.println("Please enter the line number: ");
Scanner kb = new Scanner(System.in);
myInt = kb.nextInt();
System.out.println("Plese enter text as a string: ");
Scanner kb1 = new Scanner(System.in);
myString = kb1.nextLine();
Texteditor a1 = new Texteditor(myInt, myString);
System.out.println("Would you like to keep going? Enter yes or no: " );
Scanner kb2 = new Scanner(System.in);
if (kb2.next().equals("no")){
isExit = 1;

for (Texteditor element : myLL){
System.out.println(element + "\n");



Answer Source

Your myInt and myString are static, which means they're shared by instances. Make them non-static and the code should work correctly.

Also, don't recreate the Scanner every time in the loop. Once is enough.