Issue
I need to place in a selected by User input quantity, numbers that are only in between 1 and 60, values less than 1 and more than 60 should be invalid... And asked for a new input.
Thing is, I don't know how to repeat the question and replace in the vector's square where the wrong value was inserted, to the correct one.
Ex: It keeps asking for the values, ignoring in regards of it being wrong and showing it later... Such as vector[6], the values in the end shows like: [45, 34, 23, 22, 11, 99] or [45, 55, 34, 99, 99, 99]
My task: Develop an algorithm that records bets. The player can perform bets of 6 to 15 numbers, between 1 and 60. The algorithm must then request that the inform user:
- the quantity of numbers in your bet;
- receiving bets (between 1 and 60);
- show the bet placed in order and;
- show the amount to be charged for it (following a table I was given).
My attempt:
Scanner teclado = new Scanner(System.in);
System.out.println("How many bets from 6 to 15?");
int qntd = teclado.nextInt();
int c;
int i = 0;
if ((qntd < 6) || (qntd > 15)){
System.out.println("Only 6 to 15 values.");
} else {
int[] bets = new int [qntd];
for (c=0; c<=bets.length-1; c++ ){
i++;
System.out.println("Choose a number ");
bets[c] = teclado.nextInt();
if ((bets[c] < 1) || (bets[c]>60)) {
System.out.println("Only 1 to 60 values.");
}
}
Arrays.sort(bets);
System.out.print("Realized bets [");
for (int valor: bets){
System.out.print( " " + valor );
}
System.out.println(" ]");
System.out.println(" ]");
String pr = null;
int vlr = qntd;
switch (vlr){
case 6 :
pr = "4,50.";
break;
case 7 :
pr = "31,50.";
break;
case 8 :
pr = "126,00.";
break;
case 9 :
pr = "378,00.";
break;
case 10 :
pr = "945,00.";
break;
case 11 :
pr = "2.079,00.";
break;
case 12 :
pr = "4.158,00.";
break;
case 13:
pr = "7.722,00,";
break;
case 14 :
pr = "13.513,50.";
break;
case 15 :
pr = "22.522,50.";
}
System.out.println("Bets value is R$ " + pr);
}
Solution
You don't have to insert an invalid input into the array.
int c=0;
while(c<bets.length){
System.out.println("Choose a number ");
int input = teclado.nextInt();
if ((input < 1) || (input > 60)) {
System.out.println("Only 1 to 60 values.");
continue;
}
bets[c]=input;
c++;
}
For an invalid input the loop would continue without adding the input to the array. Also c
would be incremented only for valid input.
Answered By - Gautham M
Answer Checked By - Mildred Charles (JavaFixing Admin)