【发布时间】:2017-01-24 12:09:14
【问题描述】:
我有一个任务,看起来很简单,但是我不知道如何解决它。
上面写着:
- 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));
}
}
我编译并运行。我有两个问题:
nextLine >>> 跳过第一句
我不知道如何让算法计算哪个单词/句子的值最大,或者使用 compareTo() 方法哪个单词/句子的值 > 0 与每个其他值相比在数组上。
谢谢。
【问题讨论】:
-
什么决定因素可以应用于“句子”以按字母顺序排序?
-
我不明白这个问题。如果你的意思是大写小写,没关系。一个词或一句话就可以做到。
-
对 Q 1 的回答:
num = input.nextInt();将数字作为输入,但也不会消耗换行符,因此nextLine会消耗空的换行符...您可以使用input.nextLine也可以通过读取一行来获取第一个数字而不是num = input.nextInt();,然后将 int 值解析为num = Integer.parseInt(input.nextLine()); -
您是否已经尝试编写算法来查找数组中的最大值?这是相同的想法,但使用 compareTo
-
我已经尝试了很多次,我想出的最好的就是这个:我不知道,它适用于 2 个单词/秒的句子,否则它不会,它只比较最后两个条目。 for (i=0;i
0){ last = sentence[i];我不知道,它适用于 2 个单词/秒的句子,否则它不会,它只比较最后两个条目。计数++; }else if (sentence[i].compareTo(sentence[i+1])
标签: java arrays alphabetical