나는 작동하는 아래 코드를 작성했지만 인쇄 할 때 문장이 아닌 순서대로 등급 만 인쇄합니다. 순서대로 주어진 등급에 따라 문장을 어떻게 정렬합니까 ??
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]);
}
}
이 특정 문제를 해결하기 위해 코드를 제공하는 것보다 훨씬 직관적으로 만들기 위해 재구성하는 방법에 대한 포인터를 제공 할 것입니다. 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);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다