如何解决Do-while 循环和数组
有人可以帮我做这个循环吗?我希望用户可以选择在程序结束时继续 Y/N 以重新运行或终止它。最好是 do-while 循环?
代码(Java):
public static void main(String[] args) {
int size = 10; //size of array
Scanner scan = new Scanner(System.in); //create scanner
while (true)
{
System.out.println("Enter values: ");
int[] myArray = new int[size]; //declare array
for(int i = 0; i < size; i++)
{
int userInput = scan.nextInt(); //receive user input
myArray[i] = userInput;
}
System.out.print("You entered these values: "); //print all values entered by user
for (int i=0; i<myArray.length; i++)
{
System.out.print(" " + myArray[i]);
}
System.out.println("");
IndexOfLargestBatista Object = new IndexOfLargestBatista(); //object of IndexOfLargest class
System.out.println("Index of Largest value: " + Object.findIndex(myArray)); //pass array as parameter and get index number in return
}
解决方法
您可以执行以下操作:
public static void main(String[] args) {
int size = 10; //size of array
String nextInput;
Scanner scan = new Scanner(System.in); //create scanner
do {
System.out.println("Enter values: ");
int[] myArray = new int[size]; //declare array
for (int i = 0; i < size; i++) {
int userInput = scan.nextInt(); //receive user input
myArray[i] = userInput;
}
System.out.print("You entered these values: "); //print all values entered by user
for (int i = 0; i < myArray.length; i++) {
System.out.print(" " + myArray[i]);
}
System.out.println("");
IndexOfLargestBatista largeIndex = new IndexOfLargestBatista(); //object of IndexOfLargest class
System.out.println("Index of Largest value: " + largeIndex.findIndex(myArray)); //pass array as parameter and get index number in return
System.out.println("Do you want to continue?: Y/N ");
nextInput = scan.nextLine();
} while (nextInput.equalsIgnoreCase("Y"));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。