Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在主类以外的类中使用发送到程序的参数?_Java_String_File_Oop_Linked List - Fatal编程技术网

Java 如何在主类以外的类中使用发送到程序的参数?

Java 如何在主类以外的类中使用发送到程序的参数?,java,string,file,oop,linked-list,Java,String,File,Oop,Linked List,我的程序由两个名为Main和LinkedList的类组成,我的程序有3个参数。例如,虽然我可以在主类中访问args[1],但在LinkedList类中无法访问它。它说数组访问args[2]将产生NullPointerException,如果我尝试运行它,它会让我产生NullPointerException。我怎样才能解决这个问题 这是我的密码: 主要社科院: import java.io.*; import java.util.Scanner; // Import the Scanner cla

我的程序由两个名为
Main
LinkedList
的类组成,我的程序有3个参数。例如,虽然我可以在主类中访问
args[1]
,但在LinkedList类中无法访问它。它说数组访问
args[2]
将产生
NullPointerException
,如果我尝试运行它,它会让我产生
NullPointerException
。我怎样才能解决这个问题

这是我的密码:

主要社科院:

import java.io.*;
import java.util.Scanner; // Import the Scanner class to read text files


public class Main {
    public static void main(String[] args) throws IOException {
        int i = 0;
        /* Start with the empty list. */
        LinkedList list = new LinkedList(args);
        int id1 = 0,year1 = 0,count1 = 0,price1 = 0;
        String name1 = "",singer1 = "";

        //The contents of data.txt have been loaded into the program.
        try {
            Scanner scan = new Scanner(new File(args[1]));
            while (scan.hasNextLine()) {

                String data = scan.nextLine();
                String[] readedData = data.split(";");
                LinkedList.insert(list,id1 = Integer.parseInt(readedData[0]),price1 = Integer.parseInt(readedData[1]),name1 = readedData[2],singer1 = readedData[3],year1 = Integer.parseInt(readedData[4]),count1 = Integer.parseInt(readedData[5]));
            }
            scan.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }

        //The object required to write to the file has been created.
        //FileWriter myWriter = new FileWriter(args[2]);
        PrintStream output = new PrintStream(args[2]);

        //The input.txt file has started to be read.
        try {
            Scanner scan = new Scanner(new File(args[0]));
            while (scan.hasNextLine()) {
                String data = scan.nextLine();

                // First, split on whitespace
                //String[] parts = data.split("(?<!\"\\w\")\\s+(?!\\w+\")"); //Alternate Solution

                String[] parts = data.split("\\s(?=\\w+:)");
                String[] parts1 = data.split("(?<!\"\\w\")\\s+(?!\\w+\")");
                String command1 = parts1[0];

                // The first element in the array is the command
                String command = parts[0];
                // Split the remaining elements on ':'
                String[] keyVal;
                String key = " ";
                String value= " ";
                for (i = 1; i < parts.length; i++) {
                    keyVal = parts[i].split(":");
                    if (keyVal.length == 2) {
                        key = keyVal[0];
                        value = keyVal[1];
                        switch (key) {
                            case "id" -> id1 = Integer.parseInt(value);
                            case "name" -> name1 = value.substring(1, value.length() - 1);
                            case "singer" -> singer1 = value.substring(1, value.length() - 1);
                            case "year" -> year1 = Integer.parseInt(value);
                            case "count" -> count1 = Integer.parseInt(value);
                            case "price" -> price1 = Integer.parseInt(value);
                        }
                    }
                }
                switch (command1) {
                    case "Add" -> {
                        LinkedList.insert(list, id1, price1, name1, singer1, year1, count1);                //DONE!
                        output.print("New CD added id: "+id1+" name: "+name1);
                        output.println();
                    }
                    case "Search" -> {
                        output.print("List:\n");
                        String[] key1 = command.split(" ");
                        String SearchKey = key1[1];
                        SearchKey = SearchKey.substring(1, SearchKey.length() - 1);
                        LinkedList.searchAndFind(list,SearchKey);
                    }
                    case "Remove" -> {
                        LinkedList.deleteNode(list,LinkedList.searchPosition(list,id1));                  //DONE!
                        output.print("CD removed id: "+id1);
                        output.println();
                    }
                    case "List" -> {
                        output.print("List:\n");
                        LinkedList.printList(list);                                                       //DONE!
                    }
                    case "Edit" -> {
                        output.print("Edit CD id: "+id1);
                        output.println();
                        switch (key) {
                            case "singer" -> LinkedList.editSinger(list, id1, singer1);
                            case "name" -> LinkedList.editName(list, id1, name1);
                            case "year" -> LinkedList.editYear(list, id1, year1);                         //DONE!
                            case "count" -> LinkedList.editCount(list, id1, count1);
                            case "price" -> LinkedList.editPrice(list, id1, price1);
                        }
                    }
                    case ("Sell") -> {
                        LinkedList.sell(list,id1);
                        output.print("CD Sold. ID: "+id1);                                                //DONE!
                        output.println();
                    }
                    case "Quit" -> {
                        output.print("Quit");
                        output.println();
                        output.print("Cash :"+LinkedList.cash);
                        output.println();
                    }
                }
            }
            output.close();
            scan.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }

        //LinkedList.printList(list);
    }
}
import java.io.*;
导入java.util.Scanner;//导入Scanner类以读取文本文件
公共班机{
公共静态void main(字符串[]args)引发IOException{
int i=0;
/*从空列表开始*/
LinkedList=新的LinkedList(args);
int id1=0,year1=0,count1=0,price1=0;
字符串名称1=“”,singer1=“”;
//data.txt的内容已加载到程序中。
试一试{
扫描仪扫描=新扫描仪(新文件(args[1]);
while(scan.hasNextLine()){
字符串数据=scan.nextLine();
字符串[]readedData=data.split(“;”);
LinkedList.insert(list,id1=Integer.parseInt(readedData[0]),price1=Integer.parseInt(readedData[1]),name1=readedData[2],singer1=readedData[3],year1=Integer.parseInt(readedData[4]),count1=Integer.parseInt(readedData[5]);
}
scan.close();
}catch(filenotfounde异常){
System.out.println(“发生错误”);
e、 printStackTrace();
}
//已创建写入文件所需的对象。
//FileWriter myWriter=新的FileWriter(args[2]);
PrintStream输出=新的PrintStream(参数[2]);
//已开始读取input.txt文件。
试一试{
扫描仪扫描=新扫描仪(新文件(args[0]);
while(scan.hasNextLine()){
字符串数据=scan.nextLine();
//首先,在空格上分开

//String[]parts=data.split((?问题是,字符串数组
args
main.java的主要方法的一部分

如何创建要写入LinkedList类中文件的对象

您可以做的是将LinkedList.java的构造函数更改为

public LinkedList(String[] args) throws IOException {
     this.args = args;
}
…并在类中使用它,但我们将使用PrintStream,因为它当然也有所有的方法。
printf()
println()
,等等

import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.MissingFormatArgumentException;

public class LinkedList {
    Node head; // head of list

    private String[] args;        

    public LinkedList(String[] args) throws IOException {
         this.args = args;
    }

static class Node {

    int id;
    int year;
    int count;
    int price;
    String name;
    String singer;

    Node next;

    // Constructor
    Node(int i, int p, String n, String s, int y, int c) {
        id = i;
        year = y;
        count = c;
        price = p;
        name = n;
        singer = s;

        next = null;
    }
}

public static LinkedList insert(LinkedList list, int i,int p, String n, String s, int y,int c)
{
    // Create a new node with given data
    Node new_node = new Node(i,p,n,s,y,c);
    new_node.next = null;

    // If the Linked List is empty,
    // then make the new node as head
    if (list.head == null) {
        list.head = new_node;
    }
    else {
        // Else traverse till the last node
        // and insert the new_node there
        Node last = list.head;
        while (last.next != null) {
            last = last.next;
        }

        // Insert the new_node at last node
        last.next = new_node;
    }

    // Return the list by head
    return list;
}

public static void printList(LinkedList list)
{
    PrintWriter writer = new PrintWriter(Files.newBufferedWriter(Paths.get(args[2])));
    Node currNode = list.head;

    writer.printf("%s %10s %30s %25s %15s %10s", "ID", "Price", "Name", "Singer", "Year", "Count");
    writer.println("\n-------------------------------------------------------------------------------------------------");
    // Traverse through the LinkedList
    while (currNode != null) {
        // Print the data at current node
        writer.printf("%s %10s %30s %25s %15s %10s", currNode.id, currNode.price, currNode.name, currNode.singer, currNode.year, currNode.count);

        // Go to next node
        currNode = currNode.next;
        writer.println();
    }
    writer.println();
}

public static void deleteNode(LinkedList list ,int position)
{
    // If linked list is empty
    if (list.head == null)
        return;

    // Store head node
    Node temp = list.head;

    // If head needs to be removed
    if (position == 0)
    {
        list.head = temp.next;   // Change head
        return;
    }

    // Find previous node of the node to be deleted
    for (int i=0; temp!=null && i<position-1; i++)
        temp = temp.next;

    // If position is more than number of nodes
    if (temp == null || temp.next == null)
        return;

    // Node temp->next is the node to be deleted
    // Store pointer to the next of node to be deleted
    Node next = temp.next.next;

    temp.next = next;  // Unlink the deleted node from list
}

static int search = 0;
static int cash = 0;
public static int searchPosition(LinkedList list, int x)
{
    search = 0;
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            break;
        }
        current = current.next;
        search++;
    }
    return search;
}

public static int sell(LinkedList list, int x)
{
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            cash = cash + current.price;
            break;
        }
        current = current.next;
    }
    return cash;
}

public static void editName(LinkedList list, int x, String a)
{
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            current.name = a;
            break;
        }
        current = current.next;
    }
}
public static void editSinger(LinkedList list, int x, String a)
{
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            current.singer = a;
            break;
        }
        current = current.next;
    }
}
public static void editYear(LinkedList list, int x, int a)
{
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            current.year = a;
            break;
        }
        current = current.next;
    }
}
public static void editCount(LinkedList list, int x, int a)
{
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            current.count = a;
            break;
        }
        current = current.next;
    }
}
public static void editPrice(LinkedList list, int x, int a)
{
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            current.price = a;
            break;
        }
        current = current.next;
    }
}
public static void searchAndFind(LinkedList list, String a)
{
    Node current = list.head;    //Initialize current
    PrintWriter writer = new PrintWriter(Files.newBufferedWriter(Paths.get(args[2])));

    writer.printf("%s %10s %30s %25s %15s %10s", "ID", "Price", "Name", "Singer", "Year", "Count");
    writer.println("\n-------------------------------------------------------------------------------------------------");
    while (current != null)
    {
        if (current.name.contains(a)){
            System.out.printf("%s %10s %30s %25s %15s %10s", current.id, current.price, current.name, current.singer, current.year, current.count);
            System.out.println();
        }
        current = current.next;
    }
}
}
导入java.io.PrintWriter;
导入java.nio.file.Files;
导入java.nio.file.path;
导入java.io.IOException;
导入java.util.MissingFormatArgumentException;
公共类链接列表{
节点头;//列表头
私有字符串[]args;
公共LinkedList(字符串[]args)引发IOException{
this.args=args;
}
静态类节点{
int-id;
国际年;
整数计数;
国际价格;
字符串名;
弦乐歌手;
节点下一步;
//建造师
节点(整数i,整数p,字符串n,字符串s,整数y,整数c){
id=i;
年份=y;
计数=c;
价格=p;
name=n;
辛格=s;
next=null;
}
}
公共静态链接列表插入(链接列表,int i,int p,字符串n,字符串s,int y,int c)
{
//使用给定数据创建新节点
Node new_Node=新节点(i,p,n,s,y,c);
new_node.next=null;
//如果链接列表为空,
//然后将新节点作为头
if(list.head==null){
list.head=新节点;
}
否则{
//否则将遍历到最后一个节点
//然后在那里插入新的_节点
节点last=list.head;
while(last.next!=null){
last=last.next;
}
//在最后一个节点插入新的_节点
last.next=新节点;
}
//按标题返回列表
退货清单;
}
公共静态无效打印列表(LinkedList列表)
{
PrintWriter writer=newPrintWriter(Files.newBufferedWriter(path.get(args[2]));
节点currNode=list.head;
writer.printf(“%s%10s%30s%25s%15s%10s”、“ID”、“Price”、“Name”、“Singer”、“Year”、“Count”);
writer.println(“\n-------------------------------------------------------------------------------------------------------------------------”;
//遍历LinkedList
while(currNode!=null){
//打印当前节点的数据
writer.printf(“%s%10s%30s%25s%15s%10s”,currNode.id,currNode.price,currNode.name,currNode.singer,currNode.year,currNode.count);
//转到下一个节点
currNode=currNode.next;
writer.println();
}
writer.println();
}
公共静态void deleteNode(链接列表,int位置)
{
//如果链接列表为空
if(list.head==null)
返回;
//存储头节点
节点温度=list.head;
//如果需要移除头部
如果(位置==0)
{
list.head=temp.next;//更改head
返回;
}
//查找要删除的节点的上一个节点
for(int i=0;temp!=null&&inxt)是要删除的节点
//存储指向要删除的下一个节点的指针
Node next=temp.next.next;
temp.next=next;//取消已删除节点与列表的链接
}
静态整数搜索=0;
静态整数现金=0;
公共静态整型搜索位置(链接列表,整型x)
{
搜索=0;
节点当前=list.head;//初始化当前
while(当前!=null)
{
if(current.id==x){
打破
}
当前=当前。下一步;
搜索++;
}
返回搜索;
}
公共静态int sell(LinkedList,int x)
{
节点当前=list.head;//初始化当前
while(当前!=null)
{
if(current.id==x){
现金=现金+当前价格;
打破
}
当前=当前。下一步;
}
返还现金;
}
公共静态无效editName(LinkedList l
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.MissingFormatArgumentException;

public class LinkedList {
    Node head; // head of list

    private String[] args;        

    public LinkedList(String[] args) throws IOException {
         this.args = args;
    }

static class Node {

    int id;
    int year;
    int count;
    int price;
    String name;
    String singer;

    Node next;

    // Constructor
    Node(int i, int p, String n, String s, int y, int c) {
        id = i;
        year = y;
        count = c;
        price = p;
        name = n;
        singer = s;

        next = null;
    }
}

public static LinkedList insert(LinkedList list, int i,int p, String n, String s, int y,int c)
{
    // Create a new node with given data
    Node new_node = new Node(i,p,n,s,y,c);
    new_node.next = null;

    // If the Linked List is empty,
    // then make the new node as head
    if (list.head == null) {
        list.head = new_node;
    }
    else {
        // Else traverse till the last node
        // and insert the new_node there
        Node last = list.head;
        while (last.next != null) {
            last = last.next;
        }

        // Insert the new_node at last node
        last.next = new_node;
    }

    // Return the list by head
    return list;
}

public static void printList(LinkedList list)
{
    PrintWriter writer = new PrintWriter(Files.newBufferedWriter(Paths.get(args[2])));
    Node currNode = list.head;

    writer.printf("%s %10s %30s %25s %15s %10s", "ID", "Price", "Name", "Singer", "Year", "Count");
    writer.println("\n-------------------------------------------------------------------------------------------------");
    // Traverse through the LinkedList
    while (currNode != null) {
        // Print the data at current node
        writer.printf("%s %10s %30s %25s %15s %10s", currNode.id, currNode.price, currNode.name, currNode.singer, currNode.year, currNode.count);

        // Go to next node
        currNode = currNode.next;
        writer.println();
    }
    writer.println();
}

public static void deleteNode(LinkedList list ,int position)
{
    // If linked list is empty
    if (list.head == null)
        return;

    // Store head node
    Node temp = list.head;

    // If head needs to be removed
    if (position == 0)
    {
        list.head = temp.next;   // Change head
        return;
    }

    // Find previous node of the node to be deleted
    for (int i=0; temp!=null && i<position-1; i++)
        temp = temp.next;

    // If position is more than number of nodes
    if (temp == null || temp.next == null)
        return;

    // Node temp->next is the node to be deleted
    // Store pointer to the next of node to be deleted
    Node next = temp.next.next;

    temp.next = next;  // Unlink the deleted node from list
}

static int search = 0;
static int cash = 0;
public static int searchPosition(LinkedList list, int x)
{
    search = 0;
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            break;
        }
        current = current.next;
        search++;
    }
    return search;
}

public static int sell(LinkedList list, int x)
{
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            cash = cash + current.price;
            break;
        }
        current = current.next;
    }
    return cash;
}

public static void editName(LinkedList list, int x, String a)
{
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            current.name = a;
            break;
        }
        current = current.next;
    }
}
public static void editSinger(LinkedList list, int x, String a)
{
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            current.singer = a;
            break;
        }
        current = current.next;
    }
}
public static void editYear(LinkedList list, int x, int a)
{
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            current.year = a;
            break;
        }
        current = current.next;
    }
}
public static void editCount(LinkedList list, int x, int a)
{
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            current.count = a;
            break;
        }
        current = current.next;
    }
}
public static void editPrice(LinkedList list, int x, int a)
{
    Node current = list.head;    //Initialize current
    while (current != null)
    {
        if (current.id == x){
            current.price = a;
            break;
        }
        current = current.next;
    }
}
public static void searchAndFind(LinkedList list, String a)
{
    Node current = list.head;    //Initialize current
    PrintWriter writer = new PrintWriter(Files.newBufferedWriter(Paths.get(args[2])));

    writer.printf("%s %10s %30s %25s %15s %10s", "ID", "Price", "Name", "Singer", "Year", "Count");
    writer.println("\n-------------------------------------------------------------------------------------------------");
    while (current != null)
    {
        if (current.name.contains(a)){
            System.out.printf("%s %10s %30s %25s %15s %10s", current.id, current.price, current.name, current.singer, current.year, current.count);
            System.out.println();
        }
        current = current.next;
    }
}
}
import java.io.File;  // Import the File class
import java.io.FileNotFoundException;  // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
import java.io.FileWriter;   // Import the FileWriter class
import java.io.IOException;  // Import the IOException class to handle errors

public class Main {
public static void main(String[] args) throws IOException {
    int i = 0;
    /* Start with the empty list. */
    LinkedList list = new LinkedList(args);
    int id1 = 0,year1 = 0,count1 = 0,price1 = 0;
    String name1 = "",singer1 = "";

    //The contents of data.txt have been loaded into the program.
    try {
        Scanner scan = new Scanner(new File(args[1]));
        while (scan.hasNextLine()) {

            String data = scan.nextLine();
            String[] readedData = data.split(";");
            LinkedList.insert(list,id1 = Integer.parseInt(readedData[0]),price1 = Integer.parseInt(readedData[1]),name1 = readedData[2],singer1 = readedData[3],year1 = Integer.parseInt(readedData[4]),count1 = Integer.parseInt(readedData[5]));
        }
        scan.close();
    } catch (FileNotFoundException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }

    //The object required to write to the file has been created.
    FileWriter myWriter = new FileWriter(args[2]);

    //The input.txt file has started to be read.
    try {
        Scanner scan = new Scanner(new File(args[0]));
        while (scan.hasNextLine()) {
            String data = scan.nextLine();

            // First, split on whitespace
            //String[] parts = data.split("(?<!\"\\w\")\\s+(?!\\w+\")"); //Alternate Solution

            String[] parts = data.split("\\s(?=\\w+:)");
            String[] parts1 = data.split("(?<!\"\\w\")\\s+(?!\\w+\")");
            String command1 = parts1[0];

            // The first element in the array is the command
            String command = parts[0];
            // Split the remaining elements on ':'
            String[] keyVal;
            String key = " ";
            String value= " ";
            for (i = 1; i < parts.length; i++) {
                keyVal = parts[i].split(":");
                if (keyVal.length == 2) {
                    key = keyVal[0];
                    value = keyVal[1];
                    switch (key) {
                        case "id" -> id1 = Integer.parseInt(value);
                        case "name" -> name1 = value.substring(1, value.length() - 1);
                        case "singer" -> singer1 = value.substring(1, value.length() - 1);
                        case "year" -> year1 = Integer.parseInt(value);
                        case "count" -> count1 = Integer.parseInt(value);
                        case "price" -> price1 = Integer.parseInt(value);
                    }
                }
            }
            switch (command1) {
                case "Add" -> {
                    LinkedList.insert(list, id1, price1, name1, singer1, year1, count1);                //DONE!
                    myWriter.write("New CD added id: "+id1+" name: "+name1);
                }
                case "Search" -> {
                    String[] key1 = command.split(" ");
                    String SearchKey = key1[1];
                    SearchKey = SearchKey.substring(1, SearchKey.length() - 1);
                    LinkedList.searchAndFind(list,SearchKey);
                }
                case "Remove" -> {
                    LinkedList.deleteNode(list,LinkedList.searchPosition(list,id1));                  //DONE!
                    myWriter.write("CD removed id: "+id1);
                }
                case "List" -> {
                    LinkedList.printList(list);                                                       //DONE!
                }
                case "Edit" -> {
                    switch (key) {
                        case "singer" -> LinkedList.editSinger(list, id1, singer1);
                        case "name" -> LinkedList.editName(list, id1, name1);
                        case "year" -> LinkedList.editYear(list, id1, year1);                         //DONE!
                        case "count" -> LinkedList.editCount(list, id1, count1);
                        case "price" -> LinkedList.editPrice(list, id1, price1);
                    }
                }
                case ("Sell") -> {
                    LinkedList.sell(list,id1);
                    myWriter.write("CD Sold. ID: "+id1);                                              //DONE!
                }
                case "Quit" -> {
                    myWriter.write("Quit");
                    myWriter.write(LinkedList.cash);
                }
            }
        }
        myWriter.close();
        scan.close();
    } catch (FileNotFoundException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }

    //LinkedList.printList(list);
}
}