我正在研究这个带有二进制字符串并将其转换为十进制的程序,使用本指南将二进制转换为十进制.当我在头脑中经历for循环时,我得到了正确的输出.然而,当我运行我的程序时,我得到了这个奇怪的输出:
1
3
7
15
31
63
127
Run Code Online (Sandbox Code Playgroud)
实际输出应如下所示:
1
2
5
11
22
44
89
Run Code Online (Sandbox Code Playgroud)
我无法想象我的生活.为什么我的程序会这样做?这是当前的源代码:
public class BinaryToDecimal
{
public static void main(String[] args)
{
String binary = "1011001";
int toMultiplyBy;
int decimalValue = 0;
for (int i = 1; i <= binary.length(); i++)
{
int whatNumber = binary.indexOf(i);
if (whatNumber == 0)
{
toMultiplyBy = 0;
}
else
{
toMultiplyBy = 1;
}
decimalValue = ((decimalValue * 2) + toMultiplyBy);
System.out.println(decimalValue);
}
}
}
Run Code Online (Sandbox Code Playgroud) 我正在为这个基本Pong-style游戏而努力,但我在这个GUI方面遇到了一些困难.基本上我有一个JFrame叫做窗户,里面有一切东西,还有一个JPanel叫做内容.内容应该是指ContentPanel我所拥有的.这是我到目前为止的源代码(对不起,它很长,很多都与游戏完全相关,而不是这个问题,但我不确定我需要哪些部分源代码才能使我的问题有意义):
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class Pong extends JApplet {
public static void main(String[] args) {
JFrame window = new JFrame("Pong: The Game of Champions");
JPanel content = new JPanel();
window.setContentPane(content);
window.setSize(1000,600);
window.setLocation(100,100);
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setVisible(true);
window.setResizable(false);
JMenuBar settings = new JMenuBar();
ButtonHandler listener = new ButtonHandler();
window.setJMenuBar(settings);
JMenu toolsMenu = new JMenu("Settings");
settings.add(toolsMenu);
JMenuItem preferences = new JMenuItem("Preferences");
JMenuItem about = new JMenuItem("About"); …Run Code Online (Sandbox Code Playgroud) 作为一个更大的程序的一部分,我有这个函数,当被调用时,返回返回的字符串.accountHolder,balance,interestRate和points是RewardsCreditAccount类型的对象中的变量.所以,例如,我在这里声明了一个对象:
RewardsCreditAccount testAccount = new RewardsCreditAccount("Joe F. Pyne", 7384.282343837483298347, 0.173, 567);
Run Code Online (Sandbox Code Playgroud)
所以这个对象将设置accountHolder ="Joe F. Pyne",balance = 7384.282343837483298347,依此类推.
在下面的函数中,我将这个信息返回一个字符串,如下所示:
Joe F. Pyne,7384.282美元,17.28%,567分
使用此功能:
public String toString() {
return (accountHolder + ", $" + + balance + 100*interestRate + "%, " + points + " points");
}
Run Code Online (Sandbox Code Playgroud)
但是,它实际上是返回此:
Joe F. Pyne,$ 7384.282,17.299999999999997%,567分
我试过这个,但无济于事
public String toString() {
return (accountHolder + ", $" + + ("%,1.2f",balance) + 100*interestRate + "%, " + points + " points");
}
Run Code Online (Sandbox Code Playgroud)
这很烦人,因为我希望它只返回两个小数位.我知道这可以使用%1.2f完成,但我不知道如何格式化语法.我非常感谢任何有关正确显示十进制值的帮助.谢谢!