[英]Scanner asking for input twice and only storing second input to an array
我正在使用條件在 java 中制作一個 switch case 語句。 如果一個人在 2 到 12 個月之間將一個項目添加到系統中,它將被添加到一個數組中。 如果項目持續時間小於 2 或大於 12,系統應要求他們重新輸入有效數字。 出於某種原因,我的系統提示他們輸入數字兩次,並且只將第二個條目存儲到數組中: Image of terminal prompting twice & Image of second entry only being stored to the array 。
我想這是因為我有 'myMonths[index] = sc.nextInt();' 聲明了兩次,但我不知道如何在不出現兩次的情況下繞過它。 誰能弄清楚為什么會這樣,我該如何糾正? 任何幫助將不勝感激。 這是我的代碼:
//Menu loop
int myMonths[] = new int[5];
int index = 0;
while(choice !=6){
switch (choice){
case 1:
//int n = number of projects
int n = 1;
Scanner sc = new Scanner(System.in);
System.out.println("How many months was your project?");
for(int i=0; i<1; i++){
myMonths[index] = sc.nextInt();
//if months is lesser than 2/greater than 12
if((myMonths[index] < 2) || (myMonths[index] > 12)){
System.out.println("Enter a number between 2 and 12 months");}
//if months is between 2 and 12 add it to the array
for(int x=0; x<1; x++){
//read the elements of the array
myMonths[index++]=sc.nextInt();}
for(int i=0; i<1; i++){
myMonths[index] = sc.nextInt();// put this in a variable int a = sc.nextInt();
//if months is lesser than 2/greater than 12
if((myMonths[index] < 2) || (myMonths[index] > 12)){
System.out.println("Enter a number between 2 and 12 months");}//here your are just checking if provided value is between 2 or 12 but there is no logical branching i.e. an else
//if months is between 2 and 12 add it to the array
for(int x=0; x<1; x++){
//read the elements of the array
myMonths[index++]=sc.nextInt();}//since there is no else this block will always execute
你可以在你的代碼中嘗試這樣的事情
for(int i=0; i<1; i++){
int ip = sc.nextInt();
//if months is lesser than 2/greater than 12
if((ip < 2) || ip > 12){
System.out.println("Enter a number between 2 and 12 months");
//here ask for ip again
ip = sc.nextInt();//if you wanna continue doing this until you get a valid ip use an infinite while loop with a flag for break --- see below
}else{
//code for saving ip to array whatever logic you might need
}
一個關於如何使用 while 循環提示 ip 直到它有效的例子
int ip;
boolean valid = false;
while(!valid){
ip = sc.nextInt();
if(condition){
//if codition is satisfied
valid = true;
}
//else sysout("invalid ip"); loop will continue until you get a valid ip
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.