如何在if-else语句中使用字符串输入作为条件



你好,我目前正在创建一个程序,它将询问用户10个整数,然后询问他们将使用什么排序方法,是升序还是降序。这是我目前取得的进展:

import java.util.*;
import BubbleSort;
import SelectionSort;
public class SortingAlgorithm{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
try{
String reply ="";
String choice = "";

System.out.println("Please Enter 10 numbers: ");  
int[] array = new int[10]; 
//reading array elements from the user   
for(int i=0; i<10; i++) {  
array[i]=sc.nextInt();  
}  
System.out.println("What sorting method you need? U - Bubble Sort, S - Selection Sort");
reply = sc.nextLine();
System.out.println("Would you like it to be in A - Ascending or D - Descending order?");
choice = sc.nextLine();
if(reply.equals("U") || choice.equals("u")){
System.out.println("Your number will be sorted using Bubble Sort");

if(choice.equals("A") || choice.equals("a")){
BubbleSort.bubbleSortAscending(array);
}
if(choice.equals("D") || choice.equals("d")){
BubbleSort.bubbleSortDescending(array);
}
System.out.println(Arrays.toString(array));
}
if(reply.equals("S") || choice.equals("s")){
System.out.println("Your number will be sorted using Selection Sort");
if(choice.equals("A") || choice.equals("a")){
SelectionSort.selectionSortAscending(array);
}
if(choice.equals("D") || choice.equals("d")){
SelectionSort.selectionSortDescending(array);
}
System.out.println(Arrays.toString(array));
}
}
catch(InputMismatchException ime){
System.out.println("Can only accept integers.");
}
catch(ArrayIndexOutOfBoundsException ime){
System.out.println("Array is out of Bounds.");
}   
}

}

问题是,每次我运行程序时,这都是的结果

Please Enter 10 numbers: 
1
5
2
8765
1
698541
2
8
5
2
What sorting method you need? U - Bubble Sort, S - Selection Sort
Would you like it to be in A - Ascending or D - Descending order?
A

在询问10个整数后,它跳过询问将使用哪种排序方法,直接询问他们想要按升序还是降序排序,在输入值后,程序结束,没有显示预期结果,即排列的数组。有什么可以修复或改进的吗?

所以你犯了一个错误:

What sorting method you need? U - Bubble Sort, S - Selection Sort

您没有在此处提供任何输入。你把它留空了。

最新更新