0

I am having a strange problem when trying to submit a class assignment. When I run the program it runs as intended but when uploading it and running the test cases on the code it spits out a java.util.NoSUchElementException error on line 31. I tried putting the code into its own method then calling it to see if it would change anything but it did not :(

The program is supposed to take an input from the user and then output the minimum and maximum values of the values that have been entered.

here is my code so far:

import java.util.Scanner;

public class MaxMin
{
    public static void main(String[] args)
    {   
        Scanner input = new Scanner(System.in);
        
        System.out.println("Enter a number (-1 to quit): ");
        int num = input.nextInt();
        
        minMax(num);
    }
    
    public static void minMax(int userInput) {
        Scanner input = new Scanner(System.in);
        
        int min = userInput;
        int max = userInput;
        
        while(userInput != -1) {
            if(userInput < min) {
                min = userInput;
            }
            else if (userInput > max){
                max = userInput;
            }
            System.out.println("Smallest # so far: " + min);
            System.out.println("Largest # so far: " + max);
            System.out.println("Enter a number (-1 to quit): ");
            userInput = input.nextInt();
        }
        
        System.out.println("You quit the program.");
    }
}

Any help on how to solve this problem would be greatly appreciated.

Linus
  • 115
  • 2
  • 10
  • @Linux/zwaka where are you uploading the code? – mss Jan 25 '21 at 21:05
  • You probably should have stated, that you've pressed the `-` button ...which is not `int`. – Martin Zeitler Jan 25 '21 at 21:08
  • @mss I am trying to upload it to a website called "codehs" and it is trying to check my code but is getting stuck somewhere and I can't find out why it's getting stuck :/ – Linus Jan 25 '21 at 21:39
  • @MartinZeitler Unfortunately not, I add the if statement suggested and the code runs, however, the code tester on the website I am using doesn't output anything at all. Blank screen. – Linus Jan 25 '21 at 21:45
  • 1
    @LinusZwaka I have not suggested to copy the accepted answer 1:1 (which only prevents the exception from happening). If you want to permit `-`, you probably shouldn't scan for `int` but cast to `int` (which is a signed data-type in Java). The business logic appears flawed to me, as it probably will never reach `minMax()` and therefore will produce no output at all. Likely you'd have to scan in a loop... as it currently looks alike, you can scan 1 single `int` only. – Martin Zeitler Jan 25 '21 at 21:50

0 Answers0