Taking Space Separated Row Inputs in a Two dimensional Array - java

Im relatively new to programming and i was working with a problem that requires me to read space separated integers and input them into a two dimensional array but i dont seem to understand why I am not able to do so . any hint on possible approaches will be helpful
Eg. Input will look like this
2 //FOR DIMENSION
2 3 //ROW1
4 5 // ROW 2
import java.io.*;
import java.util.*;
import java.lang.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc= new Scanner(System.in);
System.out.println("Hello World");
System.out.println("Enter Dimension of Matrix");
int N= sc.nextInt();
int[][] m=new int [N][N];
for (int i=0;i<N;i++)
{ System.out.println("Enter Elements of row "+ i);
for(int j=0;j<N;j++ )
{
m[i]=sc.nextInt();
}
}
System.out.println(m);
}
}
I tested the above code and got the following result on the console
HelloWorld.java:16: error: incompatible types: int cannot be converted to int[]
m[i]=sc.nextInt();
^
First of all, I would like to know is my thinking(approach) right?
Second, what are the possible ways to do this correctly?

here you go:
import java.io.*;
import java.util.*;
import java.lang.*;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Dimension of Matrix");
int N = sc.nextInt();
int[][] m = new int[N][N];
for (int i = 0; i < N; i++) {
System.out.println("Enter Elements of row " + i);
for (int j = 0; j < N; j++) {
m[i][j] = Integer.valueOf(sc.next());//replaced line with proper code
}
}
sc.close();
System.out.println(Arrays.deepToString(m));//use this api to print arrays
}
}

m is a multidimensional array meaning you must specify m[i][?]. Like so
m[i][j]=sc.nextInt();
Your logic is a little off, you want to ask the user for input at row start i, and for the other columns j. Try this and happy coding :)
for (int i=0;i<N;i++){
for(int j=0;j<N;j++){
System.out.println("Enter Elements of row "+ i);
m[i][j]=sc.nextInt();
}
}
for (int i=0;i<N;i++){
for(int j=0;j<N;j++){
System.out.print(m[i][j]);
}
System.out.println();
}

Related

user needs to input 10 elements in the array with JOptionPane

How does the program will ask 10 elements for the array with JOptionPane and then in the end it will show the 10 elements? It only ask one element and its done.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Array1
{
public static void main(String[] args)
{
int n = 10;
Scanner sc=new Scanner(System.in);
int[] array = new int[10];
JOptionPane.showInputDialog(null, "Enter ten elements for the array: ");
for(int i=0; i<n; i++)
{
array[i]=sc.nextInt();
}
JOptionPane.showMessageDialog("The elements are: ");
for (int i=0; i<n; i++)
{
JOptionPane.showMessageDialog(null, array[i]);
}
}
}

How to accept the 2d array being returned

In my below code, I'm checking whether the entered rows and columns are equal and then accepting the array and proceeding to calculate the sum of the diagonal elements. I understand that I can take only one variable for rows and columns but this is what our assignment says.
import java.util.*;
class main
{
int[][] acceptarray(int a[][]) //Accepting the 2d array
{
Scanner xd = new Scanner(System.in);
System.out.println ("Enter the elements of array : ");
for( int i =0; i <a.length; i++)
{
for(int j=0; j<a[0].length; j++)
{
System.out.println("Enter element "+(i)+","+(j));
a[i][j] = xd.nextInt();
}
}
xd.close();
return(a);
}
boolean check(int b[][]) //checking whether rows and colums are equal or not
{
if(b.length==b[0].length)
{return(true);}
else
return(false);
}
int sum(int c[][]) // Sum of the the diagonal of the matrix
{ int sum=0;
for(int i=0;i<=c.length;i++)
{
for(int j=0;j<=c[0].length;j++)
{
if(i==j)
{
sum =sum+c[i][j];
}
}
}
return(sum);
}}
class dsum
{
public static void main(String Args[])
{
Scanner xd = new Scanner(System.in);
System.out.println("Enter number of Rows");
int m = xd.nextInt();
System.out.println("Enter number of Columns");
int n = xd.nextInt();
xd.close();
int a[][] = new int [m][n];
main s = new main();
boolean p = s.check(a);
if(p)
{
System.out.print("It is a Square Matrix:\n\n");
s.acceptarray(a);
int b[][] =s.acceptarray(); //line with the error message
s.sum(b);
}
else
{
System.out.println("It's not a square matrix");
System.exit(0);
}
}
}
The error message is:
b =s.acceptarray();
^
required: int[][]
found: no argument
reason: actual and formal argument lists differ in length
For the record, I'm a newbie so I'm not aware of the all the concepts.
So, Can someone please help me out on how to accept this 2d array that is being returned by the acceptarray function. It'll help me understand the only concept I'm not able to understand since a week.
Peace.
You never declared a method acceptarray that doesn't take an argument. Try int b[][] =s.acceptarray(a);

How to take n input in java according to the value of test cases?

How can we take n input in java according to value of T
Like if i take t=2,then we take two n input
If value of t=3,then we take three n input
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
int t=s.nextInt();
int n=s.nextInt();
int n=s.nextInt();
int evensum=0;
for (int i=1; i<=n; i++) {
if(i%2==0) {
evensum=evensum+i;
}
System.out.print(evensum);
}
}
As in this code i take t=2 and I take two n inputs.
If I take t=3, then what how could I take that third input?
You can't have multiple variable with the same name, for your purpose use a loop :
Scanner s = new Scanner(System.in);
System.out.println("How many values ?");
int nbInput = s.nextInt();
for (int i = 1; i <= nbInput; i++) {
int input = s.nextInt();
System.out.print(input);
}

How to display Distinct values Only in an Array, Java Programming

This is my post first here and I wanted to know how to remove elements in an array that have already been entered. for an assignment due Monday. The console will print all values entered in a distinct manner meaning it will only print values that have only been entered once.
People will be prompted with the message "Enter an integer" ten times and the system will take those values and remove any duplicates but only displaying one of the two entered. I.E if 17 is entered twice only display the first 17.
So here's my code I have so far
import java.util.Scanner;
import java.util.Arrays;
public class Unit03Prog2 {
public static void main(String[] args) {
//Array
int Numbers[] = new int[10];
Scanner Numb = new Scanner(System.in);
for(int i=0; i < Numbers.length; i++){
System.out.print("Enter an integer: ");
//Stores it, and moves to the next line
Numbers[i]= Numb.nextInt();
//Removes duplicates
//Code to remove duplicates goes here VVVV
//Ends it if i = 10
if(i == Numbers.length)
{
break;
}
//End of for statement
}
System.out.println("The number of distinct values is " + Arrays.toString(Numbers));
//end of main method
}
//end of Class
}
So the code works and all but it displays every value entered no matter what. I only need numbers that have only been entered once
I.E
Enter an integer : 11
Enter an integer : 12
Enter an integer : 13
Enter an integer : 14
Enter an integer : 15
Enter an integer : 16
Enter an integer : 16
Enter an integer : 17
Enter an integer : 19
Enter an integer : 19
It should say The number of distinct values is 11 12 13 14 15 16 17 19
Thanks guys,
Joshua.
You can use a Set to solve it:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Set;
public class Main {
public static void main(String[] args) {
//Array
int Numbers[] = new int[10];
Set<Integer> integerSet = new HashSet<>();
Scanner Numb = new Scanner(System.in);
for(int i=0; i < Numbers.length; i++){
System.out.print("Enter an integer: ");
//Stores it, and moves to the next line
Numbers[i]= Numb.nextInt();
//Removes duplicates
//Code to remove duplicates goes here VVVV
integerSet.add(new Integer(Numbers[i]));
if(i == Numbers.length) {
break;
}
}
System.out.println("The number of distinct values is " + Arrays.toString(integerSet.toArray()));
}
}
Replace the code to remove the duplicates. I suggest to before inserting into the array, check for duplicates. If the entered number is duplicate, skip it and read the next input.
import java.util.Scanner;
import java.util.Arrays;
public class Unit03Prog2 {
public static void main(String[] args) {
//Array
int Numbers[] = new int[10];
Scanner Numb = new Scanner(System.in);
int j = 0;
int inputNumber;
boolean isDuplicate;
for(int i=0; i < Numbers.length; i++){
isDuplicate = false;
System.out.print("Enter an integer: ");
//Stores it, and moves to the next line
inputNumber = Numb.nextInt();
//Removes duplicates
//Code to remove duplicates goes here VVVV //Ends it if i = 10
for (int k=0; k<j; k++) {
if(inputNumber == Numbers [k]) {
isDuplicate = true;
break;
}
}
if(! isDuplicate) {
Numbers[j++] = inputNumber;
}
//End of for statement
}
System.out.println("The number of distinct values is " + Arrays.toString(Numbers));
//end of main method
}
//end of Class
}
Yes, Use a Set, which only contains unique element, to achieve your purpose.
Maybe you need to keep the sequence of input, but Set does not keep sequence.
I think you want to have a logic to remove duplicated records in an array, right?
Try this:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Set;
public class Main {
public static void main(String[] args) {
//Array
int Numbers[] = new int[10];
Set<Integer> integerSet = new HashSet<>();
Scanner Numb = new Scanner(System.in);
for(int i=0; i < Numbers.length; i++){
System.out.print("Enter an integer: ");
//Stores it, and moves to the next line
Numbers[i]= Numb.nextInt();
integerSet.add(new Integer(Numbers[i]));
}
//Array to keep unique items with same sequence of input
int uniqueNumbers[] = new int[integerSet.size()];
integerSet= new HashSet<>();
for(int i=0;i<Numbers.length;i++){
if(!integerSet.contains(Numbers[i])){
uniqueNumbers[integerSet.size()]=Numbers[i];
integerSet.add(Numbers[i]);
}
}
System.out.println("The number of distinct values is " + Arrays.toString(uniqueNumbers));
}
public static void main(String[] args) {
int a[] = {1,2,3,4,5,1,2};
for(int i=0; i<a.length;i++) {
int count = 0;
for(int j=0; j<a.length;j++) {
if(a[i]==a[j] && i!=j) {
count++;
break;
}
}
if(count == 0) {
System.out.println(a[i]);
}
}
}

Selection sort with arrays from keyboard in java

Good Morning,
I'm trying to write a code where the user writes some numbers in the keyboard (casually), and the program should write them in order, from the lower to greater.
I don't remember in particular how to insert the number from the keyboard to the array or to the arraylist class if i don't want any limit.
This is my code. i know it is not correct.
import java.util.*;
class Ordine {
public static void main (String [] args) {
Scanner s = new Scanner (System.in)
System.out.println; ("insert the number which you need to order");
int n = s.nextInt();
int [] x = new int [200];
for (int i=0; i<x.length; i++) {
x [i] = s.nextInt();
for (int j=i+1; j<x.length; j++) {
if (x[i] > x[j]) {
//cambia ELEMENTI
int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
}
}
Thank you!
Since array have fixed size you will have to use arraylist. Below is the code
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class test{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
ArrayList<Integer> a = new ArrayList<Integer>(Arrays.asList(1,2,3,4,8,9,10,13));
try{
while (true)
{
int l=0;int r=a.size()-1,m=0;
int p=in.nextInt();
while(l<=r){
m=(l+r)/2;
if(a.get(m)>p){
l=l;r=m-1;
}
if(a.get(m)<p){
l=m+1;r=r;
}
if(a.get(m)==p){
l=m;
break;
}
}
a.add(l,p);
System.out.println("Entered number is: "+p);
System.out.print("Sorted arraylist is: ");
for(int j=0;j<a.size();j++){
System.out.print(a.get(j)+" ");
}
System.out.println();
}
}
catch(Exception e){
}
}
}
I have intitialized the arraylist. And it will print the ordered arraylist everytime you enter a new number.
Below is a sample output

Categories