gpt4 book ai didi

java - 如何使用扫描仪在给定多个输入的情况下获得多个输出

转载 作者:行者123 更新时间:2023-12-02 01:38:00 25 4
gpt4 key购买 nike

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

我最终只获得使用扫描仪提供的最后一个查询/输入的输出。我如何获取剩余查询/输入的输出。感谢您提前抽出时间! :)

最佳答案

您需要使用 List 或 String[] 而不是简单的 String 对象来从函数返回多个字符串,另外,if 条件需要成为 for 循环的一部分,并且您需要将结果添加到列表或数组中,下面是使用 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());
}

}

enter the number of queries 2 1 2 3 1 3 2 [Cat B, Mouse C]

关于java - 如何使用扫描仪在给定多个输入的情况下获得多个输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54918750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com