1

(I'm a beginner at Java) I am trying to write a program that asks for 6 digits from the user using a scanner, then from those 6 individual digits find the second highest number. So far this works however I'd like to have the input read from a single line rather than 6 separate lines. I've heard of delimiters and tokenisation, but have no idea how to implement it. I'ld like to have it read like "Enter 6 digits: 1 2 3 4 5 6" and parsing each digit as a separate variable so i can then place them in an array as shown. If anyone could give me a run-down of how this would work it would be much appreciated. Cheers for your time.

    public static void main(String[] args)
    {
        //Ask user input 
        System.out.println("Enter 6 digits: ");            
        //New Scanner
        Scanner input = new Scanner(System.in);

        //Assign 6 variables for each digit
        int num1 = input.nextInt();            
        int num2 = input.nextInt();            
        int num3 = input.nextInt();            
        int num4 = input.nextInt();            
        int num5 = input.nextInt();            
        int num6 = input.nextInt();            

      //unsorted array
      int num[] = {num1, num2, num3, num4, num5, num6};     
      //Length 
      int n = num.length;     
       //Sort 
      Arrays.sort(num);
       //After sorting
      // Second highest number is at n-2 position

       System.out.println("Second highest Number: "+num[n-2]);

 }           
}   
8
  • 3
    Read in the line as a string, split the string, parse ints from the split string. All of these tasks are extensively detailed online. Commented Mar 10, 2020 at 12:28
  • and ..; what exactly is your question? Commented Mar 10, 2020 at 12:28
  • @Stultuske how do i obtain separate int variables from a single line from a scanner so i may place them in an array. thanks. Commented Mar 10, 2020 at 12:30
  • 1
    @utnicho sleepToken already explained the steps to take Commented Mar 10, 2020 at 12:31
  • @sleepToken sorry man i just started java a few days ago, so i should just change the variable type to String for my scanner? Commented Mar 10, 2020 at 12:33

3 Answers 3

0

Your solution does this allready!

If you go through the documentation of scaner you will find out that your code works with different inputs, as long they are integers separated by whitespace and/or line seperators.

But you can optimice your code, to let it look nicer:

public static void main6(String[] args) {
    // Ask user input
    System.out.println("Enter 6 digits: ");
    // New Scanner
    Scanner input = new Scanner(System.in);

    // Assign 6 variables for each digit
    int size=6;
    int[] num=new int[size];
    for (int i=0;i<size;i++) {
        num[i]=input.nextInt();
    }
    Arrays.sort(num);
    // After sorting
    // Second highest number is at n-2 position

    System.out.println("Second highest Number: " + num[size - 2]);
}

As an additional hint, i like to mention this code still produces lot of overhead you can avoid this by using:

public static void main7(String[] args) {
    // Ask user input
    System.out.println("Enter 6 digits: ");
    // New Scanner
    Scanner input = new Scanner(System.in);

    // Assign 6 variables for each digit
    int size=6;
    int highest=Integer.MIN_VALUE;
    int secondhighest=Integer.MIN_VALUE;
    for (int i=0;i<size-1;i++) {
        int value=input.nextInt();
        if (value>highest) {
            secondhighest=highest;
            highest=value;
        } else if (value>secondhighest) {
            secondhighest=value;
        }
    }
    //give out second highest
    System.out.println("Second highest Number: " + secondhighest);
}

if you do not like to point on highest if there are multiple highest, you can replace the else if:

public static void main7(String[] args) {
    // Ask user input
    System.out.println("Enter 6 digits: ");
    // New Scanner
    Scanner input = new Scanner(System.in);

    // Assign 6 variables for each digit
    int size = 6;
    int highest = Integer.MIN_VALUE;
    int secondhighest = Integer.MIN_VALUE;
    for (int i = 0; i < size - 1; i++) {
        int value = input.nextInt();
        if (value > highest) {
            secondhighest = highest;
            highest = value;
        } else if (secondhighest==Integer.MIN_VALUE&&value!=highest) {
            secondhighest=value;
        }
    }
    // give out second highest
    System.out.println("Second highest Number: " + secondhighest);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Of course, there are many ways to do that. I will give you two ways: 1. Use lambda functions - this way is more advanced but very practical:

Integer[] s = Arrays.stream(input.nextLine().split(" ")).map(Integer::parseInt).toArray(Integer[]::new);
  • first create a stream, you can read more about streams here
  • than read the whole line "1 2 3 ...."
  • split the line by space " " and after this point the stream will look like ["1", "2", "3" ....]
  • to convert the strings to int "map" operator is used
  • and finally collect the stream into Integer[]

    1. You can use an iterator and loop as many times as you need and read from the console.

      int num[] = new int[6]; for (int i = 0; i < 6; i++) { num[i] = input.nextInt(); }

Comments

0

There are several ways to do that:

take a single line string, then parse it.

        Scanner input = new Scanner(System.in);

        ....
        String numString = input.nextLine();
        String[] split = numString.split("\\s+");
        int num[] = new int[split];
        // assuming there will be always atleast 6 numbers.
        for (int i = 0; i < split.length; i++) {
            num[i] = Integer.parseInt(split[i]);
        }
        ... 
      //Sort 
      Arrays.sort(num);
       //After sorting
      // Second highest number is at n-2 position

       System.out.println("Second highest Number: "+num[n-2]);

2 Comments

your first option isn't valid, since it doesn't meet the OP's requirements of having all the numbers on a single line. Your second limits it to max 6 numbers. use split.length instead of a hardcoded 6
@ruhul i think i understand what you did, so the new variable obtained from the scanner is numString right? Which is the string of numbers (e.g 1 2 3 4 5 6) however how do i put that into an array and then sort it? i keep getting errors when i try int num[numString]; thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.