使用文件和链表。我从文件中读取双数并应该将其添加到“链接列表”的代码。当它显示数字时,它要求用户输入一个双数字。在输出中,它不会将键入的数字添加到链接列表中。不知道如何将这些数字添加到链接列表中,因此我可以对其进行操作,例如(添加/删除)。
public class LinkList
{
public static void main(String [] args)
{
linkedListNumbers numbers= new linkedListNumbers();
numbers.newLinkList();
numbers.addElementToList();
}
}
class NumNode
{
private double num;
private NumNode next;
public NumNode()
{
next = null;
}
public NumNode(double num)
{
this.num = num;
next = null;
}
public void setNum(double num)
{
this.num = num;
}
public double getNum()
{
return num;
}
public void setNext(NumNode next)
{
this.next = next;
}
public NumNode getNext()
{
return next;
}
public String toString()
{
String str = "" + num;
return str;
}
}
class linkedListNumbers
{
private NumNode head;
private int count;
NumNode aNode = new NumNode();
public void newLinkList()
{
Scanner scan = new Scanner(System.in);
Scanner fileScan;
boolean validName = false;
double num = 0.0;
boolean validNumber = false;
NumNode current = null;
NumNode previous = null;
do
{
System.out.print("Enter file name: ");
String str = scan.nextLine();
try
{
fileScan = new Scanner(new File(str));
validName = true;
double count = 0;
while(fileScan.hasNextLine())
{
try
{
str = fileScan.nextLine();
num = Double.parseDouble(str);
validNumber = true;
count++;
System.out.print(String.format("\t%6.2f", num));
}
catch (NumberFormatException nfe)
{
//System.out.println("is not a Double number");
}
}
System.out.println("\nNumber of nodes = " + count);
System.out.println(aNode);
}
catch (FileNotFoundException fnfe)
{
System.out.println("Invalid File name: enter again");
}
} while(!validName);
}
public void printList()
{
NumNode current = head;
int reading = 0;
while(current!= null)
{
System.out.printf("\t%6.2f", ++reading, current.toString());
}
}
public void addElementToList()
{
Scanner scan = new Scanner(System.in);
boolean validN = false;
double num = 0.0;
NumNode current = null;
NumNode previous = null;
double numToAdd = 0.0;
double count =0;
do
{
System.out.println("Enter double number");
String str = scan.nextLine();
try
{
num = Double.parseDouble(str);
aNode.setNext(head);
head = aNode;
count++;
}
catch (NumberFormatException nfe)
{
System.out.println("is not a Double number");
}
} while(!validN && count<1);
System.out.println(aNode.toString());
}
}