簡體   English   中英

數組Java上的最后一句話

[英]Last word/sentence on an Array Java

我有一個作業,看起來很簡單,但是我無法弄清楚如何解決它。

它說:

  • a)問用戶:您要寫多少個單詞/句子(至少5個)? (使用while循環)
  • b)使用for循環使用戶寫出單詞/句子
  • c)用戶寫完單詞/句子后,輸出按字母順序最后出現的單詞/句子(使用.compareTo()方法)

這是我想出的:

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));

}

}

我編譯並運行。 我有兩個問題:

  1. nextLine >>>它正在跳過第一個句子

  2. 我不知道如何使算法來計算哪個單詞/句子的值最大,或者使用compareTo()方法將哪個單詞/句子的值與數組中的每個其他值相比都> 0。

謝謝。

對問題1的回答: num = input.nextInt(); 接受一個數字作為輸入但不占用換行符,因此nextLine占用空的換行符...您也可以使用input.nextLine來獲取第一個數字,而不是num = input.nextInt(); 通過讀取一行,然后將int值解析為num = Integer.parseInt(input.nextLine());

回答第二季度:

您重新設置的值, last每次但你沒有未來最大的候選值與比較last重新分配前年...

例如,查看以下內容:

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;

}

它將解決您的問題。

    int count = 0;
    String [] sentence = new String[6];
    String last = "";
    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();
      count++;
      if(count >= 2){
          if(sentence[i].compareTo(last) > 0){
              last = sentence [i] ;
          }
      }else{
          last = sentence [i];
      }
      System.out.println("The word/sentence is:  " + sentence[i]);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM