【问题标题】:How do you make it so that when you enter a number it puts a space between each integer你是怎么做到的,当你输入一个数字时,它会在每个整数之间留一个空格
【发布时间】:2022-11-15 11:47:19
【问题描述】:

导入 java.util.Scanner;

公共课数字{

public static void main(String[] args) {
    /*
     * 
count = 1 
temp = n 
while (temp > 10) 
    Increment count. 
    Divide temp by 10.0. 

*/

    //Assignment: fix this code to print: 1 2 3 (for 123)
    //temp = 3426 -> 3 4 2 6
    Scanner input = new Scanner(System.in);
    System.out.print("Enter an integer: ");
    int count = 1;
    int temp = input.nextInt();
    while(temp >= 10){
        count++;
        temp = temp / 10;
        System.out.print(temp + " ");
    }
}

}

需要帮助修复代码。 示例:当您输入 123 时,它变为 1 2 3。

【问题讨论】:

  • 尝试将输入读取为字符串,然后使用循环 for (char c : temp.toCharArray())
  • 它说 Cannot invoke toCharArray() on the primitive type int
  • 也许你应该把它改成String

标签: java eclipse loops pseudocode


【解决方案1】:

您的大部分代码都是正确的,您要做的是除以 10,然后打印出该值 - 这可能应该是模数运算 % 以获得剩余的操作并将其打印出来 - 但是很好的思考方式。

尽管如此。

您可以只使用一个字符串,然后在每个字符上拆分字符串

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        String temp = input.next();

        // is this an int?
        try {
            int test = Integer.parseInt(temp);

            // at this point it is an int - so let's go through and start printing out 
            // each character with a space after it

            for (char c : temp.toCharArray()) {
                System.out.print(c + " ");
            }

        } catch (NumberFormatException ex){
            // this is not an int as we got a number format exception...

            System.out.println("You did not enter an integer. :(");
        }

        // be nice and close the resource
        input.close();
    }

【讨论】:

  • 你能修复我的原始代码以获得相同的解决方案吗?
【解决方案2】:

您的代码每次除以 10,可用于反向打印该值。要向前打印它,您需要一些涉及对数的more math。有时候,

Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int temp = input.nextInt();
while (temp > 0) {
    int p = (int) (Math.log(temp) / Math.log(10));
    int v = (int) (temp / Math.pow(10, p));
    System.out.print(v + " ");
    temp -= v * Math.pow(10, p);
}

或者,读取一行输入。去掉所有非数字,然后打印用空格分隔的每个字符。喜欢,

String temp = input.nextLine().replaceAll("\D", "");
System.out.println(temp.replaceAll("(.)", "$1 "));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2021-06-13
    • 2022-01-14
    • 2013-06-14
    相关资源
    最近更新 更多