用jav写一个冒泡排序
时间: 2023-12-15 17:49:42 浏览: 35
好的,以下是用 Java 写的冒泡排序代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 1, 2};
int temp;
// 开始冒泡排序
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// 交换相邻两个元素
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// 输出排序后的数组
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
希望能够帮助到您。
相关问题
用jav写一个马里奥吃金币
好的,下面是用Java实现马里奥吃金币的代码:
```
import java.util.Scanner;
public class Mario {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int coins = 0;
System.out.println("欢迎来到马里奥吃金币游戏!");
while (true) {
System.out.println("请按下空格键来吃金币:");
String input = scanner.nextLine();
if (input.equals(" ")) {
coins++;
System.out.println("恭喜你吃到了第 " + coins + " 个金币!");
} else {
System.out.println("请按下空格键来吃金币!");
}
}
}
}
```
这个程序会在控制台上输出欢迎信息,并且通过不断读取用户输入的方式来模拟马里奥吃金币的过程。每当用户按下空格键时,程序会增加一个金币计数器,然后在控制台上显示恭喜信息。如果用户输入的不是空格键,则程序会提示用户再次按下空格键。
JAV写一个方法给数组求和
可以使用以下代码来实现:
```java
public static int sum(int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
```
该方法接收一个整数数组作为参数,返回数组元素的总和。使用循环遍历数组中的每个元素,并将其加到变量 `sum` 中。最后返回 `sum` 即可。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)