Advanced Java Arrays Excercise

    0

    0

    Ravindu Thilakshana

    }

    The code prints the following output

    Enter Number : 1 Duplicate Number

    public static void main(String[] args) {
            
      Scanner scanner = new Scanner(System.in);
      int[] ar = new int[0];
      
      Outer : while (true){
        System.out.print("Enter Number : ");
        int x = scanner.nextInt();	
        
        
        // program exits if user enters '-1'
        if(x == -1){
        break;
        }
      
        // checking the duplicates.
        Inner : for (int j = 0; j < ar.length; j++){
        
        if(ar[j] == x){
          System.out.println("Duplicate Number");
          continue Outer;
        }
        }
        
        // Extending the array by creating new array.
        int[] cr = new int[ar.length + 1];
        
        // Copying values from old array to new array.
        for (int k = 0; k < ar.length; k++){
        cr[k] = ar[k];
        }
        
        // Assigning user entred value to the last index.
        cr[cr.length - 1] = x;
        
        // Changing reference of the new array to old array's reference.
        ar = cr;
        
      }
      
      System.out.println(Arrays.toString(ar));
      System.out.println("Array Length : "+ar.length);
      
      }
        
        
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.