无法确定如何继续:Java错误~
我正在重置不应该重置的临时块。有人能帮我格式化我的代码吗?我不知道如何放置代码标签。我想你应该跟踪最长的1或0序列。如果是这种情况,那么尝试将检查maxBlock条件的两个If语句放入循环中。我认为您的循环最好是这样:我删除了对“I”的一些冗余检查,并简化了对“maxBlock”的检查:无法确定如何继续:Java错误~,java,Java,我正在重置不应该重置的临时块。有人能帮我格式化我的代码吗?我不知道如何放置代码标签。我想你应该跟踪最长的1或0序列。如果是这种情况,那么尝试将检查maxBlock条件的两个If语句放入循环中。我认为您的循环最好是这样:我删除了对“I”的一些冗余检查,并简化了对“maxBlock”的检查: import java.util.Scanner; public class Test { private static int decimalNum = 0; private static Stri
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();
}
}
只需点击SO编辑器中的“格式”按钮。您遇到了什么问题?您可能想先在IDE中格式化它-当单个方法的所有语句都在一行上时,很难理解!请不要将问题交叉发布到多个SE站点。堆栈溢出是回答您的问题的正确位置,尽管正如我在程序员身上所说的,它需要更多的细节。如果你在不该重置的时候重置了tempBlocks,那就停止吧?你的实际问题是什么?如果你告诉我们你想要什么,这会更容易回答!我需要重新设置。问题是我很难跟踪最大块数。我想粘贴答案,以防功能中有人:
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++;
}
}