gpt4 book ai didi

java - 为什么我会出现 0 的无限循环? ( java )

转载 作者:行者123 更新时间:2023-12-01 06:42:54 27 4
gpt4 key购买 nike

前几天我问了一个关于我的代码的问题,这个问题很快就被这里令人难以置信的社区解决了。然而,我使用代码的重写版本遇到了一个完全独立的问题。这是我上一篇文章中对该程序的描述。

I'm trying to write a program that can detect the largest sum that can be made with any subset of numbers in an ArrayList, and the sum must be lower than a user-input target number. My program is working flawlessly so far, with the exception of one line (no pun intended). Keep in mind that this code isn't complete yet too.

我现在的代码问题是,在用户输入目标数字后,程序输出一个0的无限循环。即使在尝试调试之后,我仍然遇到问题。 ArrayList 完美地应用于程序,但我认为我的 while 循环之一中可能存在问题。有什么想法吗?

这是代码。

import java.util.*;
class Sum{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int temp = 0, target = 1, result = 0, firstIndex = 0, secondIndex = 0;
String tempString = null;
ArrayList<String> list = new ArrayList<String>();
ArrayList<Integer> last = new ArrayList<Integer>();
System.out.println("Enter integers one at a time, pressing enter after each integer Type \"done\" when finished.\nOR just type \"done\" to use the default list.");
String placehold = "NotDone";

while (!placehold.equals("done")){
list.add(input.nextLine());
placehold = list.get(list.size() - 1);
}
list.remove(list.size() - 1);
if (list.size() == 0){ //Inserts default list if said list is empty
list.add("1");
list.add("2");
list.add("4");
list.add("5");
list.add("8");
list.add("12");
list.add("15");
list.add("21");
}
for (int i = 0; i < list.size(); i++){
tempString = list.get(i);
temp = Integer.parseInt(tempString); //Changes the items in the list to Integers, which can be inserted into another list and then sorted
last.add(temp);
}
Collections.sort(last);
System.out.println("Enter the target number");
target = input.nextInt();
while (result < target){
firstIndex = last.size() - 1;
secondIndex = firstIndex - 1;
while (last.get(firstIndex) > target){
firstIndex--;
}
if (last.get(firstIndex) + last.get(secondIndex) < result){
result = last.get(firstIndex) + last.get(secondIndex);
last.remove(firstIndex);
last.remove(secondIndex);
last.add(result);
}
else{
secondIndex--;
}
System.out.println(result);
}
}
}

以及输出...

Enter integers one at a time, pressing enter after each integer Type "done" when finished. OR just type "done" to use the default list.

done //Prompting to use the default list

Enter the target number

15 //User inputs target number

0 0 0 0 0 0 ... //And so on

最佳答案

target = input.nextInt();

应该在循环内,否则变量将永远不会改变

while(result<target)永远不会变成假

<小时/>
while(result<target) {
target = input.nextInt();
// otherCoolCode
}

关于java - 为什么我会出现 0 的无限循环? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36086903/

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