gpt4 book ai didi

java - 将汇编器算法转变为 Java 序列计算器

转载 作者:行者123 更新时间:2023-12-01 13:46:50 25 4
gpt4 key购买 nike

当我在 java 代码中输入“3”时,它会打印

3 将乘以 3 并+1值为 10

关于如何修改它的任何建议,以便它正确计算序列

    import javax.swing.*;
public class sequences {

/**
* @param args
*/
public static void main(String[] args) {
calculateSequences();
}//ends main

public static void calculateSequences()
{
int value;
String valueInput = JOptionPane.showInputDialog("Value");
value = Integer.parseInt(valueInput);

if(value == 1)
{
System.out.println("Value is equal to 1, closing down");
System.exit(0);

}
else if ((value%2)==0)
{
System.out.println(value + " will be divided by 2");
value = value/2;
System.out.println("Value is even " + value);

}
else
{
System.out.println(value + " will be multiplied by 3 and +1");
value = 3*value+1;
System.out.println("Value is " + value);

}

}//ends calculateSequences
}//ends class

最佳答案

你忘记了“开始”

以下是一项测试的结果。

23 will be multiplied by 3 and + 1
Value is 70
70 will be divided by 2
Value is even 35
35 will be multiplied by 3 and + 1
Value is 106
106 will be divided by 2
Value is even 53
53 will be multiplied by 3 and + 1
Value is 160
160 will be divided by 2
Value is even 80
80 will be divided by 2
Value is even 40
40 will be divided by 2
Value is even 20
20 will be divided by 2
Value is even 10
10 will be divided by 2
Value is even 5
5 will be multiplied by 3 and + 1
Value is 16
16 will be divided by 2
Value is even 8
8 will be divided by 2
Value is even 4
4 will be divided by 2
Value is even 2
2 will be divided by 2
Value is even 1
Value is equal to 1, closing down

这是添加了 while 子句的代码。

import javax.swing.JOptionPane;

public class Sequences {

/**
* @param args
*/
public static void main(String[] args) {
calculateSequences();
}// ends main

public static void calculateSequences() {
int value;
String valueInput = JOptionPane.showInputDialog("Value");
value = Integer.parseInt(valueInput);

while (value > 0) {
if (value == 1) {
System.out.println("Value is equal to 1, closing down");
System.exit(0);

} else if ((value % 2) == 0) {
System.out.println(value + " will be divided by 2");
value = value / 2;
System.out.println("Value is even " + value);

} else {
System.out.println(value + " will be multiplied by 3 and + 1");
value = 3 * value + 1;
System.out.println("Value is " + value);

}
}

}// ends calculateSequences

}

关于java - 将汇编器算法转变为 Java 序列计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20304244/

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