比较字符串(用户键入任意数量的字符串),然后使用for循环判断哪一个字符串是第一个字符串(根据第一个字母是第一个)



首先我必须让用户键入一个数字。这个数字将决定他必须键入多少句子(应该大于2(,然后我必须比较这些句子。我必须根据字母顺序来判断哪一个排在第一位。到目前为止,我只做了这些。我不知道如何比较字符串,因为我不知道用户会键入多少字符串,也不知道它们的名称。

import java.util.*;
public class Sentences {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = 0;
while (number < 2) {
System.out.println("Type a number > 2");
number = scan.nextInt();
}
scan.nextLine();
String sentence;
int y = 0;
for (int i = 0; i < number; i++) {
System.out.println("Type a sentence");
sentence = scan.nextLine();
}
}
}

你很接近。您需要一个数组(sentences[](,而不是单个变量(sentence(,如下所示:

import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = 0;
while (number < 2) {
System.out.print("Type a number > 2: ");
number = Integer.parseInt(scan.nextLine());
}
String[] sentences = new String[number];
int y = 0;
for (int i = 0; i < number; i++) {
System.out.print("Type a sentence: ");
sentences[i] = scan.nextLine();
}
Arrays.sort(sentences);
for (String sentence : sentences) {
System.out.println(sentence);
}
}
}

要对String sentences[]进行排序,您需要使用如上所示的Arrays.sort(sentences)

样本运行:

Type a number > 2: 0
Type a number > 2: 3
Type a sentence: Hello world
Type a sentence: You are awesome
Type a sentence: My name is Jane
Hello world
My name is Jane
You are awesome

[更新]

根据你的澄清,你只想打印一个按字母顺序最低的句子。这就像从数字列表中跟踪最小的数字。

算法如下:

  1. 存储变量的第一个输入,比如lowestAlphabetical
  2. 在循环中,将lowestAlphabetical的值与下一输入进行比较,如果下一输入按字母顺序较低,则将下一输入放入lowestAlphabetical

演示:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = 0;
while (number < 2) {
System.out.print("Type a number > 2: ");
number = Integer.parseInt(scan.nextLine());
}
// Scan the first sentence
System.out.print("Type a sentence: ");
String sentence = scan.nextLine();
// Since we have only one sentence till now, it is also the lowest in
// alphabetical order
String lowestAlphabetical = sentence;
// Loop for next inputs
for (int i = 1; i < number; i++) {
System.out.print("Type the next sentence: ");
sentence = scan.nextLine();
if (sentence.compareTo(lowestAlphabetical) < 0) {
lowestAlphabetical = sentence;
}
}
System.out.println(lowestAlphabetical);
}
}

样本运行:

Type a number > 2: 3
Type a sentence: Hello world
Type the next sentence: Good morning
Type the next sentence: My name is Jane
Good morning

最新更新