在搜索现有成员的链表时返回布尔结果 - java

问题描述 投票:0回答:4

我正在为类编写一个程序,将用户输入无限循环并接受三个不同的命令(添加x,删除x,存在x)+一个整数值。当用户输入“exists x”时,程序应该返回一个布尔结果,指示该值是否存在于列表中。

添加x和删除x的方法工作正常,但在搜索列表时,我无法生成“真/假”结果。我尝试了几种不同的方法,这里是我目前使用的x方法:

public class LinkedNode {
public int x;         // The data value

public LinkedNode next;  // Reference to the next LinkedNode

// Default constructor
LinkedNode() {
    next = null;
}

// Constructor that initializes the data values
LinkedNode(int x) {
    this.x = x;
}

public void display() {
    System.out.print(x + " ");
}

}


public class Set {

public LinkedNode firstLink;

Set(){
    firstLink = null;
}

public boolean isEmpty() {
    return (firstLink == null); //nothing in Set yet
}

public void add(int x) {
    LinkedNode newLink = new LinkedNode(x);

    newLink.next = firstLink;
    firstLink = newLink;
}

public boolean exists(int x) {

   LinkedNode theLink = firstLink;

   while (theLink.x != x) { // keep searching until match
       if (theLink.next == null) // we've hit the end without a match, return false
               return false;
           else
               theLink = theLink.next;
       }
       return true;
}

public LinkedNode delete(int x) {
    LinkedNode currentLink = firstLink;
    LinkedNode previousLink = firstLink;

    while (currentLink.x != x) { // search while no match is found
        if (currentLink.next == null) {
            return null; // not found
    }   else { // moves to next LinkedNode
        previousLink = currentLink;
        currentLink = currentLink.next;
        }
    }
    if (currentLink == firstLink) { // first link matches search
        firstLink = firstLink.next; // delete link
    }
    else { // any other link is a match except firstLink
        previousLink.next = currentLink.next;
    }
    return currentLink;
}

public String toString() {
    String str = "";

    LinkedNode cur = firstLink;
    while (cur!=null) {
        str += cur.x + " ";
        cur = cur.next;
    }
    return str;
}

}

这是我的测试/驱动程序:

import java.util.*;

public class Test {

public static void main(String[] args) {
    Set dataSet = new Set();
    Scanner input = new Scanner(System.in);


        while (1<2) { // infinite loop on purpose

        String command, value;
        System.out.print("Enter command: ");
        String line = input.nextLine();
        String [] userInput = line.split(" ");
        command = userInput [0];
        value = userInput [1];

        if (!command.equalsIgnoreCase("add") && !command.equalsIgnoreCase("del") && !command.equalsIgnoreCase("exists")){
            System.out.println("Invalid command.");
            System.out.println("Valid commands are: add x, del x & exists x");
            System.out.print("Enter command: ");
        }
        else if (command.equalsIgnoreCase("add")) {
            dataSet.add(Integer.parseInt(value));
            System.out.println(dataSet);
        }
        else if (command.equalsIgnoreCase("del")){
            dataSet.delete(Integer.parseInt(value));
            System.out.println(dataSet);
        }
        else if (command.equalsIgnoreCase("exists"));{
            dataSet.exists(Integer.parseInt(value));
            System.out.println(dataSet);

        }
    }

如果搜索的值存在于链接中,我希望程序显示“true / false”,类似于添加/删除后显示当前列表的方式。关于我哪里出错的任何暗示?

Enter command: add 3
3 
Enter command: add 1
1 3 
Enter command: add 20
20 1 3 
Enter command: exists 20
Enter command: 
java linked-list user-input boolean-expression abstract-data-type
4个回答
2
投票

你真的很亲密,你的代码实际上工作正常,只是你有一个小错字在那里扔掉它!

else if (command.equalsIgnoreCase("exists"));{

这段代码最后包含一个分号,遗憾的是这是有效的Java,因此不会抛出任何编译时异常。虽然你应该得到警告说:

Blockquote'if'语句有空体

另外,因为这是在执行每个循环,所以结果会显示两次,所以删除分号应该可以解决问题:

else if (command.equalsIgnoreCase("exists")) {
    System.out.println(dataSet.exists(Integer.parseInt(value)));
    System.out.println(dataSet);
}

在代码示例中,为了清楚起见,我打印了LinkedList中是否存在值的结果。

注意:每次要求用户输入命令以允许拆分不同的命令时,可能还需要添加新行:

System.out.print("\nEnter command: ");

再一次,这纯粹是装饰性的,只是让你的输出更具可读性!


0
投票

感谢Andreas&M H的帮助 - 下面是产生预期输出的原因:

else if (command.equalsIgnoreCase("exists")){
    if(dataSet.exists(Integer.parseInt(value)))
    {
      System.out.println("true");
    }
    else
    {
       System.out.println("false");
    }

}

0
投票

首先,您应该打印所需的值,这将帮助您检查方法是否有效。

else if(command.equalsIgnoreCase("exists"){
   if(dataSet.exists(Integer.parseInt(value)))
     System.out.println("true");
   else
      System.out.println("false");`enter code here`

如果列表(Set)为空,您也应该复制,可能代码不起作用。此外,如果您使用局部变量作为私有,那将更正确。更改它们并为它们编写方法setX(x),getX()。关于方法存在,我认为更好的代码将是这一个:

public Boolean exists(int x){
    LinkedNode theLink = firstLink;
    Boolean resul = false;
    while(!isEmpty() && theLink.getNext() != null){
         if(link.getX() != x)
            theLink = theLink.getNext(); 
         else
            resul = true;
    }
    return resul; 

如果你不想将本地的linkedNode变量设置为私有,只需通过.next和.x更改getNext和getX。尝试理解代码,下次自己尝试更多时间,这是学习的唯一方法。


-1
投票

你的函数可能正在返回正确的bool值。但是你没有打印结果。您可以使用以下类型的代码。

if(dataSet.exists(Integer.parseInt(value))==True)
{
     system.out.println("exists");
}
else
{
     system.out.println("not exists");
}

上面的代码只是一个伪代码。

© www.soinside.com 2019 - 2024. All rights reserved.