java编程有个数组{10,5,21,66,51},要求倒序打印。要求,用for循环或者foreach完成 I
时间: 2024-02-27 15:54:17 浏览: 76
好的,对于您的问题,我可以给出以下两种实现方式:
1. 使用for循环实现数组倒序打印:
```java
int[] arr = {10, 5, 21, 66, 51};
for (int i = arr.length - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
```
2. 使用foreach循环实现数组倒序打印:
```java
int[] arr = {10, 5, 21, 66, 51};
List<Integer> list = Arrays.asList(arr);
Collections.reverse(list);
for (int num : list) {
System.out.print(num + " ");
}
```
两种方式都可以实现数组倒序打印,其中第二种方式使用了Java的集合类库。不过需要注意的是,第二种方式会将数组转化为List对象,因此可能会占用更多的内存。
相关问题
java实现有个数组{10,5,21,66,51},要求倒序打印。要求,用for循环或者foreach完成 I
好的,对于您的问题,我可以给出以下两种实现方式:
1. 使用for循环实现数组倒序打印:
```java
int[] arr = {10, 5, 21, 66, 51};
for (int i = arr.length - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
```
2. 使用foreach循环实现数组倒序打印:
```java
int[] arr = {10, 5, 21, 66, 51};
List<Integer> list = Arrays.asList(arr);
Collections.reverse(list);
for (int num : list) {
System.out.print(num + " ");
}
```
两种方式都可以实现数组倒序打印,其中第二种方式使用了Java的集合类库。不过需要注意的是,第二种方式会将数组转化为List对象,因此可能会占用更多的内存。
用户输入元素值 用整形数组存储 用sort排序 用reverse倒序 输出。用C#
在C#中,你可以按照以下步骤处理用户输入的整数元素,存储到数组中并进行排序和倒序:
1. **获取用户输入**:
```csharp
Console.WriteLine("请输入整数元素,输入‘q’结束:");
List<int> inputList = new List<int>();
while (true)
{
string userInput = Console.ReadLine();
if (userInput.ToLower() == "q") break;
int number;
if (int.TryParse(userInput, out number))
{
inputList.Add(number);
}
else
{
Console.WriteLine("无效输入,请输入整数。");
}
}
```
2. **将列表转换为数组**:
```csharp
int[] array = inputList.ToArray();
```
3. **对数组进行排序**(这里用Array.Sort方法,因为它默认是升序排列):
```csharp
Array.Sort(array);
```
4. **反转数组**(使用Array.Reverse方法):
```csharp
Array.Reverse(array);
```
5. **输出结果**:
```csharp
Console.WriteLine("排序后的数组(倒序):");
foreach (int num in array)
{
Console.Write(num + " ");
}
Console.WriteLine();
```
阅读全文
相关推荐














