This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I'm using this code:
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class Matrix
{
public static void main(String[] args)
{
Scanner enter = new Scanner(System.in);
int[][] firstMatrix = new int[4][4];
int[][] secondMatrix = new int[4][4];
Random spin = new Random();
System.out.println("Please enter 16 numbers to populate the array: ");
for (int count = 0; count<firstMatrix.length;count++) // nested for for user input to populate 4x4 array
{
for (int count2 = 0; count2 < firstMatrix[count].length; count2++)
{
firstMatrix[count][count2] = enter.nextInt(); // populate array with user input
}
} // end array population
System.out.printf("The sum is: %d%n", sumMatrix(firstMatrix)); // call sumMatrix
System.out.println(firstMatrix[0][0]); // debug
for (int count3 = 0; count3<secondMatrix.length; count3++) // nested for to populate array with random numbers 1-100, row
{
for (int count4 = 0; count4<secondMatrix[count3].length; count4++) // column
{
secondMatrix[count3][count4] = 1 + spin.nextInt(100); // 100 inclusive, generate and populate array
}
}
System.out.println(secondMatrix[0][0]); // debug to show that it is properly printing the correct element
for (int i = 0; i<secondMatrix.length; i++)
{
for (int j = 0; j<secondMatrix[i].length; j++)
System.out.print(" " + secondMatrix[i][j]); // print the total array ( this process can be used to print the returned array )
}
System.out.println(); // debug
int arrayTotal = firstMatrix[0][0] + secondMatrix[0][0]; // debug
System.out.println("The element total is " + arrayTotal); // debug
System.out.println();
addMatrix(firstMatrix,secondMatrix); // call addMatrix
System.out.println("Programmed by Stephen Mills");
} // end main
public static int sumMatrix(int[][] array) // method to sum the elements of the array
{
int total = 0;
for (int number = 0; number<array.length; number++) // row
{
for (int number2 = 0; number2<array[number].length; number2++) // column
total += array[number][number2]; // sum of all elements
}
return total; // returns the sum
} // end sumMatrix
public static int[][] addMatrix(int[][] array1, int[][] array2) // improper method
{
int[][] thirdMatrix = new int[4][4];
for (int count4 = 0; count4<thirdMatrix.length; count4++)
{
for (int count5 = 0; count5<thirdMatrix[count4].length; count5++)
thirdMatrix[count4][count5] = array1[count4][count5]+array2[count4][count5];
}
System.out.println(Arrays.toString(thirdMatrix));
return thirdMatrix;
} // end addMatrix7
}
Most of the program works as intended but I'm getting this "[[I#3d4eac69, [I#42a57993, [I#75b84c92, [I#6bc7c054" output when trying to print my array. I've tried several methods, including simple println, toString, setting a variable equal to the method call, and I've tried putting the print statement in main first and then in the method second. Any ideas why this is happening?
If you want to print int elements of the 2d array thirdMatrix you can try this:
for(int[] simpleArray: thirdMatrix)
System.out.println(Arrays.toString(simpleArray));
The reason of your output: when you call
Arrays.toString(thirdMatrix)
you will call
String.valueOf(element)
foreach element of thirdMatrix. As elements of thirdMatrix are Array not primitive types, method
String.valueOf(Object obj)
will be called which return the hashcode of thirdMatrix elements(one-dimensional arrays).
Related
I wrote a small program.
Đ¡ondition: "Given an array of size n. Insert an element with a zero value after each negative element of the array." I solved this task using 2 ArrayList arrays. I'm wondering if it's possible to get a solution using only 1 array?
Code of the program:
public class Task_108 {
public void Task108(){
System.out.println("Input size of array: ");
Scanner scn = new Scanner(System.in);
int sizeArr = scn.nextInt();
ArrayList<Integer> ArrIntNum = new ArrayList<>(sizeArr); // Declare array
Random rnd = new Random();
int val;
// Filling array random elements from -20 to 20
for(int i = 0; i < sizeArr; i++){
val = -20 + rnd.nextInt(41);
ArrIntNum.add(i, val);
}
// Output array on the screen
System.out.println(ArrIntNum.toString());
ArrayList<Integer> ArrWithZeroAftNegVal = new ArrayList<>(); // Declare once more array
// Adding zero after every negative number in array ArrIntNum and write in array ArrWithZeroAftNegVal
for(int i = 0; i < sizeArr; i ++){
if(ArrIntNum.get(i) < 0) {
ArrWithZeroAftNegVal.add(ArrIntNum.get(i));
ArrWithZeroAftNegVal.add(0);
}
else
ArrWithZeroAftNegVal.add(ArrIntNum.get(i));
}
// Output edited array on the screen
System.out.println(ArrWithZeroAftNegVal.toString());
}
}
A ListIterator works quite naturally, allow addition of elements on the same array:
ListIterator<Integer> i = ArrIntNum.listIterator();
while (i.hasNext()) {
Integer value = i.next();
if (value < 0) i.add(0);
}
Like this:
import java.util.ArrayList;
public class Task_108 {
public void Task108(){
System.out.println("Input size of array: ");
Scanner scn = new Scanner(System.in);
int sizeArr = scn.nextInt();
ArrayList<Integer> arrIntNum = new ArrayList<Integer>(sizeArr); // Declare array
Random rnd = new Random();
// Filling array random elements from -20 to 20
for(int i = 0; i < arrIntNum.size(); i++)
arrIntNum.add(-20 + rnd.nextInt(41));
// Output array on the screen
System.out.println(arrIntNum);
// Adding zero after every negative number in array ArrIntNum
for(int i = 0; i < sizeArr; i++) {
if(arrIntNum.get(i) < 0)
arrIntNum.add(i + 1, 0);
}
// Output edited array on the screen
System.out.println(arrIntNum);
}
}
I also simplified your code for you.
public static void checkMultiple(int a[]){
//will use this count variable later
//int[] count = new int[10];
//first scan over the array
for (int i = 0; i < a.length; i++)
{
//seeded loop to check against 1st loop
for (int j = 0; j < i; j++)
{
if (a[i] == a[j])
{
System.out.print(a[i] + " ");
}
}
}
}
I'm having trouble counting repeated numbers in an integer array of 10 random numbers. I havent wrote the "count" function yet but the checkMultiple() will print out the numbers that are repeated. However, some of the time it prints correctly such as:
4 2 9 0 9 6 3 3 7 5
9 3
the first line being the whole array and the second the numbers that are repeated at least once in the array. But when there is more than two of a single integer, it counts every single one of that integer such as:
9 5 2 8 5 5 7 6 3 3
5 5 5 3
Any tips or advice would be much appreciated!
It looks like as you are looping through and then immediately outputting the results.
This prevents the program from comparing what's being currently parsed and what has already been been parsed and counted.
I would pass an empty array into the first FOR loop and instead of "System.out.print," store the number in the passed-in array. You can then compare the values that have already been parsed against the value currently being parsed to see if it has already been counted.
When the outside FOR loop exits, output the array that was originally passed in empty (and now has a record of every duplicate in the initial array)
You are counting the number of duplicate instances. Your second example has three pairs of duplicate 5's. That's why you see the 5 repeated three times. Only output unique duplicate results.
Just use a hash map, if the key does not exist add it to the map with the value 1, if it does increase the value, then print the hash map.
A single iteration of the array will solve the problem.
Map<Integer, Integer> counter = new HashMap<>();
for (int i = 0; i < a.length; i++) {
if (counter.containsKey(a[i])) {
counter.put(a[i], counter.get(a[i]) + 1);
} else {
counter.put(a[i], 1);
}
}
Iterator it = counter.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
for (int i = 0; i < pair.getValue(); ++i) {
System.out.print(pair.getKey() + " ");
}
// or you could just print the number and how many times it was found
System.out.println(pair.getKey() + " " + pair.getValue());
it.remove();
}
try this
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
public class BirthdayCake {
private static void printcake(int n,int[] arr){
//Map<Integer,Integer> ha = new HashMap<Integer,Integer>();
int temp = arr[0],max=0, count=0;
/*for(int i=1;i<n;i++){
max = arr[i];
if(max<=temp){
temp=max;
count++;
break;
}
else{
max = arr[i];
count++;
break;
}
}*/
Arrays.sort(arr);
for(int i:arr){
System.out.println(i);
}
System.out.println("max:" +max);
max = arr[arr.length-1];
for(int i=0;i<n;i++){
if(arr[i]==max){
count++;
}
}
System.out.println("count:" +count);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Entere thye array size:");
int n = sc.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
printcake(n,arr);
}
}
I am learning operations on 1 dim array.
It has three parts:
Set the 10 elements of integer array counts to zero.
Add one to each of the 15 elements of integer array bonus.
Display the five values of integer array best Scores in column format.
I have already figured out the 3. I need help in figuring out 1 and 2.
This is my code:
public class OneDimArrayOperations {
public static void main(String [] args){
// a) Set the 10 elements of integer array counts to zero.
int [] zeroArray = new int[10];
for (int i = 10; i == 0; i--) {
System.out.println("Count to zero from 10 elements" + zeroArray);
}
// b) Add one to each of the 15 elements of integer array bonus.
int [] arrayBonus = new int[15];
for (int i = 0; i <arrayBonus.length; i++) {
System.out.println("Bonus array values "+ arrayBonus[i]);
}
//c) Display the five values of integer array bestScores in column format.
int [] bestScores = {100,95,85,45,65};
System.out.printf("%n%s%12s %n", "Value", "BestScores");
for (int counter = 0; counter < bestScores.length ; counter++) {
System.out.printf( "%d%9d%n" , counter , bestScores[counter]);
}
}
}
part a:display:10,9,8,7,....1,0
for(int i=10;i>=0;i--)
part b:i havent understood your question
The line int[] zeroArray = new int[10]; will create an int array of size 10 and initialise all elements to zero. That's the default behaviour in Java.
for(int i = 0; i < arrayBonus.length; i++) { arrayBonus[i]++; } will solve your second problem.
I am trying to solve a problem in Java as part of my assignment. The problem is as below:
The user enters ten numbers one by one upon prompting by the screen. The screen then assigns all the distinct value to an array and a similar array to hold the frequency of how many times those numbers have appeared.
I have done the below work, but seems I am stuck somewhere in assigning the frequencies and distinct values to the arrays:
import java.util.*;
public class JavaApplication10
{
public static void main(String[] args)
{
int [] numbers = new int [10];
int [] count = new int[10];
int [] distinct = new int[10];
for (int k=0;k<10;k++)
{
count[k]=0;
distinct[k]=0;
}
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter number 0: ");
numbers[0]=input.nextInt();
count[0]=1;
distinct[0]=numbers[0];
int j=0;
for (int i = 1;i<10;i++)
{
System.out.print("Enter number "+i+": ");
numbers[i]=input.nextInt();
while(j<i)
{
if (distinct[j]==numbers[i])
count[j]=count[j]+1;
else
distinct[j+1]=numbers[i];
j++;
}
}
for (int k=0;k<10;k++)
{
System.out.println(distinct[k]+ " "+count[k]);
}
}
}
I know that it is not fair to ask someone to help me solve the problem. But any kind of hint will be helpful.
Thank you
are the numbers limited to 0-9? If so, I would simple do the assignment.
(please note you will assign the input to a variable called "input"):
numbers[0]=input;
count[input]++;
Also you can start your for loop in "0" to avoid the assignment prior to the for loop.
Just a hint.
Hope this helps!
the ideal data structure would be a HashMap
Steps:
1) initialize an array to store the numbers and for each input
2) check if a hashmap entry with key as the entered number already exists
3) if exists simply increase its count
4) else create new entry with key as the number and count as 1
so at the end your frequencies would be calculated
if you are forced to use 2 arrays
1) initialize two arrays
2) for each input loop the number array and check whether that number is already in the array
3) if so take the array index and increment the value of the frequency array with the same index
4) if not freq[index] = 1
A proper way of doing that would be:
public Map<Integer, Integer> getFrequencies(Iterable<Integer> numbers) {
Map<Integer, Integer> frequencies = new HashMap<Integer, Integer>();
for(Integer number : numbers) {
if (frequencies.get(number) == null) {
frequencies.put(number, 0);
}
frequencies.put(number, frequencies.get(number) + 1);
}
return frequencies;
}
It returns a map number -> frequency.
Arrays are not a way to go in Java, they should be avoided whenever possible. See Effective Java, Item 25: Prefer lists to arrays.
I removed the Scanner object to write the code faster, just replace it with your code above and it should work.
int[] numbers = { 1, 2, 2, 2, 3, 3, 3, 1, 1, 2 };
int[] count = new int[10];
int[] distinct = new int[10];
count[0] = 1;
distinct[0] = numbers[0];
int disPos = 1; //Current possition in the distinct array
boolean valueInarray = false;
for (int i = 1; i < 10; i++) {
valueInarray = false;
for (int d = 0; d < i; d++) {
if (numbers[i] == distinct[d]) {
count[d] = count[d] + 1;
valueInarray = true;
break;
}
}
if (!valueInarray) {
distinct[disPos] = numbers[i];
count[disPos] = 1;
disPos++;
}
}
If you ABSOLUTELY HAVE TO use arrays.. here is a way to do it…
import java.util.Scanner;
import java.util.Arrays;
public class JavaApplication10
{
public static void main(String[] args)
{
int [] numbers = new int [10];
int [] count = new int[10];
int [] distinct = new int[10];
int [] distinct1 = new int[1];
int distinctCount = 0;
boolean found = false;
Scanner input = new Scanner(System.in);
for (int i=0; i<10; i++) {
found = false;
System.out.print("Enter number " + i);
numbers[i]=input.nextInt(); //Add input to numbers array
for (int j=0; j<=distinctCount; j++)
{
if (distinct1[j] == numbers[i]){ // check to see if the number is already in the distinct array
count[j] = count[j] + 1; // Increase count by 1
found = true;
break;
}
}
if (!found) {
distinct[distinctCount] = numbers[i];
count[distinctCount] = 1;
distinctCount++;
distinct1 = Arrays.copyOf(distinct, distinctCount+1);
}
}
for (int j=0; j<distinctCount; j++)
System.out.println("The number " + distinct1[j] + " occurs " + count[j] + " times" );
}
}
I think this is what you need, correct me if I'm wrong...
import java.util.HashMap;
import java.util.Scanner;
public class JavaApplication10 {
public static void main(String[] args) {
// Initializing variables
int[] numbers = new int[10];
HashMap<Integer, Integer> table = new HashMap<Integer, Integer>();
Scanner input = new Scanner(System.in);
// Getting the 10 inputs
for(int x=0; x<10; x++) {
// Asking for input
System.out.println("Enter number "+x+":");
numbers[x]=input.nextInt();
// If the table contains the number, add 1
// Otherwise: set value to 1
if(table.containsKey(numbers[x]))
table.put(numbers[x], table.get(numbers[x])+1);
else
table.put(numbers[x],1);
}
// Closing the reader
input.close();
// Get the highest and smallest number
int highest=0;
int smallest=0;
for(int i:table.keySet()) {
if(i>highest)
highest=i;
if(i<smallest)
smallest=i;
}
// For every value between the smallest and the highest
for (int x=smallest; x<=highest; x++) {
// Check if the frequency > 0, else continue
if(table.get(x)==null)
continue;
// Output
System.out.println(x+" is "+table.get(x)+" times in \'frequence\'");
}
}
}
This also handles with negative numbers, unlike the other's codes. If you don't want to use HashMaps let me know so I can create something with arrays.
Let me know if it (doesn't) works!
Happy coding (and good luck with your assignment) ;) -Charlie
I have gotten 10 values from the user, and I am suppose to put that into an array and call it into a method, and then call another method which contains an array that reverses the integers of the first array without using global variables. For example, the user gives me values 1,2,3, etc.. and I store that in the first array, then in the second array I output 3,2,1.
I have part of the code that gets the integers from the user, but I don't know how to reverse the array without using global variables. The code doesn't run when it gets to the second method at values[i];
Here is what I have so far:
public static void main(String[] args) {
getInput();
reverseInput();
System.exit(0);
}
public static void getInput() {
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter ten numbers.");
for (int i = 0; i<values.length; i++) {//for loop to display the values entered
values[i] = keyboard.nextInt();
System.out.println("Value" + (i +1) + " is " + values[i]);
}
}
public static void reverseInput() {
System.out.println("Now we are going to reverse the numbers.");
Scanner keyboard = new Scanner(System.in);
int [] values;
values = new int[10];
for (int i = (values.length -1); i>= 0; i--) {//for loop to display integers in reversed order
values[i];
System.out.println(values[i]);
}
}
First, if you are not going to be using global variables, then you will need to pass the array from the get input method to the reverseInput method. Something like this:
int[] values = getInput();
reverseInput(values);
Then to output the array in your reverseInput method, it would have to look like this:
public static void reverseInput(int[] values) {
for(int i = (values.length - 1); i >= 0; i--){
System.out.println(values[i]);
}
}
You can use the ArrayUtils.reverse from Commons Lang:
ArrayUtils.reverse(values);
Ok, you understand how to display the elements in reference order. As you wrote:
for (int i = (values.length - 1); i >= 0; i--) {
System.out.println(values[i]);
}
So given that, how would you put the elements of values (say it has 5 elements) in another array (call it reversedValues) such that values[4] was put into reversedValues[0] and so on up to values[0] being put into reversedValues[4]?
use the "getInput" as basis to get the 10 numbers, then after the "for" loop, just do another for loop in reverse
public static void reverseInput()
{
Scanner keyboard = new Scanner(System.in);
int[] values;
values = new int[10];
//Ask the user to enter 10 integers
System.out.println("Please enter ten numbers, we are going to reverse the numbers");
for (int i = 0; i<values.length; i++) //for loop to display the values entered
{
values[i] = keyboard.nextInt();
};
int[] revValues;
revValues = new int[10];
for (int i = (values.length -1); i>= 0; i--) //for loop to display integers in reversed order
{
revValues[ revValues.length -1 -i ] = values[ i ];
System.out.println( revValues[ i ] );
}
}