我编写了以下代码,当我运行它时,它会以[#,#,#,#]的形式显示答案。我希望它显示为####(没有大括号和逗号)并且不使用system.out.print。不知何故,我想将结果存储在一个变量中,只需调用该变量。
import java.util.Scanner;
import java.util.ArrayList;
public class trial
{
static Scanner keyboard = new Scanner(System.in);
public static ArrayList<Integer> primeFactors(long number)
{
long n = number;
ArrayList<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n; i++)
{
while (n % i == 0)
{
factors.add(i);
n /= i;
}
}
return factors;
}
public static void main(String[] args)
{
System.out.println("Enter phone number to be factored");
long input = keyboard.nextLong();
System.out.println(primeFactors(input));
}
}
答案 0 :(得分:1)
看一下它返回的内容https://docs.oracle.com/javase/7/docs/api/java/util/AbstractCollection.html#toString()
将其更改为
System.out.println(primeFactors(input)
.toString().replace("[", "").replace("]", "").replace(",", " ");
或只是遍历并打印值
答案 1 :(得分:0)
您可以在primeFactors方法中将返回类型更改为String。然后循环ArrayList并将内容添加到String中,如下所示。
package src.main;
import java.util.Scanner;
import java.util.ArrayList;
public class sampleMain
{
static Scanner keyboard = new Scanner(System.in);
public static String primeFactors(long number)
{
long n = number;
ArrayList<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
StringBuffer output = new StringBuffer();
for (Integer integer : factors) {
if( output.length()==0 ){
output.append(integer.toString());
}else{
output.append(", "+integer.toString());
}
}
return output.toString();
}
public static void main(String[] args) {
System.out.println("Enter phone number to be factored");
long input = keyboard.nextLong();
System.out.println(primeFactors(input));
}
}
根据评论
更新 StringBuffer的答案答案 2 :(得分:0)
尝试迭代ArrayList
中的值并将其附加到StringBuilder。像这样:
StringBuilder oneStringValue = new StringBuilder();
for(Integer tempNum : primeFactors(input)) {
oneStringValue.append(tempNum.toString());
}
System.out.println(oneStringValue.toString());
这应该有效。
对于添加的信息,我使用StringBuilder
附加字符串,因为它是mutable
,而不是String
immutable
。
答案 3 :(得分:0)
只需使用每个循环:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter phone number to be factored");
long input = keyboard.nextLong();
ArrayList<Integer> arr = primeFactors(input);
for(int a:arr){
System.out.print(a+" ");
}
keyboard.close();
}