根据用户输入从 LinkedList 中获取值

Posted

技术标签:

【中文标题】根据用户输入从 LinkedList 中获取值【英文标题】:Getting values from LinkedList according to user input 【发布时间】:2016-09-25 17:38:32 【问题描述】:

我的实验室代码面临一些问题 我进行了故障排除,发现我的文件读取器/缓冲读取器、Vehicle 方法和 LinkedList 值都没有问题

我发现我在使 if 语句正常工作时遇到问题 我不知道如何比较使用标记器从我的 file.txt 中提取的当前链表数据,以使用 if/else 传递给用户输入的给定字段?

主要方法

package test6;


// import packages
import java.util.LinkedList;
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Lab6 

/**
 * @param args the command line arguments
 */
public static void main(String[] args) 
    // TODO code application logic here

    // Declare variables for reading file 
    FileReader fr = null;
    BufferedReader br = null;
    String inFile = "Vehicle_Records.txt";
    final String INPUT_PROMPT = "\nPlease enter the search word " + "that you would like to obtain more information on:";
    String line;
    StringTokenizer tokenizer;

    // Declare variables to contain the record fields

   String group; 
   String brand; 
   String model; 
   double rate; 

    // Declare and instantiate a new LinkedList
   LinkedList<Vehicle> list = new LinkedList<Vehicle>();

    try 
        // Instantiate FileReader & BufferedReader objects
        fr = new FileReader(inFile);
        br = new BufferedReader(fr);

        //read a line from the file
        line = br.readLine();

        // While line is not null
        while (line != null) 
            // Tokenize the records
            tokenizer = new StringTokenizer(line, ",");
            group = tokenizer.nextToken();
            brand = tokenizer.nextToken();
            model = tokenizer.nextToken();
            rate = Double.parseDouble(tokenizer.nextToken());
            // Create a new Vehicle object of the record
            Vehicle newVehicle = new Vehicle(group, brand, model, rate);
            System.out.println(newVehicle);
             // Add this item object into the LinkedList
            list.add(newVehicle);
            // Read another line from file
            line = br.readLine();

        
        // Close BufferedReader
        br.close();
     
    catch (FileNotFoundException e) 
    
        System.out.println("The file" + inFile + "was not found");
     
    catch (IOException e) 
    
        System.out.println("Reading error!" + e);
     
    finally 
    
        //Check if FileReader is opened
        if (fr != null) 
            try 
                //close FileReader
                fr.close();

             catch (IOException e) 
                System.out.println("Error closing file!");
            
        
    
      // Print out the input prompt

        System.out.println(INPUT_PROMPT);

    try 
    

       // Create readers to read from user input
        //FileReader ufr = new FileReader(INPUT_PROMPT);
        BufferedReader ubr = new BufferedReader(new InputStreamReader (System.in));

       // Read one line from user input
       String uline=ubr.readLine();
        // Loop through all the records in the LinkedList

        for(int i = 0; i< list.size(); i++)
        
        // if the record is the same as the input from user 
        // (Hint: use contains() in String class to check whether 
        // search word is found in the records
         String temp = new String(uline);

        if(list.get(i)== uline.contains(temp))
        
            //print out the information of the vehicle that match user input
            System.out.println(list.get(i));

                  


        

     
    catch(IOException e)
    
        System.out.println(e);
    

    catch (Exception e) 
    
        System.out.println("Input error!" + e);
    
    
//main

车辆类

package lab6;


public class Vehicle 
    // Declare all the variables to contain the fields of a record 
    String group; 
    String brand; 
    String model; 
    double rate; 
// Creates a constructor to store all the fields into the variables 
    public Vehicle(String group, String brand, String model, double rate) 
     
        this.group=group; this.brand=brand; this.model=model; this.rate=rate; 
     
// Create a toString() method to return string in the same delimited 
// format as the input record 
    public String toString() 
     
        return(group+","+brand+","+model+","+rate); 
    

【问题讨论】:

欢迎来到 SO。请花更多时间格式化您的代码——您希望其他人花时间帮助您;所以你应该花点时间让这件事尽可能简单。 StringTokenizer 已弃用,不应在任何新代码中使用。 @David Conrad StringTokenizer 未标记为已弃用。 @Alex 我的意思是在英语意义上已弃用,因为每个人都把它放下并说不要使用它,尽管官方文档也说“StringTokenizer 是一个遗留类,尽管出于兼容性原因而保留不鼓励在新代码中使用它。” @David Conrad,同意你的观点,这是一些澄清。 【参考方案1】:

啊啊啊我终于和我的另一个朋友一起想通了 尽管如此,我还是要感谢你们所有人伸出手来帮助我:')

将我的问题的解决方案发布在这里

//-etc-
   // Create readers to read from user input
    //FileReader ufr = new FileReader(INPUT_PROMPT);
    BufferedReader ubr = new BufferedReader(new InputStreamReader (System.in));

   // Read one line from user input
   String uline=ubr.readLine();
    // Loop through all the records in the LinkedList


    for(int i = 0; i< list.size(); i++)
    
    // if the record is the same as the input from user 
    // (Hint: use contains() in String class to check whether 
    // search word is found in the records

     Vehicle vehicle = list.get(i);

    if(vehicle.group.contains(uline) || 
       vehicle.brand.contains(uline) ||
       vehicle.model.contains(uline))
    
        //print out the information of the vehicle that match user input
        System.out.println(list.get(i));

    

【讨论】:

【参考方案2】:

我假设,因为您查看车辆对象试图找到其四个变量之一的匹配项。您的方法是错误的,因为您正在将对象与字符串进行比较。

相反,您可以在 Vehicle 类中使用 Comparable 接口,您可以在其中简单地比较多个字符串。

编辑:

public class Vehicle implements Comparable<String>

/* This method returns 0 if the search matches
 * Else it return a negative or a positive number*/
@Override
public int compareTo(String o) 
    int cmp = this.getBrand().compareToIgnoreCase(o);
    if(cmp == 0) return cmp;

    cmp = this.getGroup().compareToIgnoreCase(o);
    if(cmp == 0) return cmp;

    cmp = this.getModel().compareToIgnoreCase(o);
    if(cmp == 0) return cmp;
    /* Edited this part to work with doubles */
    try
        cmp = (int)(this.getRate() - Double.parseDouble(o));
    
    catch(NumberFormatException e)
        return cmp;
    

    return cmp;



下面是你如何循环遍历它:

for(int i = 0; i< list.size(); i++)
            if(list.get(i).compareTo(uline) == 0)
            
                System.out.println(list.get(i));

               
        

希望对您有所帮助。

附言。我对此也很陌生:)

【讨论】:

^ 是的,我正在查看存储在 LinkedList 中的变量,是的,我该怎么做?抱歉,我对 java 还是很陌生【参考方案3】:

您的代码不在方法内,因此您遇到了问题。

【讨论】:

你可以从这里学习你的 Java:docs.oracle.com/javase/tutorial/java/javaOO/index.html 我确实有一个 main 方法,我没有在此处声明该方法,因为我忽略了它 x) ,顺便说一句,我已经完成了故障排除,这是我的代码没有生成的唯一原因任何结果都是因为我的 if 语句是错误的。我不知道如何将用户输入与存储在链表中的变量进行比较

以上是关于根据用户输入从 LinkedList 中获取值的主要内容,如果未能解决你的问题,请参考以下文章

在while循环中从用户输入中获取最小值

当用户在输入字段中输入数据时,如何从车把页面获取 jquery 中的输入文本值?

如何根据用户输入参数从 BigQuery 获取结果

js 中怎么从input获取输入的value值

PowerBI:根据度量过滤器从列中获取值

接收消息作为输入并从用户那里获取间隔值