我有一项任务,看起来很容易,但我无法弄清楚如何解决它。
它说:
这就是我提出的:
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&gt;&gt;&gt;它正在滑动第一句
我不知道如何使算法计算哪个单词/句子具有最大值,或者使用compareTo()方法,其中单词/句子的值为&gt; 0与阵列上的每个其他值相比。
谢谢。
答案 0 :(得分:0)
对Q1的回答:num = input.nextInt();
以数字作为输入,但也不使用新行,因此nextLine
消耗空的新行...你可以使用{{通过读取一行来获取第一个数而不是input.nextLine
,然后将int值解析为num = input.nextInt();
回答Q2:
您每次都会重新设置num = Integer.parseInt(input.nextLine());
的值,但在重新分配最后一次之前,您不会将下一个最大候选人的值与last
进行比较...
last
答案 1 :(得分:0)
它会解决你的问题......
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]);
}