Search code examples
javaarraysalphabetical

Last word/sentence on an Array Java


I have an assignment, it looks pretty easy however I cannot figure it out how to solve it.

It says:

  • a) Ask the user: How many words/sentences do you want to write (at least 5) ? (Use while loop)
  • b) Use for loop to make the user write the words/sentences
  • c) After the user's written the words/sentences, output which word/sentence comes last alphabetically (using .compareTo() method )

This is what I came up with:

import java.util.Scanner;
import java.lang.String;
import java.util.Arrays;

public class LastString {
public static void main (String [] args){
Scanner input = new Scanner (System.in);

final short MIN_NUM = 2;
int num = 0;
int count = 0;
String [] sentence = new String [0];
String last = "";

while (num < MIN_NUM){
  System.out.println("How many words/sentences do you want to put? " + "\t\t\t\t\t\t\t\t --- at least " + MIN_NUM);
  num = input.nextInt();
  sentence = new String [num];
}


for (int i = 0; i < num ; i++ ) {
  System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
  sentence [i] = input.nextLine();
  System.out.println("The word/sentence is:  " + sentence[i]);
}

int i = 0;
int max;

for (i=0;i<num-1 ;i++ ) {
  if(sentence[i].compareTo(sentence[i+1]) > 0){
    last = sentence[i];
    count ++;
  }else if (sentence[i].compareTo(sentence[i+1]) < 0) {
      last = sentence[i+1];
      count++;
  }
}

System.out.println("\n\n------------" +
                  "\nLast word/sentence is: " + last);



System.out.println(Arrays.toString(sentence));

}

}

I compiles and runs. I have two problems:

  1. nextLine >>> it is skiping the first Sentence

  2. I don't know how to make the algorithm to calculate which word/sentence has the biggest value or, using the compareTo() method which word/sentence has the value > 0 compared to each and every other value on the array.

Thank you.


Solution

  • Answer to Q1 : num = input.nextInt(); takes a number as the input but doesn't also consume the new-line, and hence the nextLine consumes the empty new line ... you could use input.nextLine also to get the first number instead of num = input.nextInt(); by reading a line, then parsing the int value as num = Integer.parseInt(input.nextLine());

    Answer to Q2 :

    You re-set the value of last everytime but you don't compare the value of the next biggest candidate with the last before re-assigning last ...

    for example, look at the following :

    for (int i = 0; i < num - 1; i++) {
        String thisLast = "";
        if (sentence[i].compareTo(sentence[i + 1]) > 0) {
            thisLast = sentence[i];
            count++;
        } else if (sentence[i].compareTo(sentence[i + 1]) < 0) {
            thisLast = sentence[i + 1];
            count++;
        }
    
        if (thisLast.compareTo(last) > 0)
            last = thisLast;
    
    }