有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java支持多个输入,同时获得输出

我打算找出给定数字之间的回文数,变量“t”决定测试用例的数量。例如,如果t=2,则输入为:

2
12 23(in the next line)
56 78(in the next line)
Where the output would be:
1
2 (next line)

但在输入后,我的代码如下所示:

2
12 23 

我得到的输出为1,然后我应该继续给出下一个测试用例

如何一次给出两个测试用例

import java.io.*;
import java.util.Scanner;
public class Checkall {
    public int check_all(int a, int b) {
        int c = 0;
        for (int y = a; y <= b; y++) {
            int z = y;
            int d = 0;
            while (z > 0) {
                d = d * 10 + z % 10;
                z /= 10;
            }
            if (d == y) c++;
        }
        return c;
    }
    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));
        //System.out.println("Enter the limits");
        int t = Integer.parseInt(br.readLine());
        for (int s = 1; s <= t; s++) {
            Scanner scn;
            scn = new Scanner(System. in );
            int a = scn.nextInt();
            int b = scn.nextInt();
            Checkall p = new Checkall();
            p.check_all(a, b);
            System.out.print(p.check_all(a, b));
        }
    }
}

共 (3) 个答案

  1. # 1 楼答案

    仔细使用Scanner nextInt

    public static void main(String args[]) throws IOException {
    
        System.out.println("Enter the limits");
    
        Scanner scn = new Scanner(System.in);
    
        int t = Integer.parseInt(scn.nextLine());
    
        for (int s = 0; s < t; s++) {
            int a = scn.nextInt();
            int b = scn.nextInt();
            scn.nextLine();
            System.out.println(new Checkall().check_all(a, b));
        }
    }
    
  2. # 2 楼答案

    为了调试这些格式问题,将终端同时用于输入和输出不是一个好主意。您可以将输入写入文件:

    $ cat > in.txt
    2
    1 2
    3 4
    ^C # press Control and C here
    

    然后将其输入到您的程序中:

    $ java Checkall < in.txt
    

    现在您将只看到输出

  3. # 3 楼答案

    读取所有值并将其添加到二维数组中

    int[][] values=new int[t][2]
    

    在每次迭代中添加值

    values[s][0]=first number
    values[s][1]=second number
    

    扫描迭代后,完成每个值集的调用计算方法