我的问题是如何分隔整数中的数字?下面是我的代码,一切都是我想要的东西减去我无法将整数中的数字分开的事实。当我输入“12345”时,程序输出“12345”,我希望它将数字分开,这样输出就是1 2 3 4 5.
import java.util.*;
public class SNHU_Practice
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
String input = "";
int sum = 0;
System.out.println( "Please enter a number: " );
input = console.next();
int i = 0;
while( i < input.length() )
{
char temp = input.charAt(i);
sum += Character.getNumericValue(temp);
i++;
}
System.out.println( "The number entered was " + input + ". The sum of these digits is: " + sum + "." );
}
}
答案 0 :(得分:0)
你可以写
input.replace("", " ").trim()
而不是input
中的System.out.println
。 E.g:
System.out.println( "The number entered was " + input.replace("", " ").trim() + ". The sum of these digits is: " + sum + "." );
答案 1 :(得分:0)
我想这就是你想要的。
import java.util.*;
public class SNHU_Practice{
public static void main(String args[]){
Scanner console = new Scanner(System.in);
String input = "";
StringBuilder result = new StringBuilder("");
int sum = 0;
System.out.println( "Please enter a number: " );
input = console.next();
int i = 0;
while( i < input.length() )
{
char temp = input.charAt(i);
result.append(temp + " ");
i++;
}
System.out.println( "The number entered was " + input + ". The output string is " + result + "." );
}
}