我已经尝试过这样的其他问题,但似乎都没有。如果用户在控制台中对数字进行排序后输入Y,我希望它重复。 这是代码:
package compsorter;
import java.util.Scanner;
public class Ascending_Order
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("In Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
s.close();
}
}
谢谢!
答案 0 :(得分:0)
像这样,
do{
//code here
//take input from user 'Y' or 'N'
}while(condition);
答案 1 :(得分:0)
你可以放
do {
之后
Scanner s = new Scanner(System.in);
和
} while(s.readLine().equals("Y"))
之前
s.close();
答案 2 :(得分:0)
尝试这样做的原因。例如:link
答案 3 :(得分:0)
您可以使用while循环执行此操作。 以下是您应该拥有的主要方法程序。
public static void main(String[] args) {
String flag = "Y";
Scanner s = new Scanner(System.in);
while (true) {
if ("Y".equalsIgnoreCase(flag)) {
int n, temp;
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("In Ascending Order:");
for (int i = 0; i < n - 1; i++) {
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
System.out.println();
System.out.print("Do you want to continue Y/N?");
flag = s.next();
} else {
break;
}
}
s.close();
}