Java Alphabetizing Strings [英] Java Alphabetizing Strings

查看:113
本文介绍了Java Alphabetizing Strings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个课程项目,我需要输入4个不同的字符串,然后按字母顺序输出。

I have a project for class were I need to get 4 different strings inputted and then output them in alphabetical order.

到目前为止我有这个:

String wd1, wd2, wd3, wd4;
    Scanner scan1 = new Scanner(System.in);

    System.out.println ("Type Word One: ");
    wd1 = scan1.next();

    System.out.println ("Type Word Two: ");
    wd2 = scan1.next();

    System.out.println ("Type Word Three: ");
    wd3 = scan1.next();

    System.out.println ("Type Word Four: ");
    wd4 = scan1.next();

我知道我可以通过以下方式获得2个字符串的字母顺序:

I know that I can get the alphabetical order of 2 strings by using:

int compare = wd1.compareTo(wd2);


    if (compare < 0)
    {System.out.println(wd1 + " " + wd2);}
    else {
        if (compare > 0)
        {System.out.println(wd2+ " " + wd1);}

我需要帮助以正确的顺序获取所有4个字符串。 我应该使用if else语句而不是数组来执行此操作。

I need help getting all 4 of the strings in the proper order. I am supposed to be using if else statements and not arrays to do this.

任何帮助都会很棒!

谢谢

推荐答案

boolean swapped = false;
do {
  swapped = false;
  if (w2.compareTo(w1) < 0) {
    String tmp = w2;
    w2 = w1;
    w1 = tmp;
    swapped = true;
  }
  if (w3.compareTo(w2) < 0) {
    String tmp = w3;
    w3 = w2;
    w2 = tmp;
    swapped = true;
  }
  if (w4.compareTo(w3) < 0) {
    String tmp = w4;
    w4 = w3;
    w3 = tmp;
    swapped = true;
  }
} while (swapped)

System.out.println(w1);
System.out.println(w2);
System.out.println(w3);
System.out.println(w4);

这篇关于Java Alphabetizing Strings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆