![](/img/trans.png)
[英]Why does my program not allow me to assign a value to one of the elements of my array?
[英]How to create a program for randomly assign 0 and 1 to array elements and find the decimal value for it
我編寫此代碼是為了找到符號幅度為8位表示形式的十進制值。 因此,我創建了一個數組並在0-1之間為它隨機分配值,然后為它打印位模式和真實的十進制值。 在Java中,有什么簡單的方法可以做到這一點?
import java.util.Random;
class Example {
public static void main(String args[]) {
Random r = new Random();
int A[] = new int[20];
for (int i = 0; i < A.length; i++) {
int count = 1, k = 6, l = 0, m = 0;
for (int j = 0; j < 8; j++) {
A[i] = r.nextInt(2);
System.out.print(A[i]);
if (count == 1) {
if (A[i] == 1) {
m = -A[i];
} else {
m = 1;
}
} else {
double d = Math.pow(2, k);
l += (int) d * A[i];
k--;
}
count++;
}
System.out.println(" = " + (l * m));
}
}
}
您可以嘗試制作一個隨機的二進制字符串,然后使用JAVA的字符串到十進制轉換器Integer.parseInt(string,base)將此字符串轉換為十進制值,這是一個示例:
String randBinaryNumber;
char sign;
for(int i = 0; i < 8; i++){
// creates binary string
randBinaryNumber += Integer.toString(r.nextInt(2));
}
//gets sign of randBinaryNumber
sign = randBinaryNumber.charAt(0);
// removes first character of string
randBinaryNumber = randBinaryNumber.substring(1);
// converts string to decimal
int decimal = Integer.parseInt(randBinaryNumber,2);
if(sign == '1')
decimal *=-1;
這樣的事情應該可以解決,如果您有任何問題請發表評論。
編輯:在for循環中使用字符串連接是一種不好的做法,因為它會為每次迭代創建一個新對象。 相反,您應該使用字符串生成器類進行追加。
您應該添加:
StringBuilder sb = new StringBuilder();
randBinaryNumber = sb.append(r.nextInt(2));
代替:
randBinaryNumber += Integer.toString(r.nextInt(2));
它將字符串值存儲在一個對象中,而不是每次添加二進制數字時都創建一個新對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.