I'm just learning to use multidimensional arrays in java.
I got an error when i try to create a matrix of 3x3 which values inputted by the user.
import java.util.Scanner;
public class myMatrix
{
public static void main(String args[])
{
double[][] matrixOne = new double[3][3];
double[][] matrixTwo = new double[3][3];
double[][] finalMatrix = new double[3][3];
Scanner takeInput = new Scanner(System.in);
System.out.println("Enter values of matrix One");
for(int i=0;i<3;i++)
{
for(int j=0;i<3;j++)
{
matrixOne[i][j] = takeInput.nextDouble();
}
}
System.out.println("Enter values of matrix Two");
for(int i=0;i<3;i++)
{
for(int j=0;i<3;j++)
{
matrixTwo[i][j] = takeInput.nextDouble();
}
}
for(int i=0;i<3;i++)
{
for(int j=0;i<3;j++)
{
finalMatrix[i][j] = matrixOne[i][j] + matrixTwo[i][j];
System.out.print(finalMatrix[i][j] + "\t");
}
System.out.println();
}
}
}
After inputting 4 numbers, i get an error that array index out of bounds.
Why's that?
Have i made any mistake in the program?
for(int j=0;i<3;j++)
{
matrixOne[i][j] = takeInput.nextDouble();
}
In this loop you're checking for i<3 not j<3 this would cause your error.
Its only a small mistake. Your second "for" loop is using "j" as variable but checking "i" for condition
for(int j=0;i<3;j++)
All of the inner loops have the same issue:
for(int j=0;i<3;j++)
It should be j not i.
Change it to the following code:
for(int j=0;j<3;j++)
Related
lets say I have an input of [10,8,6,15,2,-1]
the output should be [15,10,8,15,6,2]
I have written a set of code:
public static void main(String[] args) {
int[] unsortesArray=new int[]{10,8,6,15,2,-1};
int len=unsortesArray.length;
for(int i=0;i<len; i++){
for(int j=0; j<len; j++){
if(unsortesArray[i]<unsortesArray[j]){
unsortesArray[i]=unsortesArray[j];
}
}
System.out.println(unsortesArray[i]);
}
}
but not getting the expected output. Please suggest the solution.
You need to swap the two numbers:
public static void main(String[] args) {
int[] unsortesArray=new int[]{10,8,6,15,2,-1};
int len=unsortesArray.length;
for(int i=0;i<len; i++){
for(int j=i+1; j<len; j++){
if(unsortesArray[i]<unsortesArray[j]){
int temp = unsortesArray[i]; // create a temp var to store the value you are going to swap
unsortesArray[i]=unsortesArray[j]; // swap the value
unsortesArray[j] = temp; // save it back again in the array
}
}
System.out.println(unsortesArray[i]);
}
}
I have an assignment where I need to create a 3x5 array and ask the user for a boolean input. I then need to print the user input into every cell of the array. I'm stuck on how to use a for loop to enter the user input into the array. I also have to do this using methods. My code so far is:
import java.util.*;
public class TrueFalse
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
boolean myA[][] = new boolean [5][3];
popArray(myA);
}
public static void popArray(boolean answ, boolean pArray[][])
{
System.out.println("Enter true or false.");
answ = console.nextBoolean();
for (int i=0; i<pArray.length; i++)
{
pArray[i] = answ;
}
}
}
You're not far off:
for (int i=0; i<pArray.length; i++) {
for (int j=0; i<pArray[i].length; j++) {
System.out.println("Enter true or false.");
pArray[i][j] = console.nextBoolean();
}
}
will do the trick. Note you defined a matrix with 5 rows and 3 columns, the opposite of what you write in the text. Also note I'm checking nothing here.
Your code is not far off. Try iterating over the bounds of the array in your popArray method:
public static void popArray(boolean pArray[][]) {
for (int r=0; r < pArray.length; ++r) {
for (int c=0; c < pArray[0].length; ++c) {
System.out.println("Enter true or false.");
boolean answ = console.nextBoolean();
pArray[r][c] = answ;
}
}
}
One convenient option for printing your 2D array is Arrays.deepToString(), e.g.
System.out.println(Arrays.deepToString(pArray));
To make 3*5 array of boolean you should do
boolean myA[][] = new boolean [3][5];
And make nested loop. and you can index the value to the array variable myA[ i ][ j ]
for(int i=0;i<3;i++){
for(int j=0;j<5;j++){
myA[i][j]=false;
}
}
In your code you have a two dimensional array but your not assessing it correctly. You can visualized your 2d array as a matrix with 5 rows and 3 columns. So to assess every location you need to specify the row and column numbers. Your code should look like this:
private static int ROWS= 5;
private static int COLUMNS = 3;
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
boolean myA[][] = new boolean [ROWS][COLUMNS];
popArray(myA);
}
public static void popArray(boolean answ, boolean pArray[][])
{
System.out.println("Enter true or false.");
for (int i=0; i<COLUMNS ; i++)
{
for (int j=0; j<ROWS; j++)
{
pArray[i][j] = console.nextBoolean();
}
}
}
I am trying to copy my instrumentalist array into a new array called copy array and when I go to run it, it just goes blank after I am done the do while loop and doesn't print out the musicians names I have entered. from what I can find and know already I thought this is the right way to copy an array to another. thank you in advanced for your personal input
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner keyboard= new Scanner(System.in);
final int MAXPEOPLE=100;
instrumentalist [] instrumentalistArr;
instrumentalistArr=new instrumentalist[MAXPEOPLE];
char choice;
int index=0;
int instrumentalistCOUNT=0;
do {
instrumentalist ainstrumentalist = new instrumentalist();
ainstrumentalist.readin();
instrumentalistArr[index]=ainstrumentalist;
instrumentalistCOUNT++;
index++;
System.out.println("would you like to enter another data set yes or no");
choice=keyboard.next().charAt(0);
} while(choice!='n');
instrumentalist [] copyarray;
copyarray=new instrumentalist[instrumentalistArr.length];
for(int i=0; i<instrumentalistCOUNT; i++) {
copyarray[i]=instrumentalistArr[i];
}
for(int i=0; index<instrumentalistCOUNT; i++) {
System.out.println("musician"+" "+ copyarray[index].getmusicianname());
}
}
}
In this for loop:
for(int i=0; index<instrumentalistCOUNT; i++)
{
System.out.println("musician"+" "+ copyarray[index].getmusicianname());
}
Change index to i.
So your for loop should be:
for(int i=0; i<instrumentalistCOUNT; i++)
{
System.out.println("musician"+" "+ copyarray[i].getmusicianname());
}
Im having trouble sorting my array list in ABC order. This is what I have so far, any ideas on how to achieve it? My output is switching some of the words, but not putting the whole array list in ABC order. I'm lost, as you can tell from my loops at the end =[
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListLab
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
ArrayList <String> words = new ArrayList <String> ();
for (int x = 0; x < 10; x++)
{
System.out.println("Pick a word, any word!");
words.add(scan.nextLine());
}
for (int x = 0; x < 9; x++)
{
words.get(x).compareTo(words.get(x+1));
if (words.get(x).compareTo(words.get(x+1))>0)
{
String temp = words.get(x+1);
words.set((x+1),words.get(x));
words.set(x, temp);
}
else
if (words.get(x).compareTo(words.get(x+1))<0)
{
words.get(x);
}
else
if(words.get(x).compareTo(words.get(x+1))==0)
{
words.get(x);
}
}
System.out.println(words);
}
}
Make the user enter 5 integer values into the array in the main method. Pass array into a separate function. There, check for duplicated values in the array. If duplicates are found, eliminate the duplicate integer and replace it with -1.
Print the processed array back in the main method.. i think i know how to replace the value with -1 but how do I return the array to the main back again. The code is:
package methods;
import java.util.*;
public class remdup {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
check(x);
// Insert method here
}
//Method check starts here...
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
for (j=i+1; j<len-1;j++ ) {
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
System.out.println("Duplicate found");
}
}
}
}
}
use a Set to keep track of the numbers you already have. Iterate over your array and check if the set contains the number at your current position. if yes: replace it with -1. if no: add the number to the set...
public static void check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index]) {
y[index] = -1;
} else {
foundNumbers.add(y[index]);
}
}
}
you replace number in the array like this:
y[i] = -1;
but your check function will not work this way.
Since this is homework, I will not go into details however, if you look at your check function:
public static void check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
int j = i+1;
for (i=0; i<len-1; i++) {
if (y[i]==y[j]) {
//how to replace numbers???
System.out.println("Duplicate found");
}
}
}
You will notice that you are initially setting j to 1, but you are never updating its value. So in your for loop, you need to update the value of j at the end of each iteration.
You also need to include an extra loop, one which holds the current number and another one which checks the rest. Lastly, to overwrite the value you have, simply write to the array like so: y[i] = -1.
Change your whole like this way
import java.util.*;
public class test1 {
public static void main (String[]args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
int [] x= new int [5];
for (int i=0; i<5; i++) {
x[i]=in.nextInt();
}
int z[]=check(x);
for(int o=0;o<z.length;o++)
{
System.out.println(z[o]);
}
// Insert method here
}
//Method check starts here...
public static int[] check(int []y) {
// int pos = y[0];
int len=y.length;
int i=0;
//int j = i+1;
for (i=0; i<len; i++) {
for(int j=0;j<i;j++)
{
if (y[i]==y[j]) {
//how to replace numbers???
y[i]=-1;
// System.out.println("Duplicate found");
}
} }
for(int k=0;k<len;k++)
{
//System.out.println(y[k]);
}
return y;
}
}
This will work for you.
public static void main(String[] args){
Scanner in = new Scanner (System.in);
System.out.println("Enter 5 integers: ");
Map<Integer,Integer> map=new HashMap<>();
int [] x= new int [5];
for (int i=0; i<5; i++) {
int val=in.nextInt();
x[i]=val;
Integer iniVal=map.get(val);
if(iniVal==null){
iniVal=0;
}
map.put(val,iniVal+1);
}
int[] y=getNewArr(x,map);
for (int i=0;i<y.length;i++){
System.out.println(y[i]);
}
}
public static int[] getNewArr(int[] x,Map<Integer,Integer> map){
for(int i=0;i<x.length;i++){
int numElement=map.get(x[i]);
if(numElement!=1){
for(int j=0;j<i;j++){
if(x[i]==x[j]){
x[i]=-1;
}
}
}
}
return x;
}
input array: {1,4,5,1,2}
Output array: {1,4,5,-1,2}
Though this is a very old post I think there is an error in the accepted answer. We should be adding the replaced number back to the array. However in the accepted answer we are replacing it with -1 but we are never adding it back to SET.
Below is my corrected solution :
public static Set<Integer> check(int []y) {
Set<Integer> foundNumbers = new HashSet<Integer>();
for(int index = 0; index < y.length; index++) {
if(foundNumbers.contains(y[index])){
y[index] = -1;
}
foundNumbers.add(y[index]);
}
return foundNumbers;
}