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();
}
}
}
Related
I am having issues passing arrays to my methods it is getting an error of "cannot find symbol"but I am confused on how these 2D arrays should be passed in the method "how many" This program is supposed to prompt for 18 ints and placed into 2 2D arrays then return of they are equal or not. Am I supposed to place the array names in boolean equalOrNot = howmany(FirstArray, SecondArray);
or what?
import java.util.Scanner;
public class n01092281
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int FirstArray [][] = new int[3][3];
int SecondArray [][] = new int[3][3];
System.out.print("Enter List1 and List2 (18 numbers): ");
for (int row = 0; row < FirstArray.length; row++)
{
for(int column = 0; column < FirstArray[row].length; column++)
{
FirstArray[row][column] = input.nextInt();
}
}
for (int row = 0; row < SecondArray.length; row++)
{
for(int column = 0; column < SecondArray[row].length; column++)
{
SecondArray[row][column] = input.nextInt();
}
}
boolean equalOrNot = howmany(FirstArray, SecondArray);
if (equalOrNot)
{
System.out.println("Two Arrays Are Equal");
}
else
{
System.out.println("Two Arrays Are Not equal");
}
}
public class strict
{
public boolean howmany(int[][] FirstArray, int[][] SecondArray)
{
boolean equalOrNot = true;
if(FirstArray.length == SecondArray.length)
{
for (int i = 0; i < FirstArray.length; i++)
{
if(FirstArray[i] != SecondArray[i])
{
equalOrNot = false;
}
}
}
else
{
equalOrNot = false;
}
}
}
}
Few points that could help over the shared code :
Please follow better-naming conventions.
public boolean howmany does not have a return statement to actually return a boolean value, possibly add at the end of the method :
return equalOrNot;
The comparison should also be over the number of columns of the array and the condition should become somewhat like :
if(FirstArray[i][j] != SecondArray[i][j])
You cannot call howmany method currently from a static context even considering Strict to be an inner class(with those inappropriately matched braces).
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());
}
The exercise I'm trying right now will require me to to
Gather 10 values from the user to store into an array
Display the mode of the 10 values
(possible using a parallel array to count the occurrences of the values)
use a method to use entered values as a parameter for and return the array with max values in order
This is the code I have so far:
The issue is that my mode worked for 10 DEFINED values but once I tried to mess with it and add the scanner for the values I lost myself
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arraytwo = {10};
test3(arraytwo);
number = scan.nextInt;
number = arraytwo[i];
}
public static void test3(int[] array)
{
int modeTrack[] = new int[10];
int max =0; int number =0;
for (int i = 0; i < array.length; i++)
{
modeTrack[array[i]] += 1;
}
int maxIndex = 0;
for (int i = 1; i < modeTrack.length; i++)
{
int newNum = modeTrack[i];
if (newNum > modeTrack[maxIndex])
{
maxIndex = i;
}
}System.out.println(maxIndex);
}
This code will take ten values and sort them in descending order..Hope it will help you..save below code in Test.java and run it
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Integer[] array = new Integer[10];
Scanner scan = new Scanner(System.in);
for (int i = 0; i <10; i++) {
array[i] = scan.nextInt();
}
doSort(array);
}
static void doSort(Integer[] array)
{
Arrays.sort(array,Collections.reverseOrder());
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
It sounds like your test3() method isn't what's giving you trouble so I'll talk a bit about your main() method.
You have a few errors in your main() denoted by comments I have inserted:
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int[] arraytwo = {10};
test3(arraytwo);
number = scan.nextInt; //number does not exist in this scope, also nextInt method should use () to call it.
number = arraytwo[i]; //i does not exist in this scope
}
For the main method, I suggest you do something like the following:
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Integer[] arrTwo = new Integer[10];
for (int i = 0; i < 10; i++)
{
arrTwo[i] = scan.nextInt();
}
sort(arrTwo);
//System.out.println(Arrays.toString(arrTwo)); //this line will print your sorted array for you..
}
For the sort method you could do something like the following:
public static void sort(Integer[] arr){
Arrays.sort(arr, Collections.reverseOrder());
}
I am trying to create a Mastermind game in which colors are numbers [] and one number can never repeat itself in the String. The string should be made of 4 characters. I cannot figure out why my code keeps on printing strings with repeated characters.
import java.util.Random;
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
String toGuess="";
while(!IsValidNumber(toGuess));
{
for(int i=0; i<4; i++)
{
Random rando= new Random();
int rd=rando.nextInt(9);
toGuess=toGuess+rd;
}
}
System.out.println(toGuess);
}
public static boolean IsValidNumber(String s) // boolean
{
boolean noRepetition = true;
for(int i = 0; i < s.length(); i++)
{
for(int j = 0; j < i; j++)
{
if(i == j)
{
continue;
}
else if(s.charAt(i) == s.charAt(j))
{
noRepetition = false;
return false;
}
}
}
return noRepetition;
}
}
The boolean IsValidNumber never operates, I tried to print simple check words at different levels of it, and nothing ever prints but the String.
Thanks in advance, cheers
You've got a stray semicolon after the while() declaration, which causes the loop to immediately end. Consequently, your for loop constructs a number, and whatever number it constructs is immediately printed.
Consider the following instead:
public static void main(String[] args)
{
String toGuess="";
do { // Always try to generate at least one number.
toGuess = ""; //Reset each time we loop.
for(int i=0; i<4; i++) {
Random rando= new Random();
int rd=rando.nextInt(9);
toGuess=toGuess+rd;
}
} while(!IsValidNumber(toGuess));
System.out.println(toGuess);
}
That might work better.
Basically, while (exp); is equivalent to while(exp) {} or an empty while loop. Only put a semicolon after your while(exp) when using the do...while construct I illustrate here.
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;
}