我的代码中有错误,似乎无法找到解决方案,请有人调试我的代码吗?
import java.util.* ;
public class Calculator {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first number:");
String a = s.nextLine();
System.out.print("Enter the second number:");
String b = s.nextLine();
int[] num1 = new int[a.length()];
int[] num2 = new int[b.length()];
for (int i=0;i<a.length();i++) {
num1[i] = (int) a.charAt(i);
num2[i] = (int) b.charAt(i);
}
int[] sum = new int[a.length()];
for (int i = a.length() - 1; i >= 0; i--){
if (num1[i] + num2[i] >= 10){
sum[i] = (num1[i]+num2[i]) - 10;
**sum[i-1] = 1;**
} else {
sum[i] = num1[i] + num2[i];
}
}
for (int i = 0; i < a.length(); i++) {
System.out.print(sum[i]+" ");
}
}
}
答案 0 :(得分:5)
a.length()
可能不等于b.length()
有问题的代码
int[] num1 = new int[a.length()];
int[] num2 = new int[b.length()];
for (int i=0;i<a.length();i++) {
num1[i] = (int) a.charAt(i);
num2[i] = (int) b.charAt(i);
}
例如:考虑a.length()
= 10
和b.length()
= 2
进一步有问题的代码:
for (int i = a.length() - 1; i >= 0; i--){
if (num1[i] + num2[i] >= 10){
sum[i] = (num1[i]+num2[i]) - 10;
**sum[i-1] = 1;**
} else {
sum[i] = num1[i] + num2[i];
}
}
答案 1 :(得分:0)
你可以这样做。
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.print("Enter the first number");
String a = s.nextLine();
System.out.print("Enter the second number:");
String b = s.nextLine();
int[] num1 = new int[a.length()];
int[] num2 = new int[b.length()];
for (int i=0;i<a.length();i++) {
num1[i] = (int) a.charAt(i);
}
for (int i=0;i<b.length();i++)
{
num2[i] = (int) b.charAt(i);
}
int[] sum;
if(a.length()>b.length())
{
sum = new int[a.length()];
for (int i = a.length() - 1; i >= 0; i--)
{
if (num1[i] + num2[i] >= 10)
{
sum[i] = (num1[i]+num2[i]) - 10;
/*sum[i-1] = 1;*/
}
else {
sum[i] = num1[i] + num2[i];
}
}
}
else
{
sum = new int[b.length()];
for (int i = a.length() - 1; i >= 0; i--)
{
if (num1[i] + num2[i] >= 10)
{
sum[i] = (num1[i]+num2[i]) - 10;
/*sum[i-1] = 1;*/
}
else {
sum[i] = num1[i] + num2[i];
}
}
}
for (int i = 0; i < a.length(); i++) {
System.out.print(sum[i]+" ");
}
}