So my issue is that I would like to add elements into an ArrayList using the Scanner kb. I also want to make sure that the input (number) is between 0 and 100 inclusive. The code I have does not run as I want. How can I resolve this ? Thanks.
public static void addNum(final ArrayList<Double> myAList, final Scanner kb)
{
//Prompt user for a number 0-100
if(!(kb == null || myAList == null))
{
System.out.println("Please enter a number between (0 - 100): ");
double number = kb.nextDouble();
kb.nextLine();
while(number < 0 || number > 100)
{
System.out.println("That was not a qualified number, try again");
number = kb.nextDouble();
kb.nextLine();
}
for(int x = 0; x < myAList.size() - 1; x++);
{
myAList.add(number);
}
}
myAList.trimToSize();
}
Change your statement
for(int x = 0; x < myAList.size() - 1; x++); // the semicolon terminates loop without any action block // myAList.size() would keep on increaing with every `add()` inside the loop.
to
int listSize = myAList.size(); for(int x = 0; x < listSize - 1; x++) { myAList.add(number); }
The statements kb.nextLine();
are not required in the code. nextDouble()
takes care of accepting a return and moving to the next line on console.
Contradictory to (1), If you just want to add the number inputted to the existing list, you don't require the for loop anyway. Simply after the while
loop, do a
myAList.add(number);
Be careful, if myAList
would be null
, your statement myAList.trimToSize();
can throw NPE. Since it is out of the if
block where you do a null-check. Move it inside the if
would be what I would suggest.
This should just work fine -
public static void addNum(final ArrayList<Double> myAList, final Scanner kb) {
if (!(kb == null || myAList == null)) {
System.out.println("Please enter a number between (0 - 100): ");
double number = kb.nextDouble();
while (number < 0d || number > 100d) {
System.out.println("That was not a qualified number, try again");
number = kb.nextDouble();
}
myAList.add(number);
myAList.trimToSize();
System.out.println(Arrays.asList(myAList.toArray()));
}
}
if you are using final
keyword then make sure you are not choosing dead end. There is minor bug in your code if(!(kb == null || myAList == null))
can fail if any one of them is null
so make sure you check properly and below is working example
public void addNum(final List<Double> myAList, final Scanner kb) {
double number;
if (!(myAList == null && kb == null)) {
System.out.println("Please enter a number between (0 - 100): ");
number = kb.nextDouble();
while (number < 0d || number > 100d) {
System.out.println("please enter double and number must be betwen 0 to 100");
number = kb.nextDouble();
}
myAList.add(number);
System.out.println(myAList);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.