我的作业的最后一个目标要求创建方法matches()
。它接收另一个GenericMemoryCell
作为参数,如果可以在当前GenericMemoryCell
的存储值中找到它的两个存储值,则返回true。存储值的顺序并不重要。
创建方法并不困难,但我对如何从main()
调用它感到迷茫,因为我无法理解传递GenericMemoryCell
的另一个实例的概念。我在哪里首先获得另一对storedValueA
和storedValueB
? matches()
“运行”整个程序的虚拟实例吗?
import java.util.*;
public class GenericMemoryCell<T>{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter valueA: ");
String readerA = input.next();
System.out.print("Enter valueB: ");
String readerB = input.next();
GenericMemoryCell<String> values = new GenericMemoryCell<>(readerA, readerB);
System.out.println("storedValueA: " + values.readA());
System.out.println("storedValueB: " + values.readB());
values.writeA(readerA);
values.writeB(readerB);
}
public GenericMemoryCell(T storedValueA, T storedValueB)
{ this.storedValueA = storedValueA; this.storedValueB = storedValueB; writeA(storedValueA); writeB(storedValueB); }
public T readA()
{ return storedValueA; }
public T readB()
{ return storedValueB; }
public void writeA(T x)
{ storedValueA = x; }
public void writeB(T y)
{ storedValueB = y; }
public boolean matches(GenericMemoryCell<T> that){
return (this.storedValueA.equals(that.storedValueA) && this.storedValueB.equals(that.storedValueB)); }
private T storedValueA, storedValueB;
}
答案 0 :(得分:1)
我认为你需要这样的东西
public class GenericMemoryCell {
public static void main(String[] args) {
GenericMemoryCell g1 = new GenericMemoryCell();
//set g1 values here
GenericMemoryCell g2 = new GenericMemoryCell();
//set g2 values here
System.out.println(g1.matches(g2));
}
public boolean matches(GenericMemoryCell g) {
//implement the logic here
return ...;
}
}
答案 1 :(得分:0)
希望它可能适合你。但是,如果您希望系统重复请求输入,则需要某种loop
。
public class GenericMemoryCell {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first input: ");
int firstInput = scanner.nextInt();
System.out.println("Please enter second input");
int secondInput = scanner.nextInt();
list.add(firstInput);
list.add(secondInput);
Scanner scannerObj = new Scanner(System.in);
System.out.println("Please enter first input: ");
int firstArg = scannerObj.nextInt();
System.out.println("Please enter second input: ");
int secondArg = scannerObj.nextInt();
boolean isMatches = isInputMatches(firstArg, secondArg, list);
if (isMatches) {
System.out.println("These inputs were already stored before. Please try again with different inputs");
} else {
System.out.println("The inputs are successfully stored. Thank you.");
}
scanner.close();
scannerObj.close();
}
private static boolean isInputMatches(int firstArg, int secondArg, List<Integer> list) {
return list.contains(firstArg) && list.contains(secondArg);
}
}