Cannot figure out how to proceed: Java Bug~ [closed]
import java.util.Scanner;
public class Test {
private static int decimalNum = 0;
private static String binary = "";
private static void getInput() {
Scanner sc = new Scanner(System.in);
System.out.println("Please type in a number");
decimalNum = sc.nextInt();
}
private static void convert() {
int decimalNumber = decimalNum;
String binaryNumber;
if (decimalNumber <= 0)
System.out.println("ERROR: entered integer is nonpositive.");
else {
binaryNumber = "";
while (decimalNumber != 0) {
// add spaces to separate 4-digit groups
if (binaryNumber.length() % 5 == 0)
binaryNumber = "" + binaryNumber;
// extract last digit in binary representation
// and add it to binaryNumber
binaryNumber = (decimalNumber % 2) + binaryNumber;
// cut last digit in binary representation
decimalNumber /= 2;
}
binary = binaryNumber;
System.out.println("Binary: " + binaryNumber);
}
}
public static void count() {
String s = binary + "";
System.out.println("Binary number: " + s);
int temp1Block = 0;
int temp0Block = 0;
int maxBlock = 0;
for (int i = 0; i < s.length(); i++) {
if ((s.charAt(i) == '1') && (i < s.length())) {
temp0Block = 0;
temp1Block++;
}
if ((s.charAt(i) == '0') && (i < s.length())) {
temp1Block = 0;
temp0Block++;
}
}
if (maxBlock < temp0Block) {
maxBlock = temp0Block;
}
if (maxBlock < temp1Block) {
maxBlock = temp1Block;
}
System.out.println("Maxblock " + maxBlock);
}
public static void main(String[] args) {
getInput();
convert();
count();
}
}
I am resetting the tempBlocks when I should not be. And can someone help me format my code please, I don't know how to put the code tags.
I think your loop would be better off like this: (I've remove some reduncant checks on 'i' and simplified the checking for 'maxBlock'):
for(int i = 0; i < s.length(); ++i) {
if(s.charAt(i) == '1') {
// in case we were just keeping track of 0's
maxBlock = Math.max(maxBlock, temp0Count);
temp0Count = 0;
temp1Count++;
}
else {
// in case we were just keeping track of 1's
maxBlock = Math.max(maxBlock, temp1Count);
temp1Count = 0;
temp0Count++;
}
}
I'm thinking you want to keep track of the longest sequence of 1s or 0s. If that is the case, then try putting the two if statements that check the maxBlock condition inside the loop.
精彩评论