十进制到二进制不起作用

时间:2014-06-06 22:21:33

标签: java android converter

我知道一个事实我错过了一些非常小的东西,但我似乎无法让我的代码编译而没有错误。我试图让文本字段采用十进制数字OnClick,它会吐出数字二进制数。

它一直告诉我初始化Binary但是如果我将它设置为0,那么Binary' 0'而不是转换十进制数。

任何帮助都会很棒!这是我的MainActivity.java文件:

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();   
    }

    final EditText editDecimal = (EditText) findViewById(R.id.editDecimal);
    final EditText editBinary = (EditText) findViewById(R.id.editBinary);
    Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
    buttonConvert.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            int decimal =       Integer.valueOf(editDecimal.getText().toString());
            int binary;


            editBinary.setText(Integer.toBinaryString(binary));
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        return rootView;
    }
}

}

1 个答案:

答案 0 :(得分:2)

您不需要变量binary。相反,你只需要这样做:

editBinary.setText(Integer.toBinaryString(decimal));