Deleting element from an array in java - java

I created a program where users enter a command which are : adding a number to the array or delete an element from the array or print the array. The array size is 10.
Here is the tester class,
import java.util.Scanner;
public class Assignment7 {
public static void main (String [] args) {
Scanner scan = new Scanner (System.in);
final int MAX = 10;
Numbers nums = new Numbers(MAX);
char command;
int value;
System.out.println
("To add an element into the array, type a.");
System.out.println
("To delete an element from the array, type d.");
System.out.println
("To print the current contents of the array, type p.");
System.out.println
("To exit this program, type x.\n");
System.out.print
("Add (a), delete (d), print (p) or exit (x)?:");
command = scan.nextLine().charAt(0);
while (command != 'x') {
if (command == 'a' || command == 'd') {
System.out.print ("Enter a number: ");
value = scan.nextInt();
scan.nextLine();
if (command == 'a')nums.add(value);
else nums.delete(value);
}
else if (command == 'p') nums.print();
else System.out.println ("Not a value input");
System.out.print
("Add (a), delete (d), print (p) or exit (x)?: ");
command = scan.nextLine().charAt(0);
}
System.out.println ("Program Complete");
}
}
And here is my other class,
import java.util.*;
public class Numbers{
private int[] nums;
private int size;
public Numbers(int _size){
this.nums = new int[_size];
}
public void add(int addnum){
if (size == nums.length)
{
System.out.println("Array is full. The value " +addnum + " cannot be added.");
}
else
{
nums[size] = addnum;
size += 1;
}
}
public void delete(int deleteNum){
if(search(deleteNum) == -1)
{
System.out.println("The value " + deleteNum + " was not found and cannot be deleted.");
}
else {
for (int i = nums[deleteNum]; i < nums.length -1; i++){
nums[i]= nums[i+1];
}
}
}
public void print(){
String output ="";
for(int str: nums){
output = output + " " + str;
}
System.out.println(output);
}
private int search(int x){
int index = 0;
while(index < size){
if(nums[index] == x)
return index;
index++;
}
return -1;
}
}
Each time I run the program and input a number I want to delete it doesn't delete it. It deletes the number in the index.
For example, if the array inputs are 1,2,3,4,5,6,7,8,9,10 and I want to delete the number 1 it deletes the value that is in the index of 1 which would be the number 2 instead of the number 1.

I think that your "design" is not efficient. Because in your small program your array size is changing during runtime. Also your delete method is "weird".
Why it's not efficient?
You're using static array that has fixed size -> so if you want to "correctly" delete item from it, you need to re-initialise new array with new (size - 1)1 and this is such a spaghetti code operation.
And what is a suggestion?
What about to use dynamic array that can change its size dynamically when you'll remove or add new item to it? It also offers directly methods like add and remove for manipulating with it.
1You need to reinitialise static array (with new size - 1) again because if you'll "delete" for example 2. item from it it will be only assigned to zero so whole array will looks like: [ 1, 0, 3, 4, 5, 6, 7, 8, 9 ] and desired goal is [ 1, 3, 4, 5, 6, 7, 8, 9 ]

tl;dr: use an ArrayList, or seperate your array operations into its own class.
If you want to be able to add to and delete from a list, you most probably want to use an arraylist, which is implemented with an array "beneath the hood", but it supports a dynamic size.
The most valid reason for you to use an array, and not some sort of collection is for learning purposes, in which case you should make your own "arraylist" so all code related to add/deleting/etc is contained within its own class. Just know that your implementation is probably never gonna be as efficient and robust as ArrayList.
When deleting elements you do not need to "resize" the array, only keep a seperate size variable which tells you which indeces are "valid". When adding new elements you have to initialize a new array with a greater size, if you have exceeded the array's length, and copy over all the elements from the old one.

In your delete method, you should store the value you get from your search method. Right now you are calling nums[deleteNum] which is using the number inputted as an index. This is why you are having value 2 deletes. you should do something like this:
public static void delete(int deleteNum){
int index = search(deleteNum);
if(index == -1)
{
System.out.println("The value " + deleteNum + " was not found and cannot be deleted.");
}
else {
int size = nums.length;
for (int i = index; i < size; i++){
if(i < (size-1)
nums[i]= nums[i+1];
else
nums[i] = 0; //set to some base case or zero
}
}
}
You will not be able to "delete" the last value, but instead have to set it to some base case. If you want to truly delete i. you should use another data structure, ie ArrayList

Related

Take input of number of elements of an array, and input the array and display the odd and even elements of the array in their specified arrays

I have written the question I have to write the code for in the title but I am getting certain errors in my code.
The errors are:
line 7: numOfVal cannot be resolved or is not a field
line 23: numOfVal cannot be resolved to a variable
line 25: cannot invoke add(int) on the array type int[]
line 28: cannot invoke add(int) on the array type int[]
line 47: oddarray cannot be resolved to a variable
line 48: evenarray cannot be resolved to a variable
I would be very grateful if you could help me fix the errors in my code.
Thanks.
import java.util.Scanner;
public class CountEvenOddArray {
int[] mainarray;
void setInpLength(int numOfVal) {
this.numOfVal = numOfVal;
}
void setVal(int index,
int Val) {
this.mainarray[index] = Val;
}
void MainArrays() {
mainarray = new int[100];
}
void EvenOdds() {
int evenarray[] = new int[100];
int oddarray[] = new int[100];
for (int i = 0; i <numOfVal ; i++ ) {
if (mainarray[i]%2 == 0) {
evenarray = evenarray.add(mainarray[i]);
}
else {
oddarray = oddarray.add(mainarray[i]);
}
}
}
public static void main(String[] args) {
CountEvenOddArray abc = new CountEvenOddArray();
int numOfVal;
int mainarray[] = new int[100];
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements you want to store:");
numOfVal = sc.nextInt();
abc.setInpLength(numOfVal);
System.out.println("Enter the elements of the array: ");
for (int k = 0; k < numOfVal; k++ ) {
abc.setVal(k, sc.nextInt());
}
abc.EvenOdds();
sc.close();
System.out.println("The array with the odd elements is:" + oddarray);
System.out.println("The array with the even elements is:" + evenarray);
}
} ```
Here is a runnable example of how this task could be accomplished. You will notice that there are very few methods required. Having too many methods to carry out single simple tasks that can be accomplished with single lines of code just makes things harder to follow and bloats the application. Be sure to read the comments within the code:
import java.util.Scanner;
public class CountEvenOddArray {
// Class member variables:
private final String LS = System.lineSeparator();
private int[] mainArray;
// Startup main() method (Application entry point):
public static void main(String[] args) {
// App started this way to avoid the need for statics:
new CountEvenOddArray().startApp(args);
}
private void startApp(String[] args) {
/* Open a keyboard input stream. You only ever need one
of these in any console application. Do not close this
stream unless you know for sure that you will never need
it again during your application session otherwise, you
will need to restart the application to use it again.
The JVM will automatically close this resource when the
application ends. */
Scanner sc = new Scanner(System.in);
// Get the desired size of Main Array from User:
String numOfElems = "";
while(numOfElems.isEmpty()) {
System.out.println("Enter number of elements you want to store or");
System.out.print( "enter 'q' to quit: -> ");
numOfElems = sc.nextLine().trim();
// Is Quit desired?
if (numOfElems.equalsIgnoreCase("q")) {
// Yes....
System.out.println("Quiting - Bye Bye");
return; // Will force a return to main() and effectively end application.
}
// Entry Validation...
/* If the entry does not match a string representation of a
integer value. (See the isInteger() method below): */
if (!isInteger(numOfElems)) {
// Then inform the User and let him/her try again...
System.out.println("Invalid Entry! (" + numOfElems + ") Try again..." + LS);
numOfElems = ""; // Empty variable to ensure re-loop.
}
}
// If we made it the far, then the entry is valid!
// Convert the string input value to integer:
int numOfElements = Integer.parseInt(numOfElems);
// Initialize mainArray{}:
mainArray = new int[numOfElements];
// Have User enter the elements for the Array (with validation):
System.out.println();
System.out.println("Enter the elements of the array ('q' to quit):");
for (int i = 0; i < numOfElements; i++ ) {
// Prompt for each required mainArray[] Element:
String elem = "";
while (elem.isEmpty()) {
System.out.print("Enter Element #" + (i+1) + ": -> ");
elem = sc.nextLine().trim();
// Is Quit desired?
if (elem.equalsIgnoreCase("q")) {
// Yes....
System.out.println("Quiting - Bye Bye");
return; // Will force a return to main() and effectively end application.
}
// Entry Validation...
/* If the entry does not match a string representation of a
integer value. (See the isInteger() method below): */
if (!isInteger(elem)) {
// Then inform the User and let him/her try again...
System.out.println("Invalid Entry! (" + elem + ") Try again..." + LS);
elem = ""; // Empty variable to ensure re-loop.
}
}
// If we made it the far, then the entry is valid!
// Convert the string input value to integer element:
int element = Integer.parseInt(elem);
mainArray[i] = element;
}
/* mainArray[] is now initialized and filled. We will now create
the oddArray[] and evenArray[] from what is in the mainArray[]
but, because we have no idea what the User may have entered
for element values, there is no real viable way to create exact
fixed length int[] odd or even arrays unless we count them first.
This would require additional iterations basically meaning, we
are doing the job twice. We can get around this by placing our
odd/even results into a couple of List<Integer> Lists (which can
grow dynamically) then converting them to array later (if desired): */
java.util.List<Integer> odd = new java.util.ArrayList<>();
java.util.List<Integer> even = new java.util.ArrayList<>();
/* Determine Odd or Even value elements within the mainArray[]
and place those values into the appropriate odd or even Lists. */
evenOdds(odd, even);
// Convert Lists to int[] Arrays....
// Convert List<Integer> odd to oddArray[]:
int[] oddArray = odd.stream().mapToInt(d -> d).toArray();
// Convert List<Integer> even to evenArray[]:
int[] evenArray = even.stream().mapToInt(d -> d).toArray();
// Display the oddArray[] and the evenArray[]...
System.out.println();
System.out.println(oddArray.length + " odd elements are in the oddArray[]: -> "
+ java.util.Arrays.toString(oddArray));
System.out.println(evenArray.length + " even elements are in the evenArray[]: -> "
+ java.util.Arrays.toString(evenArray));
}
/* Method to determine Odd or Even value elements within the mainArray[]
and place those values into the appropriate odd or even Lists. The
Lists are added to by way of reference to them therefore no returnable
objects are required.
*/
private void evenOdds(java.util.List<Integer> odd, java.util.List<Integer> even ) {
for (int i = 0; i < mainArray.length ; i++ ) {
if (mainArray[i] % 2 == 0) {
even.add(mainArray[i]);
}
else {
odd.add(mainArray[i]);
}
}
}
public boolean isInteger(String value) {
boolean result = true; // Assume true:
// Is value null or empty?
if (value == null || value.trim().isEmpty()) {
result = false;
}
/* Is value a match to a string representation of
a integer value? */
else if (!value.matches("\\d+")) {
result = false;
}
// Does value actually fall within the relm of an `int` data type?
else {
long lng = Long.parseLong(value);
if (lng > Integer.MAX_VALUE || lng < Integer.MIN_VALUE) {
result = false;
}
}
return result;
}
}
If run and your entries are like this within the Console Window:
Enter number of elements you want to store or
enter 'q' to quit: -> 5
Enter the elements of the array ('q' to quit):
Enter Element #1: -> 1
Enter Element #2: -> 3
Enter Element #3: -> 2
Enter Element #4: -> 5
Enter Element #5: -> 4
You should see something like this:
3 odd elements are in the oddArray[]: -> [1, 3, 5]
2 even elements are in the evenArray[]: -> [2, 4]

How to make for loop stop when scanner is at the very end of the input

I'm currently trying to make a program that will allow the user to enter any amount of integers (I'm only asking them to enter 9 for now as a test) and have the rotateArray function rotate the array of integers. For example:
input: 1 2 3 4 5
output: 5 4 3 2 1
The reason as to why I included the arraylist is because I want to make the program dynamically allocate memory so that the user can enter as many single digit inputs as well. My problem is with a for loop I'm currently using. I"m looking for a way to properly make it so that the for loop stops when it hits the very end of the user's input. I tried using scan.nextInt().isEmpty() but that did not work as intended.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("This program takes two arrays, compares them, and "
+ "determines whether the original array has been rotated and put "
+ "into another array. \nWatch what happens when the original "
+ "array = [0,1,2,3,4,5,6,7,8,9] is compared to an array with contents: \n"
+ "[9,7,5,3,1,8,6,4,2,0]");
int[] original = {0,1,2,3,4,5,6,7,8,9};
int[] notRotated = {9,7,5,3,1,8,6,4,2,0};
int[] rotatedArray = {9,8,7,6,5,4,3,2,1,0};
boolean rotation;
rotation = isRotated(original, rotatedArray);
if(rotation == true)
{
System.out.println("The original array has been rotated!");
}else{
System.out.println("The original array has not been rotated");
}
System.out.println("\n Watch what happens when the original array is compared to an array"
+ " with contents \n [9,8,7,6,5,4,3,2,1,0]");
rotation = isRotated(original, rotatedArray);
if(rotation == true)
{
System.out.println("The original array has been rotated!");
}else{
System.out.println("The original array has not been rotated");
}
ArrayList<Integer> userArray = new ArrayList<Integer>(9);
System.out.println("This program can also rotate arrays that contain "
+ "single digit integers.\n Enter 9 single digit "
+ "integers separated by spaces");
//*****************************************************
userArray.add(scan.nextInt());
for(int i = 0; i<userArray.size(); i++)
{
//*****problem
if(???????? )
break;
else
userArray.add(scan.nextInt());
}
System.out.println("The array you entered is: " + userArray.toString() +"\n");
rotateArray(userArray);
System.out.println("When your array is rotated, it looks like this: \n" +
userArray.toString());
}
public static ArrayList<Integer> rotateArray(ArrayList<Integer> userArray)
{
int replace = 0;
int inc = 1;
int indexVariable = 0;
//if number of elements equals an even number
if(userArray.size() % 2 == 0)
{
for(int i = 0; i < (userArray.size()/2);i++)
{
replace = userArray.get(i);
userArray.set(userArray.get(i),userArray.size() - inc );
userArray.set(userArray.size() - inc, replace);
inc++;
}
}
//if number of elements equals an odd number
else
{
for (int i = 0; i <(userArray.size()/2) ; i++)
{
replace = userArray.get(i);
userArray.set(userArray.get(i),userArray.size() - inc );
userArray.set(userArray.size() - inc, replace);
inc++;
}
}
return userArray;
}
The thing about the scanner is that when its reading from the console, #hasNext will only ever return false if the scanner is closed, such as when you close it or the console is no longer usable for input. Otherwise, calling it will tell the scanner to wait for input and will let you know if it is valid input (e.g if you call #hasNextInt).
So the best way IMO to solve your issue is to read the scanner as a string, then split it and process it yourself as follows.
String input=scan.nextLine();
String[] numbers=input.split(" ");
for(String number:numbers)
{
if(number.isEmpty())
continue;//check for trailing so input like 3 4 5 is read
userArray.add(Integer.parseInt(number));//You would want to add a catch here for invalid input.
}
If input: 1 2 3 4 5 and userArray.size should match original.length then you can do like this:
int size = original.length;
for (int i = 0; i < size; i++) {
int num = scan.nextInt();
userArray.add(num);
Or you can hardcode variable size:
int size = 9;
or input it from console:
int size = scan.nextInt();

Program will only output else statement

I'm working on creating a linear search in Java using the StdIn library from Princeton, and I can't figure out why my if-else statement will only print out “-1”.
It seems to me that its skipping over the if block entirely and going straight onto the else. I'm entering in my list with command-line arguments and ending the list by pressing control-d (not sure what it is on windows, sorry). Any help at all would be greatly appreciated.
public class SearchAlgs {
public static void main(String[] args) {
if (args[0].equals("linear")) {
int n = Integer.parseInt(args[1]);
LinearSearch(n);
}
else {
System.out.println("Please enter linear");
}
}
public static void LinearSearch(int n) {
int x = -1;
//int u = -1;
int c, search, array[];
int value = StdIn.readInt(); //input values
array = new int[value]; //array list
while (x < 0) {
//System.out.println(n);
//System.out.println("linear");
//loop to populate array list
for(c = 0; c < value; c++)
array[c] = StdIn.readInt();
//loop to search for "n"
for (c = 0; c < value; c++) {
if(array[c] == n){
System.out.println(n + " is at index " + c);
x++;
return;
}
else{
continue;
}
}
System.out.println("-1");
x++;
}
}
}
Edit:
I updated the entire LinearSearch(n) method. It now finds the value from the list that I enter and gives me the value of -1 when the value is not there. The problem now is that the ArrayList only populates to whatever the first number I enter is when I need to populate to however many ints are entered in the command-line argument
Your method will return (after printing -1) as soon as the searched value is not in the array:
else{
System.out.println("-1");
return; // EXITING HERE
}
so if the value entered is not the the first value in the array, you will get -1 and the method is terminated.
What you probably want is to return (after printing) as soon as the value IS FOUND, or continue searching up to the last array entry. After this loop exists, that is, nothing was found, you want to print -1 (and return/terminate).
Something like
loop array {
if value is equal array entry {
print message
return
}
// else continue looping
}
print -1
Finally after lots of effort I have completed your code.
Run program as follows java SearchAlgs 4 5 6 7
enter size:5
67546
Output would be :
6 is at index 2
7 is at index 3
5 is at index 1
4 is at index 0
Code:
import java.util.Scanner;
class SearchAlgs {
public static void main(String[] args) {
int list[]=new int[(args.length)-1];
int conv=0;
if (args[0].equals("linear")){
for(int i=0;i<(args.length-1);i++)
{
conv=Integer.parseInt(args[i+1]);
list[i]=conv;
}
LinearSearch(list);
}
else{
System.out.println("Please enter linear");
}
}
public static void LinearSearch(int n[]){
int x = -1;
int c, search, array[];
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.print("Enter size:");
int size = reader.nextInt();
array = new int[size]; //array list
while (x < 0){
//loop to populate array list
for(c = 0; c < size; c++)
array[c] = reader.nextInt();
//loop to search for "n"
for (c = 0; c < n.length; c++){
for(int z=0; z<n.length;z++){
if(array[c] == n[z]){
System.out.println(n[z] + " is at index " + z);
x++;
}
else{
continue;
}
}
}
x++;
}
}
}

Sorting Arrays. The first element is length of array

Question :
Sorted?) Write the following method that returns true if the list is already sorted in increasing order. public static boolean isSorted(int[] list) Write a test program that prompts the user to enter a list and displays whether the list is sorted or not. Here is a sample run. Note that the first number in the input indicates the number of the elements in the list.
My try:
import java.util.Scanner;
public class Problem6_19 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number. for the length of the list: ");
int listLength = input.nextInt();
int[] number = new int[listLength];
for(int i = 0; i < number.length; i++) {
System.out.println("Enter a value: ");
number[i] = input.nextInt();
}
if (isSorted(number)) {
System.out.println("The list is sorted!");
} else {
System.out.println("The list is NOT sorted!");
}
}
public static boolean isSorted(int[] list) {
for(int i = 0; i < list.length; i++) {
if (list[i] > list[i + 1]) {
return false;
} else {
return true;
}
}
return false;
}
}
But there's one problem. In the question it prompts the user to enter list and the first element is length of that list. This means that we need to prompt the user only one time. So please explain how is this possible that first element becomes the size of an array??
The Scanner class uses whitespace, any white space, as the delimiter between tokens by default. This means that if the user pressed return between entering numbers then you need to handle that case and ask the user for another number, or the end user would just be on a new line and not know what to do. If the user doesn't press return between entering the numbers but separates them with a space, for example:
1 2 3 4 5
then the scanner would separate that in to 5 separate tokens that would be returned one at once when you call nextInt().
If you run your program and enter something like:
4 2 1 3 4
It should out put four questions asking you to enter inout (that you have already given to it) but then perform the function you want anyway and print "The list is NOT sorted!".
PS. the program doesn't quite work as I imagine you want it to because you as it only checks if the first two values are in ascending order and then returns. Instead you should check to see if the first two are correct, set a flag to keep track of them if they are and then carry on with the loop without exiting. Or only return in the case where the list isn't sorted and if you get to the end of checking the array and you haven't exited it must be sorted and therefore you should return true (as in the code example below). The return statements force your method isSorted to exit as soon as it hits that line, without going through the whole loop. You should also check for going off the end of the array before trying to access i+1. Something like
import java.util.Scanner;
public class ScannerClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number. for the length of the list: ");
int listLength = input.nextInt();
int[] number = new int[listLength];
for(int i = 0; i < number.length; i++) {
System.out.println("Enter a value: ");
number[i] = input.nextInt();
}
if (isSorted(number)) {
System.out.println("The list is sorted!");
} else {
System.out.println("The list is NOT sorted!");
}
}
public static boolean isSorted(int[] list) {
for(int i = 0; i < list.length - 1; i++) {
if (list[i] > list[i + 1]) {
return false
}
}
return true;
}
}

Using a single-dimensional array, ask the user for input and display only NON-duplicate values

in my java class we were learning about arrays and this question came up. I have tried to solve it and can't seem to fulfill the requirements. I can read in the user inputs and have it limited to only 5 elements (one of the other requirements), also the values have to be between 10 and 100 I have also done that. But I cannot seem to "not print" the duplicate values. The array accepts the duplicate values. They don't have to be taken out, just not printed. Here is my code so far:
import java.util.Arrays;
import java.util.Scanner;
public class ArrayTest {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int size = 5;
int InpNum[] = new int[size];
for (int i = 0; i < InpNum.length; i++){
while (InpNum[i] <= i){
System.out.println("Please type a number between 10 and 100: ");
InpNum[i] = in.nextInt();
while (InpNum[i] < 10 || InpNum[i] > 100){
System.out.println("Error: Please type an integer between 10 and 100: ");
InpNum[i] = in.nextInt();
}
Arrays.sort(InpNum);
System.out.println(Arrays.toString(InpNum));
}
while (Search(InpNum, i) == true){
System.out.println("ERROR: Please enter a number that is not a duplicate of the other numbers you have entered");
InpNum[i] = in.nextInt();
}
}
}
// I can't seem to implement the method below in a useful manner.
public static boolean Search(int InpNum[], int searchedNum) {
for(int i : InpNum) {
if (i == searchedNum) {
return true;
}
}
return false;
}
}
I would consider restructuring your application.
Instead of placing the number the user inputs into the array immediately, store it in a local variable. Then run all the checks you need to run, and add it to the array only if it passes all of them.
You should only have one while loop in the whole program (the outer one). All those others are greatly confusing the issue and making the problem much harder than it has to be.
So, in psudo-code:
int index = 0;
while (true)
{
int num = in.nextInt();
// if not between 10 and 100, continue
// if it would make the array larger than 5, continue
// (or perhaps break out of the loop, since we've filled the array)
// if it is already in the array, continue
// all the checks passed, so add it to the array!
InpNum[index++] = num;
}
As a side note, what you really need is a Set. This is a collection which is guaranteed to have no duplicates and allows you to answer the question "do I contain this value?" in an efficient manner using the method Set.contains( Object ).
So I would create a TreeSet or HashSet and put every number the user types into it. Your Search function would then simply be a one liner calling contains( searchedNum ) on your set.
A lazy way is to just create a second array that can hold the values as you go.
Loop through the input array and put the current element into the new array IF that array doesn't have that element already.
Then replace the old array with the weened out one.
Easiest way
So what I do is first ask the number. Then save the number in a variable before entering it inside the array. Then I check if that number is already in it wih search. If it is I ask for a new number. If it is not I check if it is between 10 and 100, if it is not I ask for a new. I fit is I enter It inside the array. I have to check where an empty place is because the sort mixes up the array everytime
import java.util.Arrays;
import java.util.Scanner;
public class ArrayTest
{
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int size = 5;
int InpNum[] = new int[size];
for (int i = 0; i < InpNum.length; i++){
System.out.println("Please type a number between 10 and 100: ");
int number = in.nextInt();
//while (InpNum[i] <= i){
while (Search(InpNum, number) == true){
System.out.println("ERROR: Please enter a number that is not a duplicate of the other numbers you have entered");
number = in.nextInt();
}
while (number < 10 || number > 100){
System.out.println("Error: Please type an integer between 10 and 100: ");
number = in.nextInt();
}
int counter = 0;
for (int j = 0; j < InpNum.length && counter == 0; j++){
if(InpNum[j] == 0){
InpNum[j] = number;
counter++;
}
}
Arrays.sort(InpNum);
System.out.println(Arrays.toString(InpNum));
//}
}
}
// I can't seem to implement the method below in a useful manner.
public static boolean Search(int InpNum[], int searchedNum) {
for (int i = 0; i < InpNum.length; i++){
if (InpNum[i] == searchedNum) {
return true;
}
}
return false;
}
}

Categories

Resources