Home » Java » java – Integrating a boolean into an array parameter-Exceptionshub

java – Integrating a boolean into an array parameter-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I need to create an array of random numbers using user inputted parameters(size, highest random number, lowest random number) and also include a boolean that dictates weather the highest number will be included in the random numbers or not. The boolean is whats causing me runtime errors. I cant figure out whats going wrong. i’ve tried if statements as well as switch statements but i dont think the problem is there. If you guys could help me id really appreciate it. I come here for many questions but this is my first time posting so sorry if my etiquette is wrong. here is my code thus far:

import  java.util.*;

public class Question1 {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    boolean yesNo = false;
    String yesOrNo;
    int highest;

    System.out.print("Please enter array size: ");
    int size = scan.nextInt();

    System.out.print("Please enter highest number: ");
    int high = scan.nextInt();

    System.out.print("Please enter lowest number: ");
    int low = scan.nextInt();

    System.out.print("Would you like to include " + high +" into the list of random numbers(Yes or No)?");
    yesOrNo = scan.nextLine();

    switch (yesOrNo.toUpperCase()) {
    case "YES":
        yesNo = true;
        break;
    }
    if (yesNo==true)
        high=high+1;

    randomNumberGenerator(size,high,low);
    }


public static void randomNumberGenerator(int size, int high, int low) {
    int[] randomNums = new int [size];
    for(int count = 0; count<randomNums.length; count++) {
        Random generator = new Random();
        int num = generator.nextInt(high) + (low);
        randomNums[count] = num;
    }
    System.out.print(Arrays.toString(randomNums));
 }  
 }

Please enter array size: 10
Please enter highest number: 5
Please enter lowest number: 0
Would you like to incloud 5 into the list of random numbers(Yes or No)?[0, 0, 2, 1, 2, 4, 3, 3, 0, 2]
-----------------------------------------------------------

it seems like the array is skipping over the boolean section of my code and im not sure why.
How to&Answers:

write “scan.nextLine();” after “YesOrNo = scan.nextLine” and it will show u the yes/no line

Answer:

Try as below –

System.out.print("Would you like to include " + high + " into the list of random numbers(Yes or No)?");
yesOrNo = scan.next();

Because of previous nextInt() method, nextLine() is getting skipped.

More explanation here – https://stackoverflow.com/a/13102066