I'm trying to figure out how to read in a multidimensional array from standard input given the user provides the row and col size followed by integers of the array
e.g. Input:
2 3 <= row, col of array
8 3 10 < array integers
7 9 6
My code is currently:
int colA = scan.nextInt();
int rowA = scan.nextInt();
int[][] array = new int[rowA][colA];
for (int i = 0; i <rowA;i++){
for (int j=0; j<colA;j++){
array1[i][j] += scan.nextInt();
}
}
And the output of my array is: [[8,3,10,7,9,6]] but what I'd like to do is output [[8,3,10],[7,9,6]]
Here first the row and col value got from users is reversed that is the only mistake i could see
import java.util.Arrays;
import java.util.Scanner;
public class TwoDimensionalArray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int rowA = scan.nextInt();
int colA = scan.nextInt();
int[][] array = new int[rowA][colA];
for (int i = 0; i < rowA; i++) {
for (int j = 0; j < colA; j++) {
array[i][j] += scan.nextInt();
}
}
for (int[] innerArray : array) {
System.out.println(Arrays.toString(innerArray));
}
}
}
This is a working one
There are some errors in your code.
You inverted the order of the dimensions asked to the users.
Use this:
int rowA = scan.nextInt();
int colA = scan.nextInt();
Instead of this:
int colA = scan.nextInt();
int rowA = scan.nextInt();
You wrote array1 instead of array in array1[i][j] += scan.nextInt();
Note that you can use array[i][j] = scan.nextInt(); instead of array[i][j] += scan.nextInt()
I'm trying to read a file with a line of numbers and put it into a 2d array
Here is the prompt:
Create a file of integers. Write a program that first tests whether the number of integers is a square of some integer n. If so, create a 2D array of size n×n. Then, read the numbers into the array. Finally, display the array and test whether the array forms a magic square, that is, whether the sums of rows, columns, and diagonals are all equal. For example, if the file includes numbers
6 7 2 1 5 9 8 3 4
so that n = 3, then the array
6 7 2
1 5 9
8 3 4
is displayed along with the message that the array is a magic square.
I have up to reading the file and putting it into an array but am stuck and I don't know how to put the numbers into the array I have made.
Here is my Code so far:
import java.io.*;
import java.lang.*;
//import java.util.Arrays;
class Program8 {
Scanner kb = new Scanner(System.in);
void print2Darray(int[][] a){
for(int row = 0; row < a.length; row++) {
for(int col = 0; col < a[row].length ; col++)
System.out.print(a[row][col] + " ");
System.out.println();
}
}
void magicSquare(){
Scanner fIn;
System.out.print("Enter the name of a file: ");
String s = kb.nextLine();
try {
fIn = new Scanner(new FileInputStream(s));
double x = 0;
// double y = 0;
// double z = 0;
int cnt = 0;
while(fIn.hasNextDouble()){
x = fIn.nextDouble();
cnt++;
System.out.println(cnt);
}
int sqrt = (int)Math.sqrt(cnt);
System.out.println(sqrt);
int [][] magicSqaure = new int [sqrt][sqrt];
print2Darray(magicSqaure);
//BufferedReader br = new BufferedReader(new FileInputStream(s));
while(fIn.hasNextDouble()){
for (int i = 0; i < magicSqaure.length; i++){
//input from file
for(int j = 0; i < magicSqaure.length; j++)
//input from file
}
//for(int j = 0; j < i; j++)
// z = fIn.nextDouble();
//System.out.println(Arrays.toString(magicSqaure));
// print2Darray(magicSqaure);
}
}catch(IOException e){
}
}
public static void main(String[] args) {
Program8 lab = new Program8();
lab.magicSquare();
}
}
As a beginner I am doing online problems to understand arrays, this is not homework but practice. Any advice helps!
The code should take user input.
Problem:
Print two space-separated integers denoting the respective comparison scores earned by A and B.
Sample Input
5 6 7
3 6 10
Sample Output
1 1
Explanation
In this example:
A = (a0, a1, a2) where the values are (5,6,7)
B = (b0,b1,b2) where the values are (3,6,10)
Compare each individual score:
a0 > b0 ==> so A receives 1 point.
a0 = b0 ==> nobody receives a point.
b0 > a0 ==> so B receives 1 point.
A's comparison score is 1 and B's comparison score is 1. Thus, we print 1 1 on a single line.
Approach 1:
First I though of implementing this as a 2d array but I only got this far as I am not sure where to implement the comparison:
public class CompareElem2DArray{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int array2d [][]= new int[3][3];
System.out.println("Please enter 3 marks for A and 3 marks for B: ");
for(int a = 0; a<3; a++) //row
{
for(int b=0; b<3; b++)//column
{
int array2d[a][b] = in.nextInt();
}
}
for (int column = 0; column<3; column++)
{
for(int row=0; row<3; row++)
{
System.out.println( array2d[column][row]+" ");
}
}
System.out.println();
}
}
Approach 2:
This is my second attempt without using 2D arrays.
public class Comparison {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a0 = in.nextInt();
int a1 = in.nextInt();
int a2 = in.nextInt();
int b0 = in.nextInt();
int b1 = in.nextInt();
int b2 = in.nextInt();
int a[] = new int[3];
int b[] = new int[3];
int firstAns = 0;
int secondAns = 0;
for(int i = 0; i<3; i++)
{
int a[i] = in.nextInt();
System.out.println(a[i]);
}
for(int j = 0; j<3; j++)
{
int b[j] = in.nextInt();
System.out.println(b[j]);
}
for(int z = 0; z<3; z++)
{
if(a[z]>b[z])
{
firstAns++;
}
else if(a[z]<b[z])
{
secondAns++;
}
else
{
return;
}
}
System.out.println(firstAns);
System.out.println(secondAns);
}
}
You can try doing
int[] ar = {5,6,7,3,6,10};
int halflen= (ar.length)/2;
int[] result = new int[halflen];
for(int i=0,j=halflen;i<halflen;i++,j++)
{
result[i]=ar[i]-ar[j];
}
Now you have a array with 3 results , if 0 is draw whatever how is > 0 made the point you can eliminate the array inside loop if you want and add your if ther too like :
If (ar [i] > ar [j]) A++;
If (ar [i]<ar [j]) B++;
In approach 1., I think that what you need is [3][2] or [2][3] array (you have 2 sets of data, in one set there are 3 numbers).
Then the comparison goes in second loop (in this case, array2d is [3][2]):
for(int i=0; i<3; i++)
{
//comparison goes here
}
You need to compare values of array2d[i][0] with array2d[i][1].
When input is: 5 6 7 3 6 10
Your 2d array is something like:
5 6 7
3 6 10
So the second loop is comparing 5 with 3, 6 with 6 and 7 with 10.
I'm having some trouble with this Java input:
public class Testinput {
public static void main(String[] args) {
int N = StdIn.readInt();
String[] name = new String[N];
int[] year = new int[N];
for (int i = 0; i < name.length; i++) {
name[i] = StdIn.readString();
for (int j = 0; j < name.length; j++) {
year[j] = StdIn.readInt();
}
}
for (int i = 0; i < name.length; i++ ) {
System.out.println(name[i]+" " +year[i]);
}
}
}
For example: it needs to read name and age in an alternating order:
2
bob
1963
kelly
1981
and print:
bob 1963
kelly 1961
But instead it asks for an input of length 6 (instead of 2*N = 4) and prints out:
input1 input5
input4 input6
Can you guys help me with this?
Are you coming from C background where you are used to Char-array? In Java, it is much straight forward. You can input by String.
Scanner scn = new Scanner(System.in); //Create a scanner object
int n = scn.nextInt(); //Enter number of people you want to prompt and record
String[] name = new String[n]; //Create array of size based on n
int[] year = new int[n]; //Create array of size based on n
for(int x=0; x<n; x++){
name[x] = scn.nextLine(); //for string inputs
year[x] = scn.nextInt(); //for whole number
}
This will provide you an alternative for inputs.
Most universities and schools I encounter teaches their students to use Scanner for receiving user inputs. So you may want to use it too if you are allowed to.
Without using collections,i have written a java program to remove duplicate integer element from an integer array,however the program is removing only one integer element and other integer element is left over.
Could you let me know how should i remove duplicate integer elements in the below core java program.In the below core java program i have to remove the duplicate integer element 5
Help provided will be appreciated.
Below is the Java code.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DeleteElementFromArray {
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[10];
static int i, k, f, j = 0;
static int l = a.length;
void DeletElementInt() {
for (i = 0; i < l; i++) {
if (i != k) {
if (i < k) {
b[i] = a[i];
} else{
b[i - 1] = a[i];
}
}
}
}
public static void main(String[] args) {
DeleteElementFromArray d = new DeleteElementFromArray();
System.out.println("Array Elements are ");
for (i = 0; i < l; i++){
System.out.println(a[i]);
}
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.println("Enter the Element for Delete");
try {
String s = br.readLine();
f = Integer.parseInt(s);
for (i = 0; i < l; i++) {
if (f == a[i]) {
System.out.println("Delete Element found from given array");
k = i;
j++;
d.DeletElementInt();
}
}
l = l - 1;
System.out.println("New Array ");
for (i = 0; i < l; i++)
{
System.out.println(b[i]);
}
if (j == 0) {
System.out.println("Entered Element does not found from given array");
}
} catch (IOException e) {
System.out.println(e);
}
}
}
//output
/*
Array Elements are
5
1
2
3
4
5
7
8
9
10
Enter the Element for Delete
5
Delete Element found from given array
New Array
1
2
3
4
5
7
8
9
10
*/
Here is the fixed code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DelElem {
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[10];
static int f, i, k, j = 0;
static int l = a.length;
static void DeleteElementInt(int elementToDelete) {
j = 0;
for (int i = 0; i < l; i++)
if (a[i] != elementToDelete)
b[i - j] = a[i];
else
++j;
}
public static void main(String[] args) {
System.out.println("Array elements are:");
for (i = 0; i < a.length; i++)
System.out.println(a[i]);
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.print("Enter the element to be deleted: ");
try {
String s = br.readLine();
f = Integer.parseInt(s);
DeleteElementInt(f);
System.out.println("New array:");
for (i = 0; i < l - j; i++)
System.out.println(b[i]);
if (j == 0)
System.out.println("Entered element was not found in the given array");
} catch (IOException e) {
System.out.println(e);
}
}
}
//output
/*
Array elements are:
5
1
2
3
4
5
7
8
9
10
Enter the element to be deleted: 5
New array:
1
2
3
4
7
8
9
10
*/
First you have to sort your array. It will be much easier for you to remove the duplicates if you do. The Arrays class contains various methods (most of them are static) to manipulate arrays. Use Arrays.sort(array). If you're not allowed to, you have to use one of the many existing sorting algorithm. The simplest being Bubble sort.
Insert the first integer in your result array, and in a temporary variable which will contain the last inserted value. Parse the source array: if the current value is different than the temporary var, insert it in the result array (and update the temp var).
Be careful with the size of your return array.
is Arrays.sort() okay?
static int[] a = {5,1,2,3,4,5,7,8,9,10};
static int[] b = new int[a.length];
Arrays.sort(a);
b[0]=a[0];
int bIndex = 1;
for(int aIndex = 1; aIndex < a.length; aIndex++) {
if(b[bIndex-1] != a[aIndex]) {
b[bIndex] = a[aIndex];
bIndex++;
}
}
int[] result = Arrays.copyOfRange(b, 0, bIndex);
if this is for educational purposes another interesting approach could be to construct a tree structure with the numbers and flatten the tree to an array when all inserts are done.
The first question when some one ask you to work with arrays should be. Do the order is important ?
Most problem with arrays can be solved by sorting it first and then the problem is reduced to trivial from complex as you always work on the same type of data. As Archimedes sad once "Give me a place to stand on, and I will move the Earth". The sort operation is that stand place.
When you sort your array, then you just need to traverse it and find that next item is equal to previous. This is trivial.
How ever if the order is important then we have a little bit harder task.
So first solution that pop i my mind is to create new point to stand. The rules are that array has items grater or equal then zero.
In this case we could do something like this.
We find the grates element in our source array.
We create a boolean array with size of grates item.
We move through each item of source list and
We check that boolean arrays position of value has false if so then we set it to true an print the result else we go to next item of source array.
The step 4 was simplified as we want to print the list. The technical aspect of returning new one with distinct values is trivial to.
So good luck.
import java.util.Scanner;
public class RemoveAllOccurences{
static int[] removeAll(int[] a,int n){
int[] dupl = new int[a.length];
for(int i = 0;i < dupl.length;i++){
dupl[i] = -999;
}
int index = 0;
//looping over,finding all occurrences of n and creating new array that does not contain n.
for(int i = 0;i < a.length;i++){
if(a[i] != n){
dupl[index++] = a[i];
}
}
//returning array with all duplicates removed.
return dupl;
}
public static void main(String[] args) {
int[] a = {3,5,5,5,3,6,5,3,3};
int numberToRemove;
System.out.println("the array values are:");
for(int i:a){
System.out.print(a[i]+"\t");
}
Scanner sc = new Scanner(System.in);
System.out.println("\nenter the number for which all occurences need to be deleted:");
numberToRemove = sc.nextInt();
int[] b = removeAll(a,numberToRemove);
System.out.println("After removing all occurences of "+numberToRemove);
for(int i:b){
if(i != -999)
System.out.print(i+"\t");
}
}
}
Below is my solution:
First step:- Iterate through array with nested loops to find duplicates
Second step:- If found duplicates copy all elements in new array except duplicate element.
Please find below code, any improvement would be appreciated.
public class DuplicateElements {
private static int[] arr = new int[]{3,2,4,4,5,3,8,2,4,9,10};
public static void main(String[] args) {
for(int i=0;i<arr.length;i++){
int arr_i = arr[i];
for(int j=0;j<arr.length;j++){
if(arr_i == arr[j] && i != j){
removeElement(j);
}
}
}
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+", ");
}
}
public static void removeElement(int position){
int[] intArr = new int[arr.length - 1];
for(int i=0;i<position;i++){
intArr[i] = arr[i];
}
for(int i=position+1;i<arr.length;i++){
intArr[i-1] = arr[i];
}
arr = intArr;
}
}
public static void main(String[] args) {
int a[]={1,4,3,2,6,5,7,3,5,4,2};
int b[]=new int[a.length];
Arrays.sort(a);
int j=0;
for(int i=0;i<a.length;i++){
while(i<a.length-1 && a[i]==a[i+1]){
a[i]=999; // This can be any tag which you are not going to have in your array
i++;
}
if(a[i]!=999)
b[j++]=a[i];
}
System.out.println(b);
}
Use:
package Array;
import java.util.Scanner;
public class DuplicateArrayElement {
//operation
void duplicate(int arr[],int size) {
int count=0;
for(int i=0;i<size-1;i++) {
for(int j=i+1;j<size;j++) {
if(arr[i]==arr[j]) {
arr[i]=0;
count++;
}
}
}
for(int i =0; i<size;i++) {
if(arr[i]!=0) {
System.out.println(" "+arr[i]);
}
}
System.out.println("Total duplicate number : "+count);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DuplicateArrayElement duplicateArrayElement = new DuplicateArrayElement();
try {
System.out.println("Enter the size of array:");
int size = input.nextInt();
int arr[] = new int[size];
System.out.println("Enter the elements: ");
for (int i = 0; i < size; i++) {
arr[i] = input.nextInt();
}
System.out.println("Orignal Array: ");
for (int i : arr) {
System.out.print(" " + i);
}
System.out.println("\nAfter removing duplicate values :");
duplicateArrayElement.duplicate(arr, size);
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println(ex);
} finally {
input.close();
}
}
}