ListWork.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import java.util.Scanner;
  2. public class ListWork
  3. {
  4. public static <T> boolean search(T[] arr, T target)
  5. {
  6. for (T x: arr)
  7. {
  8. if(x.equals(target))
  9. {
  10. return true;
  11. }
  12. }
  13. return false;
  14. }
  15. public static <T> void print (T[] arr)
  16. {
  17. for(T x: arr)
  18. {
  19. System.out.println(x);
  20. }
  21. }
  22. public static void main(String[] args)
  23. {
  24. Integer[] intArray = new Integer[10];
  25. System.out.println("Please input values (at least 10 integers) for this lab project!");
  26. Scanner scannerRead = new Scanner(System.in);
  27. scannerRead.useDelimiter("\\s+");
  28. int index = 0;
  29. while (index < 10)
  30. {
  31. while (!scannerRead.hasNext());
  32. try
  33. {
  34. intArray[index] = Integer.parseInt(scannerRead.next());
  35. index ++;
  36. }
  37. catch (NumberFormatException nfe)
  38. {
  39. }
  40. }
  41. //if (scannerRead.hasNextLine())
  42. //{
  43. scannerRead.nextLine();
  44. //}
  45. System.out.println("Would you like to search through this array? (y/n)");
  46. while(true) //()
  47. {
  48. String input = scannerRead.next();
  49. if (input.equalsIgnoreCase("N"))
  50. {
  51. break;
  52. }
  53. else if (input.equalsIgnoreCase("Y"))
  54. {
  55. System.out.println("What would you like to search for?");
  56. try
  57. {
  58. boolean res = search(intArray, Integer.parseInt(scannerRead.next()));
  59. System.out.println(res? "Found":"Not Found");
  60. }
  61. catch (NumberFormatException nfe)
  62. {
  63. System.out.println("Not a valid entry");
  64. }
  65. System.out.println("Would you like to search through this array again? (y/n)");
  66. scannerRead.nextLine();
  67. }
  68. else
  69. {
  70. System.out.println("Invalid input, please try \"y\" or \"n\".");
  71. }
  72. }
  73. scannerRead.close();
  74. print(intArray);
  75. }
  76. }