我试图在输入的数组中找到3的数量但是它出现了零或一个,所以我放置了System.out.print以查看我的数组是什么,它除了全部为零之外最后一个值。 我需要数组来保留它的所有值。
import java.util.Scanner;
public class FunArray1 {
static Scanner keyboard = new Scanner(System.in);
private static String input, command;
private static int a, b, i, j;
private static int[] inputArray;
private static int total, count;
public static void main(String[] args){
System.out.println("Enter A Command ::");
System.out.println("1. PNumber - Your Numbers!");
System.out.println("2. LCount - Your Lucky Numbers!");
System.out.println("3. LTotal - Your Lucky Total!");
command = keyboard.nextLine();
if (command.equals("PNumber")){
Coverter();
purifiedNumbers(inputArray);
}
if (command.equals("LCount")){
Coverter();
luckyCount(inputArray);
System.out.println("Your Lucky Number Count is "+count);
}
if (command.equals("LTotal")){
Coverter();
luckyTotal(inputArray);
}
}
private static void purifiedNumbers(int[] e){
}
private static int luckyCount(int[] e){
for (i = 0; i<inputArray.length; i++){
System.out.println((int)inputArray[i]);
if (inputArray[i] == 3){
count++;
}
}
return count;
}
private static void luckyTotal(int[] e) {
for (i = 0; i<inputArray.length; i++){
for(j = 3; j<inputArray.length; j++){
total += inputArray[j];
if(j == 5){
i = j;
break;
}
}
}
System.out.println(total);
}
private static int[] Coverter(){
System.out.println("Enter Your Life Numbers! ::");
input = keyboard.nextLine();
String[]Covert = input.split(" ");
for (a = 0; a<Covert.length; a++){
inputArray = new int[Covert.length];
inputArray[a] = Integer.parseInt(Covert[a]);
}
return inputArray;
}
}
答案 0 :(得分:1)
将数组初始化移到循环外部,
inputArray = new int[Covert.length];
for (a = 0; a<Covert.length; a++){
// inputArray = new int[Covert.length];
inputArray[a] = Integer.parseInt(Covert[a]);
}
或者你将在每次迭代时抛弃前一个实例(及其值)。并且只在最后一个位置有一个值(正如您在问题中描述的那样)。