gpt4 book ai didi

Java基本循环

转载 作者:行者123 更新时间:2023-12-01 15:05:04 25 4
gpt4 key购买 nike

我不知道为什么我的第二个 for 循环不会执行。它可以编译,但是当我运行它时它不起作用 ~_~

import java.util.Scanner;

public class ranges
{


public static void main (String[] args)

{

Scanner scan = new Scanner (System.in);

int size;
int input;
int count = 0;
int occurence = 0;
System.out.print ("Please enter the size of your array: ");
size = scan.nextInt();
int[] list = new int[size];



for (int index = 0 ; index < list.length ; index++)
{
System.out.print ("Please enter an integer between 0 to 50: ");
input = scan.nextInt();

if ( input >= 0 && input <= 50 )
{
list[index] = input;
}
else
{
System.out.println ("Invalid output, please try again");
index--;
}
}




int right = (list.length)-1;
int left = 0;

for (int counter = left ; counter < list.length ; counter++)
{
while ( right >= left )
{
if ( list[left] == list[right] )
{
occurence++;
right--;
}
}
right = (list.length)-1;
System.out.println ("The number " + list[left] + " was added " + occurence + "4 times");
}

for (int value : list)
{
System.out.print (value + " ");
}
;








}
}

我更新了 for 循环来评估事件

for (int left = 0 ; left < list.length ; left++)

{

        while ( right >= left )
{
if ( list[left] == list[right] )
{
occurence++;

}
right--;
}


System.out.println ("The number " + list[left] + " was added " + occurence + " times");
right = (list.length)-1;
occurence = 0;
}

我已经对其进行了一些清理,现在出现的情况与输入相同

最佳答案

你第二for也在工作。问题出在while循环条件即while ( right >= left ) 。如果list[left] == list[right]不相等,它会进入无限循环,因为 right也不left在这种情况下会发生变化。

我认为,你需要改变你的while如下(将 right-- 移至 if 条件之外):

  while ( right >= left )
{
if ( list[left] == list[right] )
{
occurence++;
}
right--;
}

另外两个问题:

重新初始化 occurence =0;在 while 循环之前,以便计算每个数字的出现次数并删除 4来自您的System.out.println()例如如下:

for (int counter = left ; counter < list.length ; counter++)
{
occurence = 0; //< initialize to 0
while ( right >= left )
{
if ( list[left] == list[right] )
{
occurence++;
}
right--;
}
right = (list.length)-1;
//remove 4 after "occurance +"
System.out.println ("The number " + list[left] +
" was added " + occurence + " times");
}

编辑:使用 HashMap 的工作示例:

       Map<Integer, Integer> scannedNums = new HashMap<Integer, Integer>();
for (int counter = left ; counter < list.length ; counter++)
{
if(scannedNums.get(list[counter]) == null){
scannedNums.put(list[counter], 1);
}else{
int currentCount = scannedNums.get(list[counter]);
scannedNums.put(list[counter], currentCount+1);
}
}

Set<Integer> nums = scannedNums.keySet();
Iterator<Integer> numIter = nums.iterator();
while(numIter.hasNext()){
int number = numIter.next();
System.out.println ("The number " + number +
" was added " + scannedNums.get(number) + " times");
}

关于Java基本循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13077626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com