简体   繁体   English

为什么我得到0的无限循环? (Java)

[英]Why am I getting an infinite loop of 0's? (Java)

I asked a question about my code the other day, which was quickly resolved by the incredible community here. 前几天,我问了有关我的代码的问题,该问题很快被这里令人难以置信的社区解决。 However I have encountered a completely separate problem using a re-written version of my code. 但是,使用我的代码的重写版本遇到了一个完全独立的问题。 Here's a description of the program from my previous post. 这是我上一篇文章中对该程序的描述。

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. 我正在尝试编写一个程序,该程序可以检测到可以使用ArrayList中的任何数字子集得出的最大和,并且该总和必须小于用户输入的目标数字。 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. 请记住,该代码还没有完成。

My problem with the code now is that after the user inputs a target number, the program outputs an infinite loop of 0's. 我的代码现在的问题是,在用户输入目标数字之后,程序将输出一个无限的0循环。 Even after trying to debug, I still come up with problems. 即使尝试调试后,我仍然会遇到问题。 The ArrayList is being applied to the program perfectly fine, but I think I may have a problem somewhere within one of my while loops. ArrayList可以很好地应用于程序,但是我认为我的while循环之一中的某个地方可能有问题。 Any ideas? 有任何想法吗?

Heres the code. 这是代码。

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);
        }  
    }
}

And the Output... 和输出...

Enter integers one at a time, pressing enter after each integer Type "done" when finished. 一次输入一个整数,在每个整数之后按Enter键。完成后,键入“ done”。 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 15 //用户输入目标号码

0 0 0 0 0 0 ... //And so on 0 0 0 0 0 0 ... //以此类推

target = input.nextInt();

should be within your loop otherwise the variable will never change and 应该在循环内,否则变量将永远不会更改,

while(result<target) will never turn to false while(result<target)永远不会变成false


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

You are assigning target before the while loop, and you are not altering target any way inside the while loop. 您是在while循环之前分配target ,并且您不会在while循环内以任何方式更改target You need to prompt the user within the while loop. 您需要在while循环中提示用户。 Otherwise, if you set a target variable higher than 0, it will be an infinite loop. 否则,如果将target变量设置为大于0,则它将是一个无限循环。

The problem is in 问题出在

if (last.get(firstIndex) + last.get(secondIndex) < result) {
    ...
}

Result is always initialized to zero, so that condition will never be true. 结果总是初始化为零,因此条件永远不会为真。 One possible fix is to add an extra condition to handle this initial case: 一种可能的解决方案是添加一个额外条件来处理这种初始情况:

if (result == 0 || last.get(firstIndex) + last.get(secondIndex) < result) {
    ...
}

An infinite loop occurs when you have a loop whose condition(s) do not change during an iteration of the loop. 当您的循环在迭代过程中条件没有变化时,就会发生无限循环。

Let's review your loop: 让我们回顾一下您的循环:

  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); } 

Your loop will only end if result and/or target change so that result < target is false. 仅当result和/或target更改从而result < target为false时,循环才会结束。

Within your loop you assign to result only when (last.get(firstIndex) + last.get(secondIndex) < result) is true. 在循环中,仅当(last.get(firstIndex) + last.get(secondIndex) < result)为true时,才分配result So if that condition is false then result will not change. 因此,如果该条件为假,则结果将不会改变。

You have some additional state that is not in the loop condition itself but is manipulated by the loop: firstIndex and secondIndex . 您还有一些其他状态,它们不在循环条件本身中,而是由循环操纵的: firstIndexsecondIndex Every iteration of the loop you assign to them. 您分配给它们的循环的每次迭代。 You do have an 'else' clause where you modify secondIndex just before printing the current value of result , however you then immediately assign to it at the top of the loop. 您确实有一个'else'子句,在secondIndex之前,您在打印result的当前值之前修改了secondIndex但是您随后立即在循环的顶部对其进行了分配。

This is the crux of your infinite loop (when last.get(firstIndex) + last.get(secondIndex) < result is false) : 这是无限循环的关键(当last.get(firstIndex) + last.get(secondIndex) < result为false时)

  1. result doesn't change result没有改变
  2. Your list last isn't modified, thus last.size()-1 and firstIndex - 1 remain the same 您的清单last未被修改,因此last.size()-1firstIndex - 1保持不变
  3. You assign secondIndex = firstIndex - 1; 您分配secondIndex = firstIndex - 1; overwriting the decrement at the end of the loop, thus neither firstIndex nor secondIndex change 在循环结束时覆盖减量,因此firstIndexsecondIndex更改

In this line 在这条线

if (last.get(firstIndex) + last.get(secondIndex) < result) {

the sum of both your values will hardly ever be less than result, which is "0". 两个值的总和几乎不会小于结果,即“ 0”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在Java中的此模型中出现无限循环? - Why am I getting an infinite loop in this model in java? 我在Java输出中遇到无限循环 - I am getting infinite loop in java output 为什么/在哪里陷入无限循环 - Why / where am I getting stuck in an infinite loop 为什么我输入无效无限循环? - Why am I getting an input Invalid Infinite Loop? 不能理解为什么我会陷入无限循环。 Java。 如何在不键入exit的情况下触发EoF - Cant understand why i am getting an infinite loop. Java. How to trigger EoF without typing exit 为什么我的链表赋值的 printList() 方法中出现无限循环? - Why am I getting an infinite loop in my printList() method of my linked lists assignment? 为什么我在尝试使用这个 github 项目时陷入无限循环? - Why am I getting stuck in an infinite loop when trying to use this github project? 为什么一个接一个地调用两个Intent服务时出现无限循环? - Why am I getting an infinite loop when calling two Intent services, one after the other? 为什么我在高级for循环中收到java.util.ConcurrentModificationException? - why am i getting a java.util.ConcurrentModificationException in the advanced for loop? 我正在尝试在 kotlin 中无限循环打印一个表,但得到了这个(线程“主”中的异常 java.lang.OutOfMemoryError: ZD52387880E1EA22817A72D375921389) - i am trying to print a table in infinite loop in kotlin but getting this (Exception in thread "main" java.lang.OutOfMemoryError: Java heap space)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM