import java.util.Scanner;
public class TomAndJerry {
Scanner sc = new Scanner(System.in);
public String catAndMouse(int x, int y, int z) {
String result = null;
int q = 0;
System.out.println("enter the number of queries");
q = sc.nextInt();
for (int i = 0; i < q; i++) {
x = sc.nextInt();
y = sc.nextInt();
z = sc.nextInt();
}
if (Math.abs(x - z) < Math.abs(y - z)) {
result = "Cat A";
} else if (Math.abs(x - z) > Math.abs(y - z)) {
result = "Cat B";
} else {
result = "Mouse C";
}
return result;
}
public static void main(String[] args) {
int x = 0, y = 0, z = 0;
String result = null;
TomAndJerry tj = new TomAndJerry();
result = tj.catAndMouse(x, y, z);
System.out.println(result);
}
}
输出:-
enter the number of queries
2
1 2 3
1 3 2
Mouse C
我最终只获得使用扫描仪提供的最后一个查询/输入的输出。我如何获得其余查询/输入的输出。谢谢您的宝贵时间! :)
答案 0 :(得分:2)
您需要使用List或String []而不是简单的String对象才能从一个函数中返回多个String, 同样,if条件需要成为for循环的一部分,并且需要将结果添加到List或数组中, 下面是使用List的预期输出
import java.util.*;
public class Main {
Scanner sc = new Scanner(System.in);
public List<String> catAndMouse(int x, int y, int z) {
List<String> results = new ArrayList<String>();
int q = 0;
System.out.println("enter the number of queries");
q = sc.nextInt();
for (int i = 0; i < q; i++) {
x = sc.nextInt();
y = sc.nextInt();
z = sc.nextInt();
if (Math.abs(x - z) < Math.abs(y - z)) {
results.add("Cat A");
} else if (Math.abs(x - z) > Math.abs(y - z)) {
results.add("Cat B");
} else {
results.add("Mouse C");
}
}
return results;
}
public static void main(String[] args) {
int x = 0, y = 0, z = 0;
Main tj = new Main();
List<String> results = tj.catAndMouse(x, y, z);
System.out.println(results.toString());
}
}
输入查询数2 1 2 3 1 3 2 [猫B,鼠标C]
答案 1 :(得分:0)
是因为这段代码-
System.out.println("enter the number of queries");
q = sc.nextInt();
for (int i = 0; i < q; i++) {
x = sc.nextInt();
y = sc.nextInt();
z = sc.nextInt();
}
您要向用户询问多个查询,然后在循环中多次询问x,y和z,而不在循环内处理值。
您的catAndMouse
方法的唯一责任应该是在给定输入参数的情况下给出结果。因此,将输入留给主类。
您可以像下面这样简化代码:
public class TomAndJerry {
private static Scanner sc = new Scanner(System.in);
public String catAndMouse(int x, int y, int z) {
String result;
if (Math.abs(x - z) < Math.abs(y - z)) {
result = "Cat A";
} else if (Math.abs(x - z) > Math.abs(y - z)) {
result = "Cat B";
} else {
result = "Mouse C";
}
return result;
}
public static void main(String[] args) {
System.out.println("enter the number of queries");
int q = sc.nextInt();
int x , y , z ;
String result;
TomAndJerry tj = new TomAndJerry();
for (int i = 0; i < q; i++) {
x = sc.nextInt();
y = sc.nextInt();
z = sc.nextInt();
result = tj.catAndMouse(x, y, z);
System.out.println(result);
}
}
}