W
wolf2009
Guest
SO i have this program written that i need to modify so that it partially fills the array with m +ve no.s, where the value of m is no bigger than the size of the array, n. the user inputs m positive whole numbers at the keyboard and ends the input with a -ve number. the -ve no. is used as a delimiter to indicate the end of the input and it is not stored in the array.
here's the program
here's the program
Code:
import java.util.*;
public class Test
{
public static void main(String [] args)
{
String again;
do
{
Scanner keyIn = new Scanner(System.in);
//ask the user for array size
System.out.print("How big is the array : ");
int [] test = new int [keyIn.nextInt()];
//ask the user to enter the numbers
System.out.print("Enter " + test.length + " Whole numbers : ");
//store the array
for(int i=0; i<test.length; i++)
{
test [i] = keyIn.nextInt();
}
//display the array
System.out.println("The array contains: ");
print(test);
//display the samlest number
System.out.println("\nSmallest = " + smallest(test));
//display the elements less than smallest + 20
System.out.println("\nNumber of array elements less than " + (smallest(test) + 20) + " : " + lessThan(test));
//add 10 to each element and display
System.out.println("\nThe contents of array after adding 10 to each element: ");
add(test);
//subtract 10 from each element > smallest + 30
System.out.println("\nThe contents of array after subtracting 10 from each element > smallest+30: ");
sub(test);
//ask the user if he wants to do it again
System.out.print("Do it again? Y or y (for yes), N or n(for no): ");
again = keyIn.next();
}while(again.equalsIgnoreCase("Y"));
}
//method to display the array
public static void print(int [] test)
{
for (int i= 0; i<test.length; i++)
if((i+1)%10 != 0)
System.out.print(test[i] + "\t");
else
System.out.println(test[i]);
}
//calculates the smallest element
public static int smallest(int [] test)
{
int small = test[0];
for(int i=1; i<test.length; i++)
{
if(small > test[i])
small = test[i];
}
return small;
}
//calculates the number of elements < smallest + 20
public static int lessThan(int [] test)
{
int less = smallest(test) + 20, count = 0;
for(int i=1; i<test.length; i++)
{
if(test[i] < less)
count = count + 1;
}
return count;
}
//adds 10 to each element
public static void add(int [] test)
{
for(int i=0; i<test.length; i++)
{
test [i] += 10;
if((i+1)%10 != 0)
System.out.print(test[i] + "\t");
else
System.out.println(test[i]);
}
}
//subtracts 10 from each element > smallest + 30
public static void sub(int [] test)
{
int small = test[0];
for(int i=1; i<test.length; i++)
{
if(small > test[i])
small = test[i];
}
for(int i=0; i<test.length; i++)
{
if (test[i] > (small + 30))
{
test[i] = test[i] - 10;
}
}
print(test);
}
}