简体   繁体   English

Java 程序。 需要简化 public boolean equals (object B){ is to long。 我不知道如何减少程序那部分的编码

[英]Java Program. Need to simplified public boolean equals (object B){ is to long. I do not how to reduce the coding in that part of my program

I wanted to reduce the coding in public boolean equals (Object B).我想减少公共 boolean 等于(对象 B)中的编码。 The Program is running.程序正在运行。 and output is ok. output 没问题。 Also create a new text file ("outpuPalindrome").同时创建一个新的文本文件(“outpuPalindrome”)。 I was working in this program the entire morning and can find the way to simplified the coding for the boolean equals section following the instructions that I have.我整个早上都在这个程序中工作,并且可以按照我的说明找到简化 boolean 等于部分的编码的方法。 If someone can give an idea how to do it I will appreciated.如果有人能给出一个想法,我将不胜感激。

package charstack;

//import java.io.*; 
//import java.util.*; 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Stack;

/*  StringToStack function reads the string into its private stack.
        Precondition: check if a character is an alphabetic letter
        Postcondition: only alphabetic letters of the string are in the private stack.
        Other characters(like space, digit, punct, etc) can not be in the stack.
*/
public class CharStack {
    private Stack<Character> myCharacters; 
    
    public CharStack(){
        myCharacters = new Stack<>();
    }
    public void StringToStack(String inStr){
        myCharacters = new Stack<>();
        for (Character c: inStr.toCharArray()){
            if (Character.isAlphabetic(c)){
                myCharacters.push(c);
            }
        }
    }
    
    /*  Reverse function empties its private stack out into another stack, 
        causing the order of the characters to be reversed.  Returns this new stack.
        Precondition:  Private stack is not empty.
    Postcondition:  If private stack is empty, displays error and returns.
        Otherwise: Returns new stack containing private stack's
           elements in reverse order.  Private stack is empty.
    */  
    public CharStack Reverse(){
        
        if (myCharacters.empty()){
            System.out.println("Error: CharStack is empty.");
            return null;
        }
        CharStack s = new CharStack();
        while (!myCharacters.empty()){
            s.myCharacters.push(myCharacters.pop());
        }
        return s; //return new CharStack();
    }
    
    
    
    /* IsEqual function tests if both private stack and B's stack are the same.
        Precondition:  Neither stack is empty.
    Postcondition:  If either stack is empty,
                displays error message and returns.
        Otherwise:
            Returns true if both stacks are the same, returns false otherwise.
            Both the private stack and B's stack are empty.
    */  
    @Override
    public boolean equals (Object B){
        
        if (myCharacters.empty()){
            System.out.println("Error: CharStack 1 is empty.");
            return false;
        }
        if (this == B){
            myCharacters = new Stack<>();
            return true; //return true;
        }
        if (B instanceof CharStack){
            CharStack bStack = (CharStack) B;
            if (bStack.myCharacters.empty()){
                System.out.println("Error: CharStack 2 is empty.");
                myCharacters = new Stack<>();
                return false;
            }
            while (!myCharacters.empty()){
                Character cA = myCharacters.pop();
                if (bStack.myCharacters.empty()){
                    myCharacters = new Stack<>();
                    bStack.myCharacters = new Stack<>();
                    return false;
                }
                Character cB = bStack.myCharacters.pop();
                if (cA != cB){
                    myCharacters = new Stack<>();
                    bStack.myCharacters = new Stack<>();
                    return false;
                }
            }
            if (!bStack.myCharacters.empty()){
                bStack.myCharacters = new Stack<>();
                return false;
            }
            return true;
        }
        myCharacters = new Stack<>();
        return false;
    }
    
    /* Postcondition:  Contents of stack have been converted to string on one line.  
       the private stack myCharacters is unchanged.
    */
    @Override
    public String toString(){
        //return "hello";
        StringBuilder sb = new StringBuilder();
        Stack<Character> temp = new Stack<>();
        while (!myCharacters.empty()){
            temp.push(myCharacters.pop());
        }
        while (!temp.empty()){
            Character c = temp.pop();
            myCharacters.push(c);
            sb.append(c);
        }
        return sb.toString();
    }
}

testDriveFile.java测试驱动文件.java

/*prompt user to enter file name for palindrome check
//(use provided palindrome1.txt and palindrome2.txt files)
//read file line by line and use the CharStack class to check 
//if the line is palindrome, you need to call StringToStack() function to 
//push all letters from the line to a CharStack
//output the stack using toString() function
//then call reverse() function to get the reverse of the above CharStack
//call equals() function to check if the contents of two CharStacks 
//are the same and make decision about palindrome
//output all palindrome lines to a file to save them*/

public class CharStackApp {公共 class CharStackApp {

 public static void main(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(System.in);
    System.out.println("Please, enter Palindrome file text to read.");
    String str = input.nextLine();
    File palindrome = new File(str);
    File outputPalindrome = new File("OutputPalindrome");
    PrintWriter writer;
    Scanner fileScanner;
    try{
        fileScanner = new Scanner(palindrome);
        writer = new PrintWriter(outputPalindrome);
    }
    catch (FileNotFoundException e){
        return;
    }
    while (fileScanner.hasNextLine()){
        String file = fileScanner.nextLine().toLowerCase();
        CharStack s = new CharStack();
        
        s.StringToStack(file);// original (ln) yo puse file
        System.out.println(s);
        
        CharStack sRev = new CharStack();
        sRev.StringToStack(file);
        sRev = sRev.Reverse();
        
        if (s.equals(sRev)){
            writer.write(file);
            writer.write("\n");
        }
        writer.close();
    
    }

Yeah, that equals() implementation is way overkill.是的,这equals()实现方式有点矫枉过正。 Just compare the stacks:只需比较堆栈:

@Override
public boolean equals(Object B) {
    if (! (B instanceof CharStack))
        return false;
    CharStack bStack = (CharStack) B;
    return this.myCharacters.equals(bStack.myCharacters);
}

Remember to always implement hashCode() when you implement equals() .请记住在实现hashCode() equals() It will save you a lot of headache later, if you make that a habit.如果你养成这样的习惯,以后会省去很多麻烦。

@Override
public int hashCode() {
    return this.myCharacters.hashCode();
}

Your toString() also seems overly complicated.您的toString()似乎也过于复杂。

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    for (Character c : this.myCharacters)
        sb.append(c);
    return sb.toString();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java程序。 如何在数组中循环“ isLucky”方法?如何在main方法中打印结果? - Java program. How do I loop my "isLucky method through the array? and how do I print the result in the main method? 无法运行我的java .exe程序。 我该如何解决? (“发生Java异常”)和JNI问题 - Can't run my java .exe program. How do I troubleshoot this ? (“A Java exception has occured”) and JNI problem Java程序。 如何通过我的数组循环我的“isLucky”方法? 另外,如何在 main 方法中正确打印我的结果? - Java program. How do I loop my "isLucky" method through my array? Also, how do I print my results correctly in the main method? 需要帮助在我的 Java 程序中集成一个 while 循环。 希望程序更好地处理错误输入 - Need help intgerating a while loop in my java program. Want the program to handle incorrect input better 我的RockPaperScissor程序不断收到此错误消息。 如何解决此错误? - Keep getting this error message for my RockPaperScissor Program. How do I fix this error? 此程序的Getter,setter,equals和toString是什么。 怎么写 - What is Getters, setters, equals and toString for this program. How to write it 如何在Java中判断布尔值等于布尔值还是long等于Long? - How to judge boolean equals to Boolean or long equals to Long in java? 我被困在一个 Java 程序中。 我的程序是一对多右外连接 - I am stuck in a Java program. My program is One To Many Right Outer Join 此Java程序中存在多线程冲突。 怎么解释呢? - there is a multithreads conflicts in this java program. how to explain it? 我如何减少数字时钟程序(java)的闪烁? - How do i reduce flicker from digital clock program(java)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM