我设法编写下面的代码,但是在打印时,它只按顺序打印评级而不是句子。如何按顺序给出的评级对句子进行排序?
public static void loopswithinloops()
{
String[] sentences = {"I am blessed to have you in my life. You are the one thing in my life that is true and real",
"I am honoured to have you by my side to love and to cherish each day of our lives.",
"More precious than any other thing in my life is to see your face each and every day",
"To wake up beside you is a treasure that I have found in you and that I am thankful for.",
"Your beautiful eyes dance bright and clear and I can see forever in your eyes." };
for (int i=0; i<=1; i++)
{
ratemessage(sentences); //this will loop the whole rating message two times from 0 to 1.
}
}
public static void ratemessage (String[] sentences) // this will receive the argument from the method defined above and then be printed below as shown.
{
int[] result = new int[sentences.length];//you have to give the array a size
String inputStr;
for (int i = 0; i < sentences.length; i++)
{
JOptionPane.showMessageDialog(null, sentences[i]);//the sentences one at at time
inputStr = JOptionPane.showInputDialog("what do you rate this sentence out of 10?");
result[i] = (int)Float.parseFloat(inputStr);//put the input into the array - it comes as a float so you'll have to cast it to int
}
sort (result, sentences);
printsort (result, sentences);
}
public static void sort( int [] result , String [] sentences)
{
int temp;
for(int i = 0; i < result.length; i++)
{
for(int j = 1; j < (result.length -i); j++)
{
//if numbers[j-1] > numbers[j], swap the elements
if(result[j-1] > result[j])
{
temp = result[j-1];
result[j-1]=result[j];
result[j]=temp;
}
}
}
}
public static void printsort (int [] result , String [] sentences)
{
System.out.println("The ratings go in ascending order: ");
for(int i = 0; i < result.length; i++)
{
System.out.println("Your ascending rating is " + result[i]+ " " + sentences[i]);
}
}
答案 0 :(得分:0)
我不会仅提供修复此特定问题的代码,而是指示如何对其进行重组以使其更加直观。我使用的是Java 8功能,但如果需要,可以轻松转换回来。
创建一个同时包含消息和评级的类。
public class RatedMessage {
private final String message;
private final int rating;
public RatedMessage(String message, int rating) {
this.message = message;
this.rating = rating;
}
public String toString() {
return rating + ": " + message;
}
public static int compareRating(RatedMessage rm1, RatedMessage rm2) {
return rm1.rating - rm2.rating;
}
}
然后创建一个RatedMessage对象列表
List<RatedMessage> ratedMessages = new ArrayList<>();
更改您的邮件评分方法,为每条评分的邮件创建一个RatedMessage,并将其添加到列表中。
ratedMessages.add(new RatedMessage(message, rating));
然后使用评分对您的列表进行排序:
Collections.sort(ratedMessages, RatedMessage::compareRatings);
然后打印出排序列表:
ratedMessages.stream().map(RatedMessage::toString).forEach(System.out::println);