[英]Finding consecutive numbers in a sequence without a fixed input using scanner Java
我是這個網站的新手並且正在編寫Java但是我正在嘗試一個問題,用戶可以輸入任意數量的數字(不用空格或逗號分隔),輸出將是連續出現的數字和連續出現的次數那條鏈子。
我遇到了如何比較將出現的不同數字鏈的問題。 例如,如果連續有3個零后跟5個七位數,我需要將它們相互比較。
我想出了兩個變量,一個將連續計數最多,另一個將排在第二位。 然后,如果第二個位置連續超過最多位置,則第二個位置成為第一個位置,然后將值重置為零。 我無法讓它工作,我相信這是因為我使用了for循環。
問題:我正在尋找如何正確解決這個問題的一些指導。 我這樣做錯了嗎?
這是我的代碼的唯一版本。 如果我輸入一個像10000這樣的數字,它將得到0正確,但像100011這樣的數字將得到錯誤。
謝謝。
import java.util.Scanner;
public class Sequence
{
public static void main(String[] args)
{
String numInput;
int mostInaRow = 1;
int secondPlace = 1;
char mostNum = 1;
Scanner input = new Scanner(System.in);
System.out.println("Enter the numbers");
numInput = input.next();
for (int i = 0 ;i < numInput.length() - 1 ; i++ )
{
if(numInput.charAt(i) == numInput.charAt(i + 1))
{
mostInaRow++;
secondPlace++;
mostNum = numInput.charAt(i);
}
else
{
}
}
System.out.println(mostNum);
System.out.println(mostInaRow);
}
}
int i = 0;
while(i < numInput.length() - 1) {
int j = i + 1;
int current = 1;
while (j < numInput.length() && numInput.charAt(i) == numInput.charAt(j)) {
current++;
j++;
}
if (current > mostInaRow) {
mostInaRow = current;
mostNum = numInput.charAt(i);
}
i = j;
}
你可以做這樣的事情
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.