创建一种从数字转换为二进制,转换为字母,再转换为矩阵的方法 [英] Creating a method to transfer from a number, to binary, to a letter, to a matrix

查看:93
本文介绍了创建一种从数字转换为二进制,转换为字母,再转换为矩阵的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在编写这个程序来模拟一个侧面为H和T的硬币翻转,并且有时间来创建我的方法。该程序背后的主要思想是用户应该能够输入任意数字b / w 1和511.一旦输入数字,我的方法应该将它们的数字转换为二进制,0为Heads,1为Tails。



所以,一旦我得到000000011,我想要打印一个如下的矩阵:



HHH

HHH

HTT



任何人有想法?这是我到目前为止的代码,但是我的方法是空的。



So I'm writing this program that simulates a coinflip with sides H and T, and its come time to create my method. The main idea behind the program is that a user should be able to enter any number b/w 1 and 511. Once the number is entered, my method should convert their number to binary, 0's being Heads, and 1's being Tails.

So once I get 000000011 perhaps, I want to print a matrix that looks like:

HHH
HHH
HTT

Anyone have an idea? Here is my code so far, however my method is empty.

import java.util.Scanner;
public class Problem8_11 {
public static void main(String[] args) {
	Scanner input = new Scanner(System.in);

	System.out.print("Enter one number between 0 and 511: ");
    int number = input.nextInt();
    
    String binaryValue = binaryConverter(number);
    
    int[][] matrix = new int[3][3];
    int binary = 0;
    
    for (int i = 0; i < matrix.length; i++) {
    		for (int x = 0; x < matrix[i].length; x++) {
            int HeadOrTails = (binaryValue.charAt(binary++) == '0') ? 0 : 1;
            		matrix[x][i] = HeadOrTails;
        }
    }
    for (int i = 0; i < matrix.length; i++) {

        for (int x = 0; x < matrix[i].length; x++) {
            char HorT = (matrix[i][x] == 0) ? 'H' : 'T';
            System.out.print(HorT + "");
        }
        System.out.println(" ");
    }

}





我尝试过:



我尝试过使用Charachter.isDigit,但这似乎并不是很有用。我还被告知有一个binaryToString转换器,但我找不到。



What I have tried:

I've tried using Charachter.isDigit but that didnt seem to be very useful. I was also told there was a binaryToString convertor but I couldnt find that.

推荐答案

java中有一个内置方法 Integer.toString(int i,int radix)将整数转换为二进制,并将二进制值作为字符串返回,您可以将其存储在strin g变量中。



Integer.toString(int i,int radix)



i - 这是一个要转换的整数。



radix - 这是字符串表示中使用的基数。





在你的程序中,你可以直接写



String binaryValue = Integer.toString(number,2);



2是二进制数系统的基数

8 for octal

16 for hexadecimal
There is an inbuilt method in java Integer.toString(int i,int radix) which converts integer into binary and returns the binary value as a string which you can store in a strin g variable .

Integer.toString(int i,int radix)

i − This is an integer to be converted.

radix − This is the radix to use in the string representation.


In your programme , you can directly write

String binaryValue = Integer.toString(number,2);

2 is the radix of binary number system
8 for octal
16 for hexadecimal


这篇关于创建一种从数字转换为二进制,转换为字母,再转换为矩阵的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆