The world’s Largest Sharp Brain Virtual Experts Marketplace Just a click Away
Levels Tought:
Elementary,Middle School,High School,College,University,PHD
| Teaching Since: | Apr 2017 |
| Last Sign in: | 103 Weeks Ago, 2 Days Ago |
| Questions Answered: | 4870 |
| Tutorials Posted: | 4863 |
MBA IT, Mater in Science and Technology
Devry
Jul-1996 - Jul-2000
Professor
Devry University
Mar-2010 - Oct-2016
Hey, I have a quick question about my code, I can not get the expected results, is anyone willing to help me modify my code? thanks a lot!
A little more about that test program is that I am required to structure it as an infinite loop (so I'll have to exit the program with ctrl-c). For each loop iteration, print a prompt for the user, and then read all the data from the line into an ArrayList, and then print out the whole ArrayList. Running it might look something like this:
Enter a space separated list of numbers: 1 3 5 The numbers were: [1, 3, 5] Enter a space separated list of numbers: The numbers were: [] Enter a space separated list of numbers: 7 The numbers were: [7]
Â
Â
import java.util.ArrayList;import java.util.Arrays;import java.util.Scanner;public class ReadTester {public static void main(String args[]){ArrayList <Integer> arr = new ArrayList<>();System.out.print("Enter a space separated list of numbers:");Scanner s = new Scanner (System.in);do{if (s.hasNextInt())arr.add(s.nextInt());if(arr == null || arr.size() == 0)System.out.println("[]");else if(arr.size() == 1){System.out.print("[");System.out.print(arr.get(0));System.out.println("]");System.out.print("Enter a space separated list ofnumbers:");//s.next();}else{System.out.print("[");for(int i = 0; i< arr.size();i++){System.out.print(arr.get(i)+", ");System.out.println("]");System.out.print("Enter a space separated list ofnumbers:");//s.next();}}arr.clear();}while(true);}}