java - 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). The Program is running. and output is ok. Also create a new text file ("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. 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
/*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 {
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. 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()
. 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.
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Character c : this.myCharacters)
sb.append(c);
return sb.toString();
}
推荐阅读
- angular - 对象字面量只能指定已知属性,并且在“IndividualSeriesOptions”类型中不存在“中心”
- django - How to set Session on LoginView in-built Django
- ruby-on-rails - 在 AREL 中横向连接
- reactjs - 如何从地图(类型)中获取信息
- here-api - 如何使用 curl 提交新地址
- python - 如何允许用户将单个列表项输入到列表列表中?
- tomcat - JMeter - AJP 采样器因非 HTTP 响应消息而失败
- javascript - 等待后未调用承诺
- php - 致命错误:找不到类 'Illuminate\Console\Command'
- maven - 添加我的 H2 依赖项后项目对象模型中的错误