java - 在对象列表中搜索名称的例程...帮助。 java

标签 java

在这里,我正在创建对象:一个神经元和一个突触,它有两个子类:主要子类、次要子类。我试图查看突触列表,看看我输入的目的地是否与列表中已有的突触名称相匹配。这是我为此使用的具体代码:

public static Synapse findSynapse( String n ) {
        for (Synapse s: synapses) {
            if (s.name.equals(n)) {
                return s;
            }
        }
        return null;
    }

我的问题:为什么这不起作用?该程序的其余部分工作正常,附在下面。

// NeuronNetwork.java
/** A Java program to read and output a textual description of a neuron network.
 *  @Author Douglas W. Jones
 *  @Author CJH
 *  @Version Mar. 4, 2015
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.Scanner;

// Utility classes

/** Error reporting methods
 */
class Errors {
    static void fatal( String message ) {
        System.err.println( "Fatal error: " + message );
        System.exit( 1 );
    }
    static void warning( String message ) {
        System.err.println( "Error: " + message );
    }
}

/** Input scanning support methods
 */
class ScanSupport {
    /** Force there to be a line end here, complain if not
     */
    static void lineEnd( Scanner sc, String message ) {
        String skip = sc.nextLine();
        if (!"".equals( skip )) {
            // Bug:  do we want to allow comments here
            Errors.warning( message + " -- expected a newline" );
        }
        // Bug:  what if sc.nextLine() was illegal (illegal state)
    }

    /** Get the next float, or complain if there isn't one
     */
    static String nextName( Scanner sc, String message ) {
        if (sc.hasNext( "[a-zA-Z]\\w*" )) {
            return sc.next();
        } else {
            Errors.warning( message + " -- expected a name" );
            return null;
        }
    }

    /** Get the next float, or complain if there isn't one
     */
    static float nextFloat( Scanner sc, String message ) {
        if (sc.hasNextFloat()) {
            return sc.nextFloat();
        } else {
            Errors.warning( message + " -- expected a number" );
            return 99.99f;
        }
    }
}

// Simulation classes

/** Neurons are the vertices in the neuron network
 *  @see Synapse
 */
class Neuron {
    String name;            // name of this neuron
    private float threshold;    // voltage at which the neuron fires
    private float voltage;      // voltage at the given time
    private float time;     // (see above)

    private LinkedList <Synapse> synapses;  // the outputs of this neuron

    public class IllegalNameException extends Exception {}

    // initializer
    public Neuron( Scanner sc ) throws IllegalNameException {
        // scan and process one neuron
        name = ScanSupport.nextName( sc, "Neuron ??" );
        if (name == null) {
            sc.nextLine();
            throw new IllegalNameException();
        }
        if (NeuronNetwork.findNeuron( name ) != null) {
            Errors.warning(
                "Neuron " + name + " -- duplicate declaration"
            );
            sc.nextLine();
            throw new IllegalNameException();
        }
        threshold = ScanSupport.nextFloat( sc, "Neuron " + name );
        voltage = ScanSupport.nextFloat( sc, "Neuron " + name );
        time = 0.0f;
        ScanSupport.lineEnd( sc, "Neuron " + name );
    }

    // other methods
    public String toString() {
        return (
            "Neuron " +
            name +
            " " +
            threshold +
            " " +
            voltage
        );
    }
}

/** Synapses join neurons
 *  @see Neuron
 */
abstract class Synapse {
    Neuron source;
    static String name;
    static String sourceName;
    static String dstName;
    static Float delay;
    static Float strength;
    Neuron destination;
    static Synapse altDestination;  // destination which is a synapse

    /** Determine which type of Synapse, the call constructor to create new 
     *  object based on attributes
     */     
    static Synapse getType( Scanner sc ) {
        name = sc.next();   
        sourceName = ScanSupport.nextName(sc, 
            "Synapse " + name + " ??" 
        );
        dstName = ScanSupport.nextName(sc,
            "Synapse " + name + " " +
            sourceName + " ??"
        );

        delay = ScanSupport.nextFloat( sc,
            "Synapse " + name + " " +  
            ( dstName != null ? dstName : "??" ) +
            " ??"
        );
        strength = ScanSupport.nextFloat( sc,
            "Synapse " + name + " " +
            ( sourceName != null ? sourceName : "??" ) +
            " " +
            ( dstName != null ? dstName : "??" ) +
            " " + delay + " ??"
        );
        altDestination = NeuronNetwork.findSynapse( dstName );
        if( altDestination == null ) {
            return new PrimarySynapse( sc );
        }else{
            return new SecondarySynapse( sc );
        }
    }
}
class SecondarySynapse extends Synapse { 
    String theName = name;
    String theSource = sourceName;
    String theDst = dstName;
    Float theDelay = delay;
    Float theStrength = strength;
    Synapse altDst = altDestination; 
    // interface or abstract??
    public SecondarySynapse( Scanner sc ) {
        // check correctness of fields
        if (theName == null) {
            Errors.fatal( "Synapse Name is Null "); 
            sc.nextLine();
        }
        source = NeuronNetwork.findNeuron( theSource );
        if (source == null) {
            Errors.warning(
                "Synapse " + theName + " " +
                ( theSource != null ? theSource : "??" ) +
                " " +
                ( theDst != null ? theDst : "??" ) +
                " -- no such source"
            );
        }
        if ( altDst == null) {
            Errors.warning(
                "Synapse " + theName + " " +
                ( theSource != null ? theSource : "??" ) +
                " " +
                ( theDst != null ? theDst : "??" ) +
                " -- no such destination"
            );
        }
        if (theDelay < 0.0f) {
            Errors.warning(
                "Synapse " + theName + " " +
                ( theSource != null ? theSource : "??" ) +
                " " +
                ( theDst != null ? theDst : "??" ) +
                " " + theDelay + " " + theStrength +
                " -- illegal negative delay"
            );
            theDelay = 99.99f;
        }
    }
    public String toString() {
        return (
            "Synapse " + theName + " " +
            ( source != null ? source.name : "---" ) +
            " " +
            ( altDst != null ? altDst.name : "---" ) +
            " " + theDelay + " " + theStrength
        );
    }
}
class PrimarySynapse extends Synapse {      
    String theName = name;
    String theSource = sourceName;
    String theDst = dstName;
    Float theDelay = delay;
    Float theStrength = strength;
    // interface ortract??
    public PrimarySynapse( Scanner sc ) {
        // check correctness of fields
        if (theName == null) {
            sc.nextLine();
            Errors.fatal(
                "Synapse name is null"
            );
        }
        source = NeuronNetwork.findNeuron( theSource );
        if (source == null) {
            Errors.warning(
                "Synapse " + name + " " +
                ( theSource != null ? theSource : "??" ) +
                " " +
                ( theDst != null ? theDst : "??" ) +
                " -- no such source"
            );
        }
        destination = NeuronNetwork.findNeuron( theDst );
        if (destination == null) {
            Errors.warning(
                "Synapse " + name + " " +
                ( sourceName != null ? sourceName : "??" ) +
                " " +
                ( dstName != null ? dstName : "??" ) +
                " -- no such destination"
            );
        }
        if (theDelay < 0.0f) {
            Errors.warning(
                "Synapse " + theName + " " +
                ( theSource != null ? theSource : "??" ) +
                " " +
                ( theDst != null ? theDst : "??" ) +
                " " + theDelay + " " + theStrength +
                " -- illegal negative delay"
            );
            theDelay = 99.99f;
        }
    }
    public String toString() {
        return (
            "Synapse " + theName + " " +
            ( source != null ? source.name : "??" ) + " " +
            ( destination != null ? destination.name : "??" ) + 
            " " + theDelay + " " + theStrength
        );
    }
}
/** NeuronNetwork is the main class that builds the whole model
 *  @see Neuron
 *  @see Synapse
 */
public class NeuronNetwork {

    // the sets of all neurons and all synapses
    static LinkedList <Neuron> neurons
        = new LinkedList <Neuron> ();
    static LinkedList <Synapse> synapses
        = new LinkedList <Synapse> ();

    /** Same lookup method as below but for Synapse
     */
    public static Synapse findSynapse( String n ) {
        for (Synapse s: synapses) {
            if (s.name.equals(n)) {
                return s;
            }
        }
        return null;
    }
    /** Look up s in neurons, find that Neuron if it exists
     *  return null if not.
     */
    public static Neuron findNeuron( String s ) {
        for (Neuron n: neurons) {
            if (n.name.equals(s)) {
                return n;
            }
        }
        return null;
    }
    /** Initialize the neuron network by scanning its description
     */
    static void initializeNetwork( Scanner sc ) {
        while (sc.hasNext()) {
            String command = sc.next();
            if ("neuron".equals( command )) {
                try {
                    neurons.add( new Neuron( sc ) );
            } catch (Neuron.IllegalNameException e) {
                    // no action required
                }
            } else if ("synapse".equals( command )) {
                if( sc.hasNext( "-" ) || sc.hasNext( "[a-zA-Z]\\w*" )) {
                    synapses.add ( Synapse.getType( sc ) );
                }
            } else {
                Errors.warning( command + " -- what is that" );
                sc.nextLine();
            }
        }
    }

    /** Print out the neuron network from the data structure
     */
    static void printNetwork() {
        for (Neuron n:neurons) {
            System.out.println( n.toString() );
        }
        for (Synapse s:synapses) {
            System.out.println( s.toString() );
        }
    }

    /** Main program
     * @see initializeNetwork
     */
    public static void main(String[] args) {
        try {
            if (args.length < 1) {
                Errors.fatal( "-- missing file name" );
            }
            if (args.length > 1) {
                Errors.fatal( "-- too many arguments" );
            }
            initializeNetwork( new Scanner(new File(args[0])) );
        } catch (FileNotFoundException e) {
            Errors.fatal( "" + args[0] + " -- file not found" );
        }
        printNetwork();
    }
}

最佳答案

您的 Synapse 类将大多数变量定义为静态的。 static关键字意味着该变量总体上属于该类,而不是特定的实例。因此,当您将 name 字符串设置为某个字符串时,它就是您创建的所有突触的名称(所有突触都具有相同的名称)。所以,当你搜索一个名字时,很可能会失败。

您应该从名称变量中删除 static 关键字。

关于java - 在对象列表中搜索名称的例程...帮助。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35906422/

相关文章:

java - Jboss 7.1.1 + Windows 7 (64位) + JDK 7 1.7.07 (64位) 启动失败

java - 计算素数(新手)

java - HashMap 中的键排序是什么?

java - 使用安全连接时的 Jetty 9 WebSocket 客户端问题

java - 如何根据每个字符串的不同部分对字符串数组进行排序?

java - JNDI 中的 LdapContext 与 dircontext

java - MouseListener 未提供准确的鼠标位置

java - 验证简单的时间日期格式 ? (yyyy-MM-dd'T'HH :mm:ss)

java - 如何从java应用程序外部运行google apps脚本

java - Spring服务应该是可序列化的