我试图弄清楚如何计算一个数组中一个特定元素相互出现的次数。就像掷骰子时,数字6出现了多少次。
例如::如果这是抛出56611166626634416
的结果,那么结果将是2倍!!
我已经尝试过使用for循环并比较元素,但是它会继续计数是否 6 彼此相邻出现两次以上。
package dice;
import java.util.Scanner;
public class dice2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int k=0;
Scanner input1 =new Scanner(System.in);
Scanner input2 =new Scanner(System.in);
System.out.println("please enter the number of throws!");
int N=input1.nextInt();
int count=0;
String faces[]=new String[N];
System.out.println("enter the faces of the dice !");
while((N>=1) && (N<= 100) && (N!=count))
{
String x=input2.next();
switch(x) {
case "1":
faces[count]=x;
break;
case "2":
faces[count]=x;
break;
case "3":
faces[count]=x;
break;
case "4":
faces[count]=x;
break;
case "5":
faces[count]=x;
break;
case "6":
faces[count]=x;
break;
default : System.out.println(" enter 1-6");
}
count++;
}
for(int i=0;i<faces.length;i++) {
for(int j=i+1;j<faces.length;j++) {
if((faces[i].equals("6")) && (faces[j].equals("6")) )
{
k++; i=j;
}
else
break;
}
System.out.println("k is "+k);
}
}
答案 0 :(得分:0)
以下是仅打印连续出现的数字的工作代码:
public class dice
{
public static void main(String[] args)
{
String input = "11555677666551189988777"; //suppose you saved input using Scanner.Next() in 'input'
char[] number = new char[input.length()]; // will hold each distintive number
int[] occurence = new int[input.length()]; //will hold the occurence of that number
int j=0, distinct = 0, visited = -1;
for (int i = 0; i < input.length() - 1; i++)
{
// Counting occurrences of input[i]
while (input.charAt(i) == input.charAt(i + 1))
{
if(i!=0)
{
if (input.charAt(i) != input.charAt(i - 1))
{
number[j] = input.charAt(i);
distinct++;
j++;
}
}
else
{
number[j] = input.charAt(i);
distinct++;
j++;
}
i++;
if(i + 1 == input.length())
break;
}
}
for(int i = 0; i < distinct; i++)
{
int count = 1;
for(j = i+1; j < distinct; j++)
{
if(number[i] == number[j])
{
count++;
//To avoid counting same element again
occurence[j] = visited;
}
}
if(occurence[i] != visited)
occurence[i] = count;
}
System.out.println("----------------------------------------------");
System.out.println(" Element | Consecutive Occurence");
System.out.println("----------------------------------------------");
for(int i = 0; i < distinct; i++)
{
if(occurence[i] != visited)
System.out.println(" " + number[i] + " | " + occurence[i]);
}
System.out.printf("\nAll other numbers doesn't Occured Consecutively !!");
}
}
输出:
----------------------------------------------
Element | Consecutive Occurence
----------------------------------------------
6 | 3
1 | 1
4 | 1
All other numbers doesn't Occurred Consecutively !!!
希望这就是您想要的,请告诉我是否需要与此相关的其他事情。