【发布时间】:2016-10-25 21:45:31
【问题描述】:
有 2 个数组,一个是 int,一个是 Strings (words) ;对它们进行排序,然后以奇数位置应为单词和偶数的方式打印。
这是我的代码:
import java.util.*;
public class JavaApplication4 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int num[]=new int[10];
String str[]=new String[10];
String str1[]=new String[20];
for(int i=0; i<5; i++)//for taking strings
{
str[i]=in.next();
}
for(int i=0; i<5; i++)//for taking nums
{
num[i]=in.nextInt();
}
for(int i=0; i<5; i++)
{
System.out.println("The String are "+str[i]);
}
for(int i=0; i<5; i++)
{
System.out.println("The num are "+num[i]);
}
for (int i = 0; i < 5; i++) //for sorting nums
{
for (int j = i + 1; j < 5; j++)
{
if (num[i]>(num[j]))
{
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
for (int i = 0; i < 5; i++)// for sorting strs
{
for (int j = i + 1; j < 5; j++)
{
if (str[i].compareTo(str[j])>0)
{
String temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
System.out.println("The sorted strings are:");
for(int i=0; i<10; i++)//for merging both
{
if((i+1)%2==0)
{
int k=0;
str1[i]=String.valueOf(num[k]);
System.out.println("The String are "+str1[i]);
k++;
}
else
{
int j=0;
str1[i]=str[j];
System.out.println("The String are "+str1[i]);
j++;
}
}
/* for(int i=0; i<10; i++)
{
System.out.println("The String are "+str1[i]);
}
*/
}
}
我得到的输出:
排序后的字符串是:
字符串是 ab
字符串是 1
字符串是 ab
字符串是 1
字符串是 ab
字符串是 1
字符串是 ab
字符串是 1
字符串是 ab
字符串是 1
它只取两个数组的第一个元素。
【问题讨论】:
-
你为什么期待别的东西?在访问数组元素之前,您将变量
k和j设置为0... 那么除了第一个元素之外,他们还应该检索什么? -
您应该尝试为变量使用有意义的名称。很难说哪个索引/数组指的是什么。