Get values from int, then save in array and calculate modulo - java

I need to write a program which should read a few numbers from an int, then save the values in array and to calculate the modulo of the numbers I read in.
I made this so far, but I have no idea how to store int in array, or how to calculate modulo of an array. Hope someone can help.
public class modulo {
public static void main (String[] args) {
int counter = 0;
int r = 0;
int modus;
int numbers;
int[] n;
Out.print("How many numbers you want to calculate: ");
r = In.readInt ();
Out.print("With which number you want to calculate the modulo: ");
modus = In.readInt ();
while (counter != r) {
counter++;
Out.print("Put the " + counter + ".number: ");
numbers = In.readInt ();
}

First of all, you need to new your array, otherwise you'd get NullPointerException. Since you already know your array size, this is what you will write after you've read r from the input:
int[] n = new n[r]
Then, you need a for loop to read from the input and save it to the array.
As for your next question, here is the answer.
How can I implement a modulus on a list of numbers?

Arrays are not dynamic, meaning, once given a size it will stay that size. For example "int[] arr = {1, 2, 3, 4, 5, 6}; or int[] arr = new int[5];"
For this particular example you may want to do the second declaration of array that I gave you as an example because this allows you to later declare the size of the array(after you get your input from how many numbers you want to calculate"
after this you ask with which number you want to calculate the array to. This can be done using a for loop and then doing something like:
for(int i = 0; i < arr.lenght; i++){
new_arr[i]= arr[i]%mod; //this stores each operation into a new array.
}
hope this helps!

I do this, still the same
public class modulo {
public static void main (String[] args) {
int counter = 0;
int zahlen = 0;
int modus;
int numbers;
int[] n = new int[zahlen];
int [] new_arr = new int [0];
Out.print("Wie viele Zahlen moechten Sie berechnen: ");
zahlen = In.readInt ();
Out.print("Mit welcher Zahl moechten Sie Modulo berechnen: ");
modus = In.readInt ();
while (counter != zahlen) {
counter++;
Out.print("Geben sie die " + counter + ".Zahl ein: ");
numbers = In.readInt ();
}
for(int i = 0; i < n.length; i++){
new_arr[i]= n[i]%modus;
Out.print(new_arr);
}
}
}

Related

Java: Print out each number in an array without printing its an repeats of that number?

Im trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}

Sorting even numbers from original array

I have to create a program that reads an arbitrary number of positive integers from the user and store them into an array. The number of input data is not more than 100. After the user finishes the program should remove all even integers and place them in another array leaving all odd integers in the original array with no holes. It should display the contents in the original array as the order of input, the contents of the even integer array with a count, and the contents of the original array after taking out all even integers with a count
No third array should be used
Im having trouble displaying the original array and original integer array after taking out the even integers. here is my code so far
import java.util.*;
public class Arrays
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter in any amount of positive numbers, Enter -1 when finished");
int i=0;
int nextElm=0;
int a,b;
int[] origArray = new int[100]; /* Two arrays at length 100*/
int[] evenArray = new int[100];
while((i<origArray.length && i<evenArray.length)&& nextElm!= -1)
{
System.out.println("Enter next number: ");
nextElm = scan.nextInt();
if (nextElm%2 != 0)//Sorts even numbers
{
origArray[i]= nextElm;
}
else
evenArray[i] = nextElm;
i++;
}
System.out.print("\n");
System.out.println("Even Array: ");
for (b=0; b<evenArray.length;b++)
{
if (evenArray[b]== -1)
{
evenArray[b]= 0;
}
if(evenArray[b]!= 0)
{
System.out.print(evenArray[b]+" ");
}
}
System.out.print("\n");
System.out.println("Original Array: ");
for(a=0; a<origArray.length && a<evenArray.length; a++)
{
if (origArray[a]== -1)
{
origArray[a]= 0;
}
if(origArray[a]!= 0)
{
System.out.print(origArray[a]+" " + evenArray[a]);
}
}
System.out.print("\n");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter in any amount of positive numbers, Enter -1 when finished");
int i = 0;
int nextElm = 0;
int a, b;
int[] origArray = new int[100]; /* Two arrays at length 100 */
int[] evenArray = new int[100];
while (nextElm != -1) {
System.out.println("Enter next number: ");
nextElm = scan.nextInt();
if (nextElm > 0) {
origArray[i] = nextElm;
i++;
}
}
int x = 0;
System.out.println();
// Displays original array and sorts even numbers to even array +
// original count
System.out.printf("\nTotal count of original array is : %d", i);
System.out.println();
for (int orgNumber : origArray) {
if (orgNumber != 0) {
System.out.print(orgNumber + " ");
}
if (orgNumber % 2 == 0) {
if (orgNumber != 0) {
evenArray[x] = orgNumber;
x++;
}
}
}
System.out.println();
// Displays sort even numbers to even array + even count
System.out.printf("\nTotal count of even array is : %d", x);
System.out.println();
for (int evenNumber : evenArray) {
if (evenNumber != 0) {
System.out.print(evenNumber + " ");
}
}
// Displays sort odd numbers from original array + odd count
System.out.printf("\nTotal count of orignal array without even is : %d", i - x);
System.out.println();
for (int oddNumber : origArray) {
if (oddNumber % 2 != 0) {
System.out.print(oddNumber + " ");
}
}
}
This should work perfectly if I understood your question well. Hope you find this helpful.
You want three separate loops. One for inputting the values (I would suggest the while construct as you have done) and one for sorting the values.
Your input loop should read in a new number each time and only quit when the user wants to. For example, if the user inputs a negative number, then your loop will quit. Like this:
System.out.println("Enter any number of numbers; enter a negative when finished.");
int nextElm = 0;
int count = 0;
while (nextElm >= 0) {
nextElm = scan.nextInt();
origArray[count] = nextElm;
count++;
}
// This is where you would put a print statement that prints the original array with a count.
Now after this, use the java.util.Arrays.copyOf() method to trim out the empty elements of the array, like so:
origArray = java.util.Arrays.copyOf(origArray, count+1);
Next, use a for loop to iterate through the array, and move even numbers to the other array. This is the tricky part, because removing items from an array requires iteration to move each value to it's previous index.
int j = 0;
for (int i=0; i<count; i++){
if (origArray[i] % 2 == 0){
evenArray[j] = origArray[i]; //add even number to evenArray
j++; //move to next index of evenArray
for (int k=i; k<(origArray.length-1); k++){
origArray[k] = origArray[k+1]; //store next value in current index
}
}
}
Then finally, use the java.util.Arrays.copyOf() method to trim out the empty elements of the array again, like so:
evenArray = java.util.Arrays.copyOf(evenArray, j+1);
Disclaimer: This was all coded from the hip so let me know if I missed something or did something incorrectly.

Store random integers in array

package selectionsortintro;
public class SelectionSortIntro {
public static void main(String[] args) {
int nums[] = { 22, 30, 15, 1, 7, 87, 65, 24, 22, 0 };
// print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
System.out.println("\n---------------------------------");
selectionSort(nums);
// print out sorted list
System.out.println("After sorting using the Selection Sort," + " the array is:");
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
}
}
public static void selectionSort(int data[]) {
int smallest;
for (int i = 0; i < data.length - 1; i++) {
smallest = i;
// see if there is a smaller number further in the array
for (int index = i + 1; index < data.length; index++) {
if (data[index] < data[smallest]) {
swap(data, smallest, index);
}
}
}
}
public static void swap(int array2[], int first, int second) {
int hold = array2[first];
array2[first] = array2[second];
array2[second] = hold;
}
}
I want to add a random amount of random integers into the array, so the selection sort algorithm will sort them out. The only problem is, I don't know how to store the array with random numbers and not be a fixed amount. If that's confusing, when you make the array it's like :
int[] randomNumbers = new int[20];
Where 20 is the amount of numbers generated. Well I want to have the user be the judge of how many numbers are randomly generated into the array. So I'm thinking maybe use ArrayList? But then, I get confused as to how I can use it to add the random numbers into itself. If anyone can help me that'd be awesome
EDIT: So I got input using scanner, but I really would prefer JOptionPane as the input dialog looks a lot nicer, but if scanner is the only way that's fine. So now that that's done, I just need to actually FILL the array with random integers, does anyone know how to do that?
Here's what I came up with, I get an error with my code, if anyone could help that'd be awesome.
Scanner input = new Scanner(System.in);
Scanner s = new Scanner(System.in);
System.out.println("enter number of elements");
int n = s.nextInt();
int nums[]=new int[n];
Random randomGenerator = new Random();
//print out unsorted list
for (int count = 0; count < nums.length; count++) {
System.out.print(nums[count] + " ");
nums[n] = randomGenerator.nextInt(1001);
}
Here's an example using a traditional array and a JOptionPane:
import javax.swing.*;
import java.util.Random;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
int[] array = new int[iTotalCount];
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array[i] = randomGenerator.nextInt(1001);
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.length; i++){
System.out.println(array[i]);
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
And here's an example of using an ArrayList with JOptionPane instead of a regular int[] array;
import javax.swing.*;
import java.util.Random;
import java.util.ArrayList;
public class Random_int_array {
public static void main(String[] args) {
JFrame frame = new JFrame("Total number of integers");
int iTotalCount = Integer.parseInt(JOptionPane.showInputDialog(frame, "What is the total number of integers?"));
// Can also be written as: ArrayList<Integer> array = new ArrayList<>();
// in newer versions of Java.
ArrayList<Integer> array = new ArrayList<Integer>();
Random randomGenerator = new Random();
for(int i=0; i < iTotalCount; i++){
array.add(randomGenerator.nextInt(1001));
}
// Now you can do whatever processing you would like to do
// For the sake of this answer, I will just print the numbers
for(int i=0; i < array.size(); i++){
System.out.println(array.get(i));
}
// We should explicitly call exit because we used a form/window
System.exit(0);
}
}
Note: ArrayLists cannot use primitive data types, so you must specify it as using an Integer rather than an int.
Adding an option to set the size of the array based off of user input is a bit more tricky
The easiest way to code it is to pass in command line arguments and read them in your args variable in your main method
Another way to read input is the Scanner class
Whichever way you choose, you may end up with a String variable you need to convert to an int with
String input = args[0]; //or use Scanner
int size = Integer.parseInt(input);
Three different methods of generating random integers, from easiest to implement to hardest
To generate a random int [0, max)
(int)(Math.random() * max)
or use
Random r = new Random();
r.nextInt(max);
A more complicated way to generate a more random number instead of Java's pseudo-random generators would be to query random.org for data. Do note that this may take a bit longer to set up and code, as well as relying on third party servers (no matter how reliable they may be)
You can use the random int to initialize the input array with a random length, then fill in the values with random numbers with a for loop

Java 2D array assigning randomly

I have an array a[5][5] and several values. I want to randomly assign values based on random percentages I create. For example one value is 6 and 25% of the elements in the array should have the value 6. With what I have so far: I created the random percentages and I'm able to randomly assign values for different elements in the array. My problem is: more than 25% of the elements have 6. My question is: How do I make sure that when assigning elements with 6, exactly 25% of the elements in the array a[5][5] have that value? I'm new to programming and tried several loops and ifs but nothing is working out for me. Please push me towards the right direction.
25% of 25 is about 6. It is not accurate. Here is a possible solution.
import java.util.Random;
import java.util.Scanner;
public class Matrix25 {
public static void main(String[] args) {
int[][] Matrix = new int[5][5];
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number you want to fill the array to 25%: ");
int number = scanner.nextInt();
int percentage=25;
generateMatrix(Matrix,number,percentage);
printMatrix(Matrix);
}
public static void generateMatrix(int Matrix[][],int num, int perc) {
int n;
int max=Matrix.length*Matrix[0].length;
int[] numbers = new int[max];
Random rnd = new Random();
int m = (int)(max * (perc/100.0));
int x=num>m?m-1:m;
for(int i=0;i<max;i++)
numbers[i]=(i<x)?num:i+1;
for(int i=0;i<Matrix.length;i++)
for(int j=0;j<Matrix[i].length;j++) {
n=rnd.nextInt(max);
Matrix[i][j]=numbers[n];
numbers[n]=numbers[max-1];
max--;
}
}
public static void printMatrix(int Matrix[][]) {
for(int i=0;i<Matrix.length;i++) {
for(int j=0;j<Matrix[i].length;j++)
System.out.printf("%3d\t",Matrix[i][j]);
System.out.print("\n");
}
}
}
I would do it like this
import java.util.Random;
import java.util.Scanner;
class Random2darray {
/**
* #param args
*/
public static void main(String[] args) {
// Create array; you specified 5x5 but you probably shouldn't hard code like this
int[][] numbers = new int[5][5];
//Create a scanner to get user input
Scanner scanner = new Scanner(System.in);
//I am not doing anything to make sure they give a decimal so the program won't work
//right if you are not giving a decimal
System.out.println("How much do you want to fill? Enter a decimal.");
//Get a double
double populatePercentage = scanner.nextDouble();
System.out.println("What number do you want to fill with?");
//Get an int
int fillNumber = scanner.nextInt();
//Don't hardcode like this
int fillTimes = numberOfTimesToFill(25, populatePercentage);
//This is declared outside of the loops because otherwise it will be
//reset each time the loop runs
int count = 0;
//Create a random number generator; default seed is current time which is good enough for this
Random rand = new Random();
//Fill the array with numbers
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
//Check if you have filled with given number enough times
if(count < fillTimes){
numbers[i][j] = fillNumber;
//Increment count by 1; this is how you are keeping track
count++;
}else{
//Otherwise pick a random number generator
//This will pick a random int between 0 - 50 inclusive
int randomNumber = rand.nextInt(51);
//This will make sure that you are not generating random numbers that are the same
//as the number you are filling with; This says if it is the same generate a new number
while(randomNumber == fillNumber){
randomNumber = rand.nextInt(51);
}
//Once we know its random fill the spot in the array
numbers[i][j] = randomNumber;
}
}
}
//Print the array out
printArray(numbers);
}
private static void printArray(int[][] numbers) {
//Just loop through and print every number
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
//Print with formatting: this says print a digit (%d) followed by a
//tab(\t) and then specifies what number I want to print
System.out.printf("%d\t", numbers[i][j]);
}
//Print a new line after each row
System.out.printf("\n");
}
}
private static int numberOfTimesToFill(int elements, double populatePercentage) {
System.out.println((int)(populatePercentage * elements));
//Cast to an int to truncate the decimal part of the number because you can't have
//a fraction of an element
return (int)(populatePercentage * elements);
}
}
I have commented the code to explain what everything does. However it does not protect against bad user input and it hardcodes the size of the array, you should always try to avoid hardcoding. In this example I did it (and marked where) to be more clear. Also as was mentioned in the comments above, for your situation where you want exactly 25% of 25 is not possible. This is because .25 * 25 = 6.25 and you can't have .25 of an element.

Java: how do I initialize an array size if it's unknown?

I'm asking the user to enter some numbers between 1 and 100 and assign them into an array. The array size is not initialized since it is dependent on the number of times the user enters a number.
How should I assign the array length?
If user enters 5 6 7 8 9 (5 numbers), then
int[] list;
becomes
int[] list = new int[5];
I'm trying to use a loop, but it won't stop.
int[] integers;
int j = 0;
do {
integers = new int[j + 1];
integers[j] = in.nextInt();
j++;
} while((integers[j-1] >= 1) ||(integers[j-1]) <= 100);
You should use a List for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List instead. Most would probably tackle this problem by using an ArrayList.
If you really can't use a List, then you'll probably have to use an array of some initial size (maybe 10?) and keep track of your array capacity versus how many elements you're adding, and copy the elements to a new, larger array if you run out of room (this is essentially what ArrayList does internally). Also note that, in the real world, you would never do it this way - you would use one of the standard classes that are made specifically for cases like this, such as ArrayList.
I think you need use List or classes based on that.
For instance,
ArrayList<Integer> integers = new ArrayList<Integer>();
int j;
do{
integers.add(int.nextInt());
j++;
}while( (integers.get(j-1) >= 1) || (integers.get(j-1) <= 100) );
You could read this article for getting more information about how to use that.
I agree that a data structure like a List is the best way to go:
List<Integer> values = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values.add(value);
} while (value >= 1) && (value <= 100);
Or you can just allocate an array of a max size and load values into it:
int maxValues = 100;
int [] values = new int[maxValues];
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values[numValues++] = value;
} while (value >= 1) && (value <= 100) && (numValues < maxValues);
If you want to stick to an array then this way you can make use. But its not good as compared to List and not recommended. However it will solve your problem.
import java.util.Scanner;
public class ArrayModify {
public static void main(String[] args) {
int[] list;
String st;
String[] stNew;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9
st = scan.nextLine();
stNew = st.split("\\s+");
list = new int[stNew.length]; // Sets array size to 5
for (int i = 0; i < stNew.length; i++){
list[i] = Integer.parseInt(stNew[i]);
System.out.println("You Enterred: " + list[i]);
}
}
}
String line=sc.nextLine();
int counter=1;
for(int i=0;i<line.length();i++) {
if(line.charAt(i)==' ') {
counter++;
}
}
long[] numbers=new long[counter];
counter=0;
for(int i=0;i<line.length();i++){
int j=i;
while(true) {
if(j>=line.length() || line.charAt(j)==' ') {
break;
}
j++;
}
numbers[counter]=Integer.parseInt(line.substring(i,j));
i=j;
counter++;
}
for(int i=0;i<counter;i++) {
System.out.println(numbers[i]);
}
I always use this code for situations like this. beside you can recognize two or three or more digit numbers.
int i,largest = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of numbers in the list");
i = scan.nextInt();
int arr[] = new int[i];
System.out.println("Enter the list of numbers:");
for(int j=0;j<i;j++){
arr[j] = scan.nextInt();
}
The above code works well. I have taken the input of the number of elements in the list and initialized the array accordingly.
**input of list of number for array from single line.
String input = sc.nextLine();
String arr[] = input.split(" ");
int new_arr[] = new int[arr.length];
for(int i=0; i<arr.length; i++)
{
new_arr[i] = Integer.parseInt(arr[i]);
}

Categories