Intellij Idea While循环的输入不显示任何类型的输入或结果提示

vddsk6oq  于 2023-10-15  发布在  其他
关注(0)|答案(3)|浏览(97)

我目前正在编写一个程序作为类的练习,其中提示用户输入一系列数字,输入应以0结束。当程序与输入的正数接触时,它应该能够将变量的正和加1。程序应该能够在与输入中的负数接触时向变量负和加1。程序应该把所有这些数字加在一起,以获得总数。程序应该能够得到平均值并将其显示为双精度。
当我尝试运行这个程序时,我得到了一个路径,指向我的下载文件夹中intellij所在的目录。
我不确定我能尝试什么不同的方式。IDE中没有弹出错误警告。
这是我的代码:
` import java.util.Scanner;

public class LoopPractice {
public static void main(String[] args) {
//create scanner object
    Scanner input = new Scanner(System.in);

    int positiveSum = 0;
    int negativeSum = 0;
    int numberOfPositive = 0;
    int numberOfNegative = 0;
    int totalNumbers = 0;
    int integers = input.nextInt();

    while(integers != 0){
        System.out.println("Enter integers ending with 0: ");
        integers = input.nextInt();

            if (integers > 0) {
                positiveSum += integers;
                numberOfPositive++;
                totalNumbers++;
                System.out.println("The number of positives is " + positiveSum);

            } else  if (integers < 0) {
                negativeSum += integers;
                numberOfNegative++;
                totalNumbers++;
                System.out.println("The number of negatives is " + negativeSum);
            }
        double average =  (numberOfPositive + numberOfNegative) / totalNumbers;
        System.out.println("The total is: " + totalNumbers);
            System.out.println("The average is: " + average);
            }
        }
     }

`

myzjeezk

myzjeezk1#

当你执行你的代码时,它停止在
“int nums = nums();“
并期望您在向下循环之前提供输入。在声明int变量时调用了nextInt()方法,因此扫描器需要一个int输入。这就是为什么在intellij目录后会看到空白。
我对你的代码做了一点调整,其余部分保持不变。我在你声明integers变量之前打印了一条语句。所以,当你进入循环时,你提供的第一个输入计数,一旦循环结束,我们再次检查新的输入。(或者,你可以按照Reilas的建议使用do while循环)
更改了几个变量名numberOfPositive > positiveValue。.等等。
public static void main(String[] args){ Scanner input = new Scanner(System.in);

int positiveSum = 0;
    int negativeSum = 0;
    int PositveEntries = 0;
    int NegativeEntries = 0;
    int totalEntries = 0;
    int totalSum;
    double average;


    System.out.println("Enter integers ending with 0: ");
    int integers = input.nextInt();

    while(integers != 0){


        if (integers > 0) {
            positiveSum += integers;
            PositveEntries++;
            totalEntries++;
            System.out.println("Sum of positive entries " + positiveSum);

        } else  if (integers < 0) {
            negativeSum += integers;
            NegativeEntries++;
            totalEntries++;
            System.out.println("Sum of negative entries " + negativeSum);
        }
        totalSum = positiveSum + negativeSum;
        average =  totalSum / totalEntries;
        System.out.println("Total sum = " + totalSum + ". Average = "+ average);

        System.out.println("Enter another sum or enter 0 to terminate");
        integers = input.nextInt();
    }
    System.out.println("program terminated");


}
8ljdwjyq

8ljdwjyq2#

使用一个 *do-while循环 * 和一个 boolean
此外,您可以将 * BigInteger * 类用于 positiveSumnegativeSum
这里有一个例子。

import static java.math.BigInteger.ZERO;
import java.math.BigInteger;
import java.util.Scanner;
Scanner in = new Scanner(System.in);
int i;
BigInteger x, a = ZERO, b = ZERO;
boolean exit = false;
do {
    x = in.nextBigInteger();
    i = x.compareTo(ZERO);
    if (i == 0) exit = true;
    else if (i < 0) a = a.add(x);
    else b = b.add(x);
} while (!exit);

输出

z4bn682m

z4bn682m3#

"When I do try running the program, I get a pathway to the directory in which intellij is held in my downloads folder."
我完全不知道你是什么意思:/但是,它看起来更像是一个IntelliJ设置问题,而不是你确实有一个实际的代码问题。你是如何运行代码来解决这个问题的?在你发布的问题中解释一下。
下面是一个可运行的例子,解释了如何使用用户输入验证来完成这一点(阅读代码中的注解-注解使代码看起来很像,但实际上不是。如果你喜欢的话,你可以删除它们:
演示中使用的唯一扫描器方法是Scanner#nextLine()方法,我认为它提供了更好的输入控制,但这只是我的意见。为了执行用户输入验证,演示使用了String#matches()方法,该方法传递了一个小的Regular Expression(regex):"-?\\d+"基本上是这样的:

  • -?数字字符串可以以减号开头,也可以不以减号开头,表示字符串值是有符号的(如果有,则为负数)还是无符号的(如果没有,则为正数);
  • \\d+数字字符串只包含0到**9* 的 * 一个或多个 * 数字。
public class LoopPractice {
    // A variable to hold the OS dependent newline character sequence:
    private final String ls = System.lineSeparator();
    
    // Declare a Scanner Object:
    private java.util.Scanner input;

    
    // Application Entry Point:
    public static void main(String[] args) {
        /* App is opened this way to avoid the need for 
           statics (unless we want them):        */
        new LoopPractice().startApp(args);
    }
    
    private void startApp(String[] args) {
        /* Open a keyboard input stream. Do Not close this particular stream!
           The JVM will close this resource automatically when the application 
           closes.        */
        input = new java.util.Scanner(System.in);
        
        // A List Interface of Integer to hold supplied unsigned (positive)integer numbers:
        java.util.List<Integer> unsignedInts = new java.util.ArrayList<>();
        
        // A List Interface of Integer to hold supplied signed (negative) integer numbers:
        java.util.List<Integer> signedInts = new java.util.ArrayList<>();
        
        // Will hold the actual valid integer number supplied once converted:
        int intNumber;
        
        /* Will hold the current prompt count so the User always
           knows what the numbers count is they are currently
           working on:        */
        int cnt = 0; 
        
        /* This variable will actually hold the User's numberical input
           and yes, it is of type String. I like to accept string input
           from the User because I think it's easier to validate and 
           other things like "(q to quit)" can be added to the prompt.
           There should be no need to catch Exceptions for input 
           validation:        */
        String numString;
        
        /* Boolean Flag used as the condition for the outer `while` 
           loop. If false, we keep looping. If true, we exit the 
           loop:                   */
        boolean quit = false;
       
        /* Describe what is "expeted" from the User. 
           This greatly helps the User make proper 
           entries:                            */
        System.out.println("Enter a series of valid signed or unsigned integers." + ls
                         + "All the numbers you supply MUST end with 0 otherwise" + ls
                         + "that number will be considered Invalid and you will " + ls
                         + "need to re-enter the desired number. Entering just 0" + ls
                         + "is Invalid as is any number that contains alpha type " + ls
                         + "characters. The integer numbers you supply can not be" + ls
                         + "less than the value of  -2147483648  and, can not be " + ls
                         + "greater than the value of 2147483647:" + ls);
       // Keep looping while the `quit` variable holds false:
        while (!quit) {
            numString = ""; // Set `numString` to Null String (""):
            
            /* Keep looping while the `numString` variable is 
               Empty (holds Null String(""):            */
            while (numString.isEmpty()) {
                cnt++;  // Increment the prompt counter by 1
                // Display the prompt to User:
                System.out.print("Enter Integer #" + cnt + " (or q to quit): -> ");
                
                /* Get keyboard input from User. The code halts here
                   and waits for the User to enter something from the 
                   keyboard and hit the ENTER key:                */
                numString = input.nextLine().trim();
                
                // Is quit desired......
                if (numString.equalsIgnoreCase("q")) {
                    /* Yes...set the `quit` variable to boolean true 
                       and exit this inner loop:                */
                    quit = true;
                    break;
                }
                
                // INPUT VALIDATION:
                /* Is the supplied string representation of a numerical 
                   value a signed or unsigned integer value which contains 
                   a 0 on the end, is greater than Integer.MIN_VALUE (-2147483648)
                   and is less than Integer.MAX_VALUE (2147483647), and 
                   finally, is not just 0:
                */
                if (!numString.matches("-?\\d+") || !numString.endsWith("0")
                                                 || Long.parseLong(numString) < Integer.MIN_VALUE
                                                 || Long.parseLong(numString) > Integer.MAX_VALUE
                                                 || Integer.parseInt(numString) == 0) {
                    // NO...Inform the User of an Invalid Entry and to try again...
                    System.out.println("Invalid Numerical Entry (" + numString + ")! - Try again..." + ls);
                    // Decrement the prompt counter because of an Invalid Entry:
                    cnt--; 
                    /* Empty the `numString` variable to ensure re-loop
                       so the User can try again:             */
                    numString = "";
                }
            }
            
            /* If we get to this point then either `q` for quit 
               was entered or a VALID integer value was supplied.  */
            if (quit) {
                continue;
            }
            
            // Convert the String numerical value to int:
            intNumber = Integer.parseInt(numString);
            
            /* If the supplied integer number is greater than 0
               then the value supplied is an unsigned (positive)
               integer number so, add it to the `unsignedInts`
               List otherwise add it to the   `signedInts` List.
               We know it can't be 0 because that wouldn't have
               passed validation: We used an `if` statement with 
               Ternary Operator for this:               */
            if (intNumber > 0 ? unsignedInts.add(intNumber) : signedInts.add(intNumber));
        }
        
        /* Count the total number of Integer values the User supplied.
           These values are held within the `unsignedInts` and the 
           `signedInts` Lists so, to find out how many VALID numbers
           were entered, we sum together the size of both lists:   */
        int totalNumberOfInts = (unsignedInts.size() + signedInts.size());
        
        /* If both Lists contain nothing then `totalNumberOfInts` would
           contain 0. Chances are, the `q` for quit was supplied before 
           any valid integer numbers could be established so, inform the
           User that there is nothing to report and return which will
           effectively end the application (or the entry session):   */
        if (totalNumberOfInts == 0) {
            System.out.println("No Results To Show!" + ls + "Quiting - Bye Bye");
            return;
        }
        
        // Otherwise, report the results of the values that were entered then quit.
        
        // Sum the values containd within the `unsignedInts` List:
        int sumOfUnsignedIntegers = unsignedInts.stream().mapToInt(Integer::intValue).sum();
        
        // Sum the values containd within the `signedInts` List:
        int sumOfSignedIntegers = signedInts.stream().mapToInt(Integer::intValue).sum();
        
        // Acquire the Overall Sum of the two Lists:
        int overallSum = (sumOfUnsignedIntegers + sumOfSignedIntegers);
        
        // Start displaying the calcualted results into the Console Window:
        System.out.println();
        System.out.println("The total number integers supplied was:            " 
                            + totalNumberOfInts);
        System.out.println("The number of unsigned (positive) integers is:     " 
                            + unsignedInts.size() + "  ->  " + unsignedInts);
        System.out.println("The number of signed (negative) integers is:       " 
                            + signedInts.size() + "  ->  " + signedInts);
        System.out.println("The total sum of unsigned integers is:             " 
                            + sumOfUnsignedIntegers);
        System.out.println("The total sum of signed (negative) integers is:    " 
                            + sumOfSignedIntegers);
        System.out.println("The overall total sum of all supplied integers is: " 
                            + overallSum);
        
        // Calculate the Average (cast the int's to doubles):
        double average = ((double)overallSum / (double)totalNumberOfInts);
        
        // Display the Average within the Console Window:
        System.out.println("The overall Average is:                            " 
                            + average);
        
        // Inform of Quiting:
        System.out.println(ls + "Quiting - Bye Bye" + ls);
    }   
}

相关问题