gpt4 book ai didi

java - 友好号码Java程序

转载 作者:行者123 更新时间:2023-11-29 05:45:57 25 4
gpt4 key购买 nike

所以我得到了这个奇怪的输出,其中只有第一个数字被检查了两次,而第二个数字甚至没有被考虑。请帮忙。

代码:-

import java.util.Scanner;

public class Amicable
{
private static int a,b;
private static String m,n;

public static void main()
{
acceptNumbers();

if (firstNumber() == secondNumber())
{
System.out.println(a+" and "+b+" are amicable numbers");
}

else System.out.println(a+" and "+b+" are not amicable numbers");
}

public static void acceptNumbers()
{
Scanner sc = new Scanner(System.in);

int count=0;

System.out.print("Enter two numbers [ separated by a ',' ] : ");
String input = sc.nextLine();

System.out.println();

for (int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);

if (c == ',')
{
count++;
if (count == 1)
{
m = input.substring(0,i);
n = input.substring(0,i);
}

break;
}
}

if (count == 0)
{
System.out.println("Invalid operation : You have entered only 1 number");
}

m = m.trim(); n = n.trim();

a = Integer.valueOf(m);
b = Integer.valueOf(n);
}

public static int firstNumber()
{
int a1,a2=0;

for (int i = 0; i < m.length()-1; i++)
{
a1 = Integer.valueOf(m.charAt(i));

if (a%a1 == 0) a2 = a2+a1;
}

return a2;
}

public static int secondNumber()
{
int b1,b2=0;

for (int i = 0; i < n.length()-1; i++)
{
b1 = Integer.valueOf(n.charAt(i));

if (b%b1 == 0) b2 = b2+b1;
}

return b2;
}
}

这是输出:-

输入 2 个数字 [以 ',' 分隔]:248、222

248和248是友好数

最佳答案

你的 m 和 n 是相等的,因为你有:

m = input.substring(0,i);
n = input.substring(0,i);

将其更改为:

m = input.substring(0,i);
n = input.substring(i+1);

顺便说一句,你做了很多不必要的事情,完整的解决方案(我不关心异常):

import java.util.Scanner;

public class Amicable {
public static void main(String args[]) {
try {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers [ separated by a ',' ] : ");
String input = sc.nextLine();

String[] numbers = input.split(",");

int num1 = Integer.parseInt(numbers[0].trim());
int num2 = Integer.parseInt(numbers[1].trim());
int sum1 = 0, sum2 = 0;
for (int i = 1; i <= num1; i++) {
if (num1 % i == 0)
sum1 += i;
}
for (int i = 1; i <= num2; i++) {
if (num2 % i == 0)
sum2 += i;
}
if (sum1 == sum2)
System.out.println(num1 + " and " + num2
+ " are amicable numbers");
else
System.out.println(num1 + " and " + num2
+ " are not amicable numbers");
} catch (Exception e) {
e.printStackTrace();
}
}
}

部分代码来自:http://www.daniweb.com/software-development/java/code/304600/amicable-numbers

关于java - 友好号码Java程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15853242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com