下面的代码返回一个奇怪的结果.问题是在第46行.
添加String作为println的参数解决了这个问题
System.out.println("result" + arr[i] + arr[j]+ arr[k]);
System.out.print("\n" + arr[i] + arr[j]+ arr[k]);
我不明白为什么println不起作用.如果不在java中插入字符串,是不是可以连接数组元素?
import java.util.Scanner;
public class Main
{
public static void main(String Args[])
{
System.out.print("How many digits: ");
Scanner obj = new Scanner(System.in);
int n = obj.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++)
{
System.out.print("Enter number "+ (i+1) +": ");
arr[i]=obj.nextInt();
}
combinations(arr);
}
public static void combinations(int[] arr) {
int count=0;
for(int i=0; i<arr.length; i++) {
for(int j=0; j<arr.length; j++) {
for(int k=0; k<arr.length; k++) {
System.out.println(arr[i] + arr[j]+ arr[k]);//Line 46
count++;
}
}
}
System.out.print("\n" + "Total combinations: "+ count);
}
}
解决方法:
这是因为操作符根据其操作数具有不同的行为:要么添加数字,要么连接字符串.
您已将数组声明为[int].这意味着当你这样做时:
arr[i] + arr[j]+ arr[k];
你正在计算三个int的总和,它返回一个int.这被定义为in the Java specification:
The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands.
但是,当你写:
"result" + arr[i] + arr[j]+ arr[k];
因为第一个元素是String,Java会将所有其他元素转换为字符串并将它们连接在一起.
这被描述为in the Java specification:
If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time.
最后,当您调用System.out.println时,它将首先计算作为参数给出的表达式,然后检查其类型是否为String,如果不是,则检查其上是否为toString.
标签:java,string-concatenation 来源: https://codeday.me/bug/20190823/1699380.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。