I have created this code (with the help of Reimeus). How would I achieve to instead of replace every value in the array with true to replace only one pre determined (by z for example) and this always being a value on the top column of the 2d array. Furthermore I would like to how I should start to get instead of the output being true and false it being x for true and y for false but still keeping the array an boolean
import java.util.*;
class Main {
public static void main(String[] args) {
int x;
int y;
Scanner scanner;
scanner = new Scanner(System.in);
x = scanner.nextInt();
y = scanner.nextInt();
boolean[][] cells = new boolean[x][y];
for (int i = 0; i < cells.length; i++) {
Arrays.fill(cells[i], true);
System.out.println(Arrays.toString(cells[i]));
}
}
}
Use Arrays.toString to display the array content, otherwise the Object#toString representation of the Object arrays will be displayed
System.out.println(Arrays.toString(cells[i]));
Aside from Reimeus answer:
What would I need to do if I would want to make only 1 piece of the array true and decide where this true should go in the same way as I decide the length of the array.
Using fact that boolean arrays are by default filled with false values you just need to read once index of element that should be set to true just like you did with lengths
boolean[][] cells = new boolean[x][y];
int trueX = scanner.nextInt();
int trueY = scanner.nextInt();
cells[trueX][trueY] = true;
also don't forget to remove Arrays.fill(cells[i], true);
Secondly is there a way in which I could replace the true statement with "*" and the false statement with "-"
You can create second loop that will iterate over elements of row and if it its value is true print * if not - like in this code:
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
if (cells[i][j])
System.out.print("* ");
else
System.out.print("- ");
}
System.out.println();
}
or just replace "true" string from result of Arrays.toString() with * and "false" with "-"
for (int i = 0; i < cells.length; i++) {
System.out.println(Arrays.toString(cells[i]).replace("true", "*")
.replace("false", "-"));
}
Related
I am new to Java and I need to create a two dimensional array of boolean of which the dimensions of can be changed and then display the boolean table, but I am getting some errors.
I tried using the reccomended fixes but these made more errors
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner joos = new Scanner(System.in);
System.out.println("Please enter the desired height of the grid.");
int y = joos.nextInt();
System.out.println("Please enter the desired width of the grid.");
int x = joos.nextInt();
boolean [] [] height = new boolean[y][x];
//System.out.println(y);
//System.out.println(x);
int i = 0;
int j = y*x;
for (i<=j:i++;) {
System.out.println(height[i]);
}
}
}
There's a couple things going on here:
First, the statement for(i<=j; i++;) is not a valid way to create a for loop. Secondly, if i<j, but j=x*y, then you are going to get an ArrayIndexOutOfBoundsException when you call height[i] when i>=y.
If you want to do something for each position in your 2d array, you can use the following nested loops:
for (int i = 0; i < y; i++){
for (int j = 0; j < x; j++) {
// do something now with the boolean at height[i][j]
boolean value = height[i][j];
System.out.println(value);
}
}
The general idea here is that a 2d array requires a "2d" loop (in other words, 2 nested loops) to access each element.
I am trying to get this code to read in a text file and then populate a 15x15 grid with the numbers from the file. What it is doing is only populating the grid with 0's. I am not sure how to fix it, but I think the issue is with how I am trying to use list.indexOf() in the loop.
I have tried switching to use list.get(i) or using j, which has not worked the way I need it to.
public Grid(String fileName) throws FileNotFoundException {
//reading file using scanner
Scanner sc = new Scanner(new File(fileName));
//first number is the dimension for rows
this.rows = sc.nextInt();
//since it is square matrix second dimension is same as first
this.cols = this.rows;
grid = new boolean[rows][cols];
String longNumber = sc.next();
List<Integer> list = new ArrayList<>();
for(char ch : longNumber.toCharArray()) {
list.add( Integer.valueOf(String.valueOf(ch)));
}
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) {
//reading from file 1 and 0 if 1 then store true else store false in grid
if (list.indexOf(i) == 1)
grid[i][j] = true;
else
grid[i][j] = false;
}
}
I am getting an output showing a 15x15 block of 0's, instead of the 1's and 0's that are being read in from the text file. The text file should be read in and displayed (along with a count of blobs or clumps of 1's), but this is not happening. If you need the rest of the code, please let me know. I am required to read in a file, which contains an int (15) which is used to make the grid, and then 15 lines of 1's and 0's, which should be displayed in the same way when the program works properly.
Why are you converting it into a List<Integer>? You can simply work with String that you got from the file.
For each row, you'll have to get a String and then for each of such a String you can do charAt() to check what is the character there and store true or false in grid accordingly.
The code will look something like this:
this.rows = sc.nextInt();
//since it is square matrix second dimension is same as first
this.cols = this.rows;
grid = new boolean[rows][cols];
for (int i = 0; i < rows; i++) {
String longNumber = sc.next();
for (int j = 0; j < cols; j++) {
//reading from file 1 and 0 if 1 then store true else store false in grid
grid[i][j] = (longNumber.charAt(j) == 1);
}
}
Notice that I've placed String longNumber = sc.next() in the outer loop.
HTH
Im trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}
Here in array I insert 0 value in all array index, now I want to check if any array index is equal to 0, then replace the value 0 by value 1, but only one time. for example at the beginning it will find index [0]==0 then replace it by 1 then stop the execution. if index[0]==1, then loop need to find next index where value==0 and replace that value 0 with 1.
public class test {
static int roomArray[] = new int[10];
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
roomArray[i] = 0;
System.out.println(roomArray[i]);
}
test.book();
}
public static void book() {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the room you want to book");
int desiredRoom = sc.nextInt();
for (int i = 0; i < 10; i++) {
if (roomArray[i] == 0) {
roomArray[desiredRoom] = 2;
}
}
}
}
You can change it to
int desiredRoom= sc.nextInt();
if(roomArray[desiredRoom]==0){
roomArray[desiredRoom]= 2;
}
so you are checking and setting the same position
Your code and your requirements to not really match. If you go for
now i want to check if any array index ==0; then replace the value 0 by value 1, but only one time. for example in the begining it will find index [0]==0 then replace it by 1 then stop the execution. if index[0]==1, then loop need to find next index where value ==0 and replace that value 0 with 1.
then it could be like adding a break or even return
for (int i=0; i<10; i++){
if(roomArray[i]==0){
roomArray[desiredRoom]= 2;
break;
}
}
If you want to check only the desired rom, then it is like Scary Wombats answer.
I'm having trouble with this, maybe you could help me:
I have 3 strings like: word1, word2, word3 and I have to build a matrix with them, like this:
on the first row : word1("ABC"), second row: word2("DEF") and third row: word3("GHI").
A|B|C
D|E|F
G|H|I
I need this because after that I have to check if the formed words ("ADG","BEH","CFI") are in an array of words. And I don't know how to put those strings in the matrix so I can check. Any help is useful.
Thanks
Based on this comment:
the words have the same size, because the matrix is actually like a puzzle. I choose randomly 3 words from an array, put them in a matrix and check after that if the words resulted are from the same array.
I'll assume some things in order to make this work (since we don't have enough info):
You have an array of Strings where you have all the words
private String[] words;
You have a method to randomly pick up 3 Strings from this array.
private String s1, s2, s3;
public void pickThreeRandomWords() {
s1 = aRandomWord(words);
s2 = aRandomWord(words);
s3 = aRandomWord(words);
//or maybe another fancy algorithm to get this...
}
So you would need an array of array of chars based on these 3 Strings. This code could do the work for you:
public char[][] createMatrixFromStrings(String s1, String s2, String s3) {
char[][] theMatrix = new char[3][]; //yes, hardcoded
theMatrix[0] = s1.toCharArray();
theMatrix[1] = s2.toCharArray();
theMatrix[2] = s3.toCharArray();
return theMatrix;
}
Of course, if you would want to make this method to support more than 3 Strings you can make the method to receive a random quantity of Strings:
public char[][] createMatrixFromStrings(String ... strings) {
if (strings == null || strings.length == 0) return null;
char[][] theMatrix = new char[strings.length][];
int i = 0;
for(String s : strings) {
theMatrix[i++] = s.toCharArray();
}
return theMatrix;
}
You can build the result words without a matrix:
List<String> verticalWords = new ArrayList<String>();
for (int i = 0; i < horizontalLen; i++){
String currentWord = "";
for (int j = 0; j < wordCount; j++)
currentWord += words.get(j).get(i);
verticalWords.add(currentWord);
}
P.S. For the currentWord you can use a StringBuilder to make it more efficient, but I doubt it is highly needed here.
Java doesn't have matrix.It has array of array
So,you can try this
List<char[]> lst=new ArrayList();//stores a list of char[]
lst.add(("ADC".toCharArray()));//adds array of characters i.e 'A','D','C'
lst.add(("DEF".toCharArray()));
lst.get(0)[0];//A
lst.get(1)[0];//D
Now you can iterate vertically
for(int i=0;i<lst.size();i++)temp+=lst.get(i)[0];
temp would have AD which you can now cross check with equals method
The main thrust of this goal is that you're taking a one-dimensional value, and converting it into a two-dimensional value. There are many ways you can do this, but here are the two that come off the top of my head:
Set up a nested while loop to iterate over the first dimension, and when it reaches the length, reset and cause the outer loop to increment, much like a clock
You can create a new subarray using ArrayUtils.toSubArray(), and with some finagling, get that to work:
Create a new row of the array each time, based on the dimension slices you want to hit up. I'll leave figuring this one out as an exercise for the reader. But here's a hint:
for(int i = 0; i < theDimension; i++, j += 3) {
ret[i] = ArrayUtils.subarray(word, i*theDimension, j);
}
Lastly, I assume that there's a restraint on the type of input you can receive. The matrix must be square, so I enforce that restriction before we build the array.
I strongly encourage you to poke and prod this answer, and not just blindly copy it into your schoolwork. Understand what it's doing so you can reproduce it when you're asked to again in the future.
public char[][] toMatrix(int theDimension, String theEntireWord) {
if(theEntireWord.length() != theDimension * theDimension) {
throw new IllegalArgumentException("impossible to add string to matrix of uneven dimension");
}
char[][] ret = new char[theDimension][theDimension];
int i = 0;
int j = 0;
while(i < theDimension) {
if(j == theDimension) {
j = 0;
++i;
} else {
ret[i][j] = theEntireWord.charAt((i * theDimension) + j);
j++;
}
}
return ret;
}
I think this will sort your problem.
package printing;
public class Matrix {
public static void main(String[] args) {
//Length can define as you wish
String[] max = new String[10];
String[] out = null;
//Your Inputs
max[0]="ADG";
max[1]="BEH";
max[2]="CFI";
//following for loop iterate your inputs
for (int i = 0; i < max.length; i++) {
if(out==null){out= new String[max.length];}
String string = max[i];
if(string==null){ break;}
//Here breaking input(words) one by one into letters for later contcatnating.
String[] row = string.split("");
for (int j = 0; j < row.length; j++) {
String string1 = row[j];
// System.out.println(string1);
//create the values for rows
if(out[j]!=null){ out[j]=out[j]+string1;}
else{
out[j]=string1;
}
}
}
//following for loop will out put your matrix.
for (int i = 0; i < out.length; i++) {
String string = out[i];
if(out[i]==null){break;}
System.out.println(out[i]);
}
}
}