[英]Last word/sentence on an Array Java
我有一個作業,看起來很簡單,但是我無法弄清楚如何解決它。
它說:
這是我想出的:
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));
}
}
我編譯並運行。 我有兩個問題:
nextLine >>>它正在跳過第一個句子
我不知道如何使算法來計算哪個單詞/句子的值最大,或者使用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.