Scanner Two-dimensional array (n x n) - java

import java.util.Scanner;
class Test1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] num = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < 0; j++)
if (i == j)
num[i][j] = 1;
else
num[i][j] = 0;
for (int[] a : num) {
for (int b : a)
System.out.print(b + " ");
System.out.println();
}
}
}
i want to make
1 0 0
0 1 0
0 0 1
but my answer come out like
0 0 0
0 0 0
0 0 0

It looks like your code is kicking out of the inner loop, the one using j as the variable. You initialize j = 0, and then if j < 0 it will execute. However, 0 < 0 is false so it never iterates thru the inner loop. Try changing that line to
for (int j = 0; j < n; j++) and I'll expect you'll get the result you are looking for.

you need to loop through all elements in 2d array not just the 0th element. see modified for loop.
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] num = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (i == j)
num[i][j] = 1;
else
num[i][j] = 0;
for (int[] a : num) {
for (int b : a)
System.out.print(b + " ");
System.out.println();
}
}
}

Related

Take in a positive integer n Create n triangles in stars with their bases below of size n each

Help with this question:
Take a positive integer n and form n triangles from stars with their base down of size n each.
For example, for input 3, the following output will be obtained:
* * *
** ** **
*** *** ***
Here's what I've tried.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter n");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) {
for (int c = 1; c <= n - r; c++)
System.out.print(" ");
for (int c = 1; c <= r; c++)
System.out.print("*");
System.out.println();
}
}
}
Here's my solution, with explanations in comments
import java.util.Scanner;
class Main {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in)) {
System.out.println("enter n");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) { // <-- we will have to print n rows
printLine(n, r);
}
}
}
static void printLine(int n, int lineNumber) {
StringBuffer line = new StringBuffer();
for(int i = 0; i < n; i ++) { // <-- each line will have '*'s for n triangles
for(int j = lineNumber; j > 0; j--) { // <-- each line has as many '*'s as its line number, so print those first
line.append("*");
}
for(int j = 0; j < n - lineNumber + 1; j ++) { // <-- we then have to add enough spaces to leave room for the next triangle's '*'s
line.append(" ");
}
}
System.out.println(line.toString()); // <-- print the line we've built so far
}
}
EDIT:
Here's a replit that avoids one of the loops by using a modulo to print an entire line at once, and also uses recursion, for no real reason, in place of the outer-most loop: https://replit.com/#anqit/MicroExtrovertedTrace#Main.java
First, the blanks follow the stars, then, you have to repeat n times the two loops:
for (int r = 1; r <= n; r++) {
for (int t = 1; t <= n; t++) {
for (int c = 1; c <= r; c++)
System.out.print("*");
for (int c = 1; c <= n - r; c++)
System.out.print(" ");
}
System.out.println();
}
You have one for loop that prints out a single triangle of stars using nested for loops. The outer loop is responsible for the number of rows and the inner loops are responsible for printing the spaces and stars.
In my updated code, I added an outer loop that runs n times, and each time it runs, it prints out a triangle of stars. The inner loops are responsible for printing the stars of the triangle and spaces between the triangles.
The main difference is that in your first code, only one triangle is printed, while in my updated code, n triangles are printed. In addition, the indentation of the inner loops has been adjusted to align the triangles correctly on the same line.
import java.util.Scanner;
public class ex3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter n:");
int n = input.nextInt();
while (n <= 0) {
System.out.println("error: please enter a positive number:");
n = input.nextInt();
}
for (int r = 1; r <= n; r++) {
for (int t = 1; t <= n; t++) {
for (int c = 1; c <= r; c++) {
System.out.print("*");
}
for (int i = 0; i < n - r + 1; i++) {
System.out.print(" ");
}
}
System.out.println();
}
}
}
Here is a 3 forloop variant
int n = 4;
for (int i = 1; i <= n; i++) {
StringBuilder b = new StringBuilder("");
for (int s = 0; s < n; s++) {
b.append(s < i ? "*" : " ");
}
String line = b.append(" ").toString();//space between
for (int j = 1; j < n; j++) {
System.out.print(line);
}
System.out.println();
}
produces
> * * *
> ** ** **
> *** *** ***
> **** **** ****

Count and print even flowers

We have n number of flowers that can be black or white. We have m number of months. At the end of each month, if the number of white flowers is even, we print B for the number of roses that are even, and print F for the rest of the characters.For example:(W=white,B=black)
input:3(n) 2(m)
WBW
BBW
output:FBB
My code just work well just for this example and dont give true answer for other examples.
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of flowers: ");
int flower = input.nextInt();
System.out.println("Enter number of months : ");
int month = input.nextInt();
String[] arr = new String[month];
char ch = ' ';
int count = 0;
for (int j = 0; j < month; j++)
arr[j] = input.next();
for (int i = 0; i < month; i++) {
char[] s = arr[i].toCharArray();
for (int j = 0; j < flower; j++) {
if (s[j] == 'W') {
count++;
}
}
if (count % 2 == 0) {
for (int k = 0; k < flower - count; k++) {
System.out.print('F');
}
for (int b = 1; b <= count; b++) {
System.out.print('B');
}
}
}
}
}
In your for loop
for (int j = 0; j < flower; j++) {
if (s[j] == 'W') {
count++;
}
}
We must remember what s is referring to, char[] s = arr[i].toCharArray(); which means that s will not have a length of flower but will have a length of arr[i].length() or s.length.
So if you change the for loop to use that as its control, it should solve the index out of bounds exception that you get.
The fix would look like:
for (int j = 0; j < s.length; j++) {
if (s[j] == 'W') {
count++;
}
}

Find lowest matching values in Java

I created this program that allows the user to input 5 numbers for array 1 and 5 numbers for array 2, the idea of the program is to iterate through those arrays and find the matching values for example: user types on input 1 = 1, 2, 3, 4 and 5 and the same for input 2, the lowest matching value is 1 and my program does that, if there is no matching value displays a message that there is no matching values and my program does that. However, if the user inputs something like this on 1 = 3, 4, 5, 7, 2 and input 2 = 9, 12, 8, 7, 15, what my program does in this case, variable min1 on array1 find lowest value which is 2 and variable min2 on array2 find lowest value which is 7 so in theory does not match, but they are asking me to find the lowest MATCHING values so both of them have 7 so it should display 7, I have some code there that select the 7 on each array and display them, now I have to figure out how to add that temporal variable into the displays so it only displays one or the other, as of now it displays 7 and then no matching value, tried adding it to the if statement but couldn't make it
import java.util.Scanner;
public class SmallestArrayItem {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int array1[] = new int[5];
int array2[] = new int[5];
System.out.println("Please enter 5 values for array 1");
for(int i = 0; i < array1.length; i++) {
int userInput = keyboard.nextInt();
array1[i] = userInput;
}
System.out.println("Please enter 5 values for array 2");
for(int i = 0; i < array2.length; i++) {
int userInput = keyboard.nextInt();
array2[i] = userInput;
}
int min1 = array1[0];
for(int index1 = 1; index1 < array1.length; index1++) {
if(array1[index1] < min1) {
min1 = array1[index1];
}
}
int min2 = array2[0];
for(int index2 = 1; index2 < array2.length; index2++) {
if(array2[index2] < min2) {
min2 = array1[index2];
}
}
int tmpval = Integer.MAX_VALUE;
for(int i = 0; i < array1.length; i++){
for(int j = 0; j < array2.length; j++){
if(array1[i] == array2[j]){
// same value
if(tmpval > array1[i]){
tmpval = array1[i];
}
}
}
}
System.out.println(tmpval);
if(min1 == min2) {
System.out.println("The Smalest match in the array is : " + min1);
} else if(min1 != min2) {
System.out.println("There is no smallest matching integer!");
}
}
}
Your code look great, its just a problem with your logic. In your question, you talked about nesting for loops, so you were on the right track.
int[] arr1 = {3,4,5,7,2};
int[] arr2 = {9,12,8,7,15};
int tmpval = Integer.MAX_VALUE;
for(int i = 0; i < arr1.length; i++){
for(int j = 0; j < arr2.length; j++){
if(arr1[i] == arr2[j]){
// same value
if(tmpval > arr1[i]){
tmpval = arr1[i];
}
}
}
}
System.out.println(tmpval);
It's not clear from your description if the matching values have to be at the same position in the two arrays. If we assume that they do then something like this would work:
int[] arr1 = {3,4,5,7,2};
int[] arr2 = {9,12,8,7,15};
int minIdx = -1;
for(int i = 0; i < arr1.length; i++)
{
if(arr1[i] == arr2[i] && (minIdx < 0 || arr1[i] < arr1[minIdx]))
{
minIdx = i;
}
}
if(minIdx < 0)
System.out.println("No match");
else
System.out.println("Min match: " + arr1[minIdx]);
Note how we use a negative index as an indicator that we haven't found a match. The standard trick of using Integer.MAX_VALUE as our starting value isn't really safe as it could be a matching value in the array.
If the matching values can appear at any position in the arrays then you'll need to compare each value in array1 with every value in array2:
for(int i = 0; i < arr1.length; i++)
{
for(int j = 0; j < arr2.length; j++)
{
if(arr1[i] == arr2[j] && (minIdx < 0 || arr1[i] < arr1[minIdx]))
{
minIdx = i;
}
}
}
Thanks for all your help guys, this is the final code:
public class SmallestArrayItem {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int array1[] = new int[5];
int array2[] = new int[5];
System.out.println("Please enter 5 values for array 1");
for(int i = 0; i < array1.length; i++) {
int userInput = keyboard.nextInt();
array1[i] = userInput;
}
System.out.println("Please enter 5 values for array 2");
for(int i = 0; i < array2.length; i++) {
int userInput = keyboard.nextInt();
array2[i] = userInput;
}
int minIdx = -1;
for(int i = 0; i < array1.length; i++)
{
for(int j = 0; j < array2.length; j++)
{
if(array1[i] == array2[j] && (minIdx < 0 || array1[i] < array1[minIdx]))
{
minIdx = i;
}
}
}
if(minIdx < 0)
System.out.println("There is no smallest matching integer!");
else
System.out.println("The Smallest match in the array is : " + array1[minIdx]);
}
}

Two-dimentional arrays [duplicate]

This question already has answers here:
Syntax for creating a two-dimensional array in Java
(13 answers)
Closed 3 years ago.
I am working with 2-D arrays and I require help on this topic. My task is to create a 2-D array such that it is n by n (i.e. the number of rows and columns are equal). Fill the array with alternating 0's and 1's
void setup()
{
int n=3;
// code to populate the array
// code to display the output of array in a table format
/* output should be as follows:
The expected result when n=3 should be as the following:
1 0 1
0 1 0
1 0 1
*/
}
Solution:
class test{
public static void main(String[] args) {
int n = 3;
int[][] arr = setup(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}
static int[][] setup(int n){
int[][] arr = new int [n][n];
boolean even = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = even ? 1 : 0;
even = !even;
}
}
return arr;
}
}
Output:
0 1 0
1 0 1
0 1 0
This should work.
You can replace the 3 that is given to n with any number you want as the 2D-Array's length.
void setup(){
int n = 3;
int count = 0;
int[][] myArray = new int[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(count % 2 == 0){
myArray[i][j] = 1;
}
else{
myArray[i][j] = 0;
}
System.out.print(myArray[i][j] + " ");
count++;
}
System.out.println();
}
}
Output:
0 1 0
1 0 1
0 1 0
It's not complex, you just have to iterate two loops, that's it. Although you can get the solution on different ways.
public static void main(String[] args) {
int n = 3;
int [][] arr = new int[n][n];
int val = 1;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
arr[i][j] = val;
val = (val == 0) ? 1 : 0;
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
Output:
0 1 0
1 0 1
0 1 0
A simple implementation:
void setup()
{
int n=3;
final int[][] array = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((n * i + j) % 2 == 0) {
array[i][j] = 1;
}
}
}
}
Here is how you can approach your logic , create a counter and negate each time after it prints value.
public static void main(String[] args) {
int counter = 0;
int n = 3;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(counter==0?1:0);
counter = ~counter;
}
System.out.println();
}
}
Output
101
010
101
Here is Online source code.

Scanner array (n x n)

My code :
import java.util.Scanner;
class Test1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] num = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
System.out.print(num[i][j] + " ");
System.out.println();
}
}
the answer come out
0 0 0
0 0 0
0 0 0
but i want to make
1 0 0
0 1 0
0 0 1
As explain in the doc of Java, a int is initialized with the value 0. So when you only declare your array without setting specific value, it only contains 0. That's why your output is
0 0 0
0 0 0
0 0 0
You need to first initialize your array to put the value 1 in the wanted places. In your case you want to make an identity matrix, so put 1 in the places that have the same index for row and column (In the diagonal). This should look like this :
for (int i = 0; i < n; i++)
num[i][i] = 1;
Place this initialization before printing the array, so the full code will look like :
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] num = new int[n][n];
for (int i = 0; i < n; i++)
num[i][i] = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
System.out.print(num[i][j] + " ");
System.out.println();
}

Categories