2D Array: Magic Square - java

The question I am working on is:
A square with the side length n is filled with numbers 1,2,3,...n2 is a magic square if the sum of elements in each row, column, and two diagonals is the same value.
Write a program that reads in a value of 16 values from the keyboard and tests whether they form a magic square when put into a 4 x 4 array. You need to test the following 2 features:
Does each number of 1,2,...16 occur in user input? Tell the user to try again if they enter a number that they've already entered.
When the numbers are put into a square, are the sums of rows, columns, and diagonals equal to each other?
It must be done using two-dimensional array
I am having trouble with asking the user to try again if they enter a number that they have previously entered. And, numbers in 4 x 4 do not print.
What am I doing wrong? How can I fix it?
This is the code I have so far:
Scanner in = new Scanner (System.in);
int n =4;
int[][] square = new int[n][n];
int number = 0;
int num = 0;
for (int i = 0; i <16; i++){
number = num;
System.out.print ("Enter a number: ");
num = in.nextInt();
int num_2 = 0;
if (number==num || number==num_2) {
System.out.println ("Try again.");
System.out.println ("Enter a number: ");
num_2 = in.nextInt();
}
if (num > 16){
System.out.println ("Try again.");
break;
}
}
for (int i= 0; i < n; i++){
for (int j = 0; j < n; j++) {
num+=square [i][j];
System.out.print(square[i][j] + "\t");
}
}
}
}

You can try this code for 1st feature and add code for 2nd one.
int ar[][] = new int[4][4];
System.out.println("Enter Numbers");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
boolean flag = false;
int num = sc.nextInt();
if (num > 16 || num < 1) {
System.out.println("Please Enter number between 1 to 16");
flag=true;
j--;
} else {
for (int k = 0; k <= i; k++) {
for (int l = 0; l <= j; l++) {
if (ar[k][l] == num) {
System.out.println("This number already inserted...Please give another");
j--;
flag = true;
}
}
}
}
if (!flag) {
ar[i][j] = num;
}
}
}
If you can't understand anything please ask.
Hope this help.

Related

Program ends after entering a string in Java

I've been looking for different solutions out here but on my code they won't work. I'm getting an input from a user but then it doesn't display what's inside the if-else statement. I tried to do a different code for the if statement but it doesn't work. The int input works but it doesn't work in the string input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int numbers [] = new int[10];
int temp;
String sc = " ";
Scanner scan = new Scanner(System.in);
// Loop through array
// Change value of each array per iteration
System.out.print("Enter 10 integers: ");
for(int i = 0; i < numbers.length; i++){
numbers[i] = scan.nextInt();
}
System.out.print("\nPlease Choose Among The Following:");
System.out.println("\n A - Display the numbers \t B - Display the values of even indexes \n C - Display the values of odd indexes \t D - Display the values in ascending order \n E - Display the values in descending order");
System.out.print("\nEnter The Letter of Your Choice: ");
sc = scan.nextLine();
if (sc.equals('A') || sc.equals('a')){
System.out.print("Display each item in array");
for(int number: numbers){
System.out.println(number);
}}
else if (sc.equals('B') || sc.equals('b')){
System.out.println("Display odd indexes");
for(int i = 0; i < numbers.length; i++){
if(i % 2 == 0){
System.out.println(numbers[i]);
}
}}
else if (sc.equals('C') || sc.equals('c')){
System.out.println("Display even indexes");
for(int i = 0; i < numbers.length; i++){
if(i % 2 == 1){
System.out.println(numbers[i]);
}
}}
else if (sc.equals('D') || sc.equals('d')){
int [] ascendingList = numbers.clone();
System.out.println("Display in ascending order using bubble sort");
for(int i = 0; i < ascendingList.length - 1 ; i++){
for(int j = 0; j < (ascendingList.length - i - 1); j++){
if(ascendingList[j] > ascendingList[j+1]){
temp = ascendingList[j];
ascendingList[j] = ascendingList[j+1];
ascendingList[j+1] = temp;
}
}
}
for(int number: ascendingList){
System.out.println(number);
}}
else if (sc.equals('E') || sc.equals('e')){
int [] descendingList = numbers.clone();
System.out.println("Display in descending order using bubble sort");
for(int i = 0; i < descendingList.length - 1 ; i++){
for(int j = 0; j < (descendingList.length - i - 1); j++){
if(descendingList[j] < descendingList[j+1]){
temp = descendingList[j];
descendingList[j] = descendingList[j+1];
descendingList[j+1] = temp;
}
}
}
for(int number: descendingList){
System.out.println(number);
}}
}
}

Printing a * on each line as output

I'm fairly new to java. This is how the output to my problem should be:
Enter a number between 5 and 20:
5.....5 stars* on the first line. 4 stars on the sec. 3 on the next and so on one star on the last line.
I did everything but I can't get the stars to print that way, here is my code:
int number;
int num_stars;
Scanner num = new Scanner(System.in);
System.out.println("Enter a number between 5 and 20"); user to enter a
number = num.nextInt();
for(int i= 5; i >= number; i--)
{
// inner loop to handle number of columns
// values changing acc. to outer loop
for(int j = 20; j >= i; j--)
{
// printing stars
System.out.print("* ");
}
// ending line after each row
System.out.println();
}
thank you for your time
try this:
for (int i=number;i>0;i--){
for(int j=i;j>0;j--){
System.out.print("*");
}
System.out.println( );
}
but try this kind of exercises to solve on your own. It builds up your logic.
you can try fallowing code.. work for me..
int number;
int num_stars;
System.out.println("Enter a number between 5 and 20");
Scanner s = new Scanner(System.in);
number = Integer.valueOf(s.nextLine());
num_stars=number;
for (int i = 1; i <= number; i--) {
for (int j = 0; j < num_stars; j++) {
System.out.print("*");
}
num_stars--;
System.out.println();
}
System.out.println("over");
}

Number Triangles with alternating number

Hello All,
I was wondering if someone could help me with making a number triangle in Java that looks like the one below using nested while loops. Would someone be able to help me out?
4
56
789
1234
56789
I have a variable 'i' on the outer loop determining how many rows the triangle will be and a variable 'j' on the inner loop determine which number the triangle will begin with. the numbers have to stay between [1-9].
Can anyone help me out?
Try This, It Will Work... It accepts rows & number through user and in first for loop it runs the loop till the number of rows and second loop print the number as per the value of I in pattern and if condition to check if the number is 10 then reset the number with 1 to start the numbering again.
import java.util.Scanner;
public class Pattern {
public static void main(String[] args) {
int rows, number = 1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter no of rows");
rows = sc.nextInt();
System.out.println("Enter no to start with");
number = sc.nextInt();
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(number + " ");
++number;
if (number == 10) {
number = 1;
}
}
System.out.println();
}
}
}
Try.. r is for number of rows and v is the value
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
int v = sc.nextInt();
int i = v - 1;
int j = 1;
while(j != r + 1){
int k = 0;
int ans = 0;
while( k < j){
i = i + 1;
if(i == 10){
i = 1;
}
ans = ans * 10 + i;
k = k + 1;
}
System.out.println(ans);
j = j + 1;
}

how to find prime number in 2d array and copy these numbers to another array

i have a code that create 2d array by asking user to enter the input than the system check if the elements are prime or not and if they are prime the system will copy them to an 1d array.
i can create the 2d array but i am stuck in the checking on the prime number and copied to a second array
this is the code
package question6;
import java.util.Scanner;
public class MtrixPrime {
public static void main(String[] args) {
int rows;
int cols;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of row");
rows = sc.nextInt();
System.out.println("Enter number of column");
cols = sc.nextInt();
int[][] matrix = new int[rows][cols];
int[] array = new int[rows];
System.out.println("Enter numbers in the matrix");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if(matrix[i][j] % matrix[i][j] ==0 && matrix[i][j] %1 == 0){
////here i am stuck can anyone help me ??
array[i * j];
}
matrix[i][j] = sc.nextInt();
}
}
for(int row = 0 ;row<matrix.length; row++){
for(int col = 0 ; col< matrix.length; col++){
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}
I know it's old post but this might help others.
Used isPrime a boolean flag to save the state of matrix[i][j] value.
If reminder is 0 isPrime will hold false state of matrix[i][j].
Everything is similar like finding prime number of single number. Just have to use 3 for loops for matrix index, before that I have taken matrix values separately.
here's the code.
public static void main(String[] args) {
int rows, cols, remainder;
boolean isPrime = true;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of row and colums : ");
rows = sc.nextInt();
cols = sc.nextInt();
int[][] matrix = new int[rows][cols];
System.out.println("Enter numbers in the matrix");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = sc.nextInt();
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
for (int k = 2; k <= matrix[i][j] / 2; k++) {
remainder = matrix[i][j] % k;
if (remainder == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(matrix[i][j] + " is a Prime number");
} else
System.out.println(matrix[i][j] + " is not a Prime number");
}
}
}
One tricky thing to look out for is that since you don't know how many primes you're going to get, and you're using regular arrays, you need a 1d array at least the total size of your 2d array, or you should just use an ArrayList. If you're set on using a primitive array, you could just add a counter that increases every time you find a new prime, and use that counter value as your index. This however would leave you with zeros on the back end of your array. If you want your index to correspond to the multi-dimensional array index, you multiply the row index by the number of members in the row, and then add the column index in order to get a 1d index as shown below. This would leave you with zeros inbetween elements in your array. Having zeros shouldn't necessarily be a bad thing since it isn't prime, but its still way easier in my mind to use an ArrayList.
int[][] nums2d = {{0,1,2},{3,4,5},{6,7,8}};
int[] nums1d = new int[9];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int index = i * 3 + j;
nums1d[index] = nums2d[i][j];
}
}

Java Arrays: Finding Unique Numbers In A Group of 10 Inputted Numbers

I'm at a loss here.
I have this homework assignment where I have to enable the user to input 10 numbers, place them in an array, and figure out which inputted numbers are unique.
This is my workflow right now: Input number> If number has not been inputted before, store in array; if number has been inputted before, ignore> Display the numbers inputted> Display the unique numbers
ex: Inputting 1 2 3 5 1 2 4 6 would find the unique numbers and show "1 2 3 4 5 6"
So far my code looks like this:
public class HwChapter6 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int[] count = new int[10];
int number = 0;
int x = 0;
boolean unique = false;
int length = count.length;
System.out.println("Insert 10 single digit numbers in any order your heart desires:");
for (int i = 0; i < count.length; i++) {
count[i] = input.nextInt();
number = count[i];
for (int j = 0; j < count.length; j++) {
Thanks for the help guys.
Instead of an array of input values, put them in a Set of Integers. Sets, by definition, store only unique values. If you add 3 'foos', there will be only one 'foo' in the set.
// Add this to your top-level loop
Set<Integer> uniqueValues = new TreeSet<Integer>;
uniqueValues.add(number);
// Add this after the loop to write all unique values on one line
for (Integer value : uniqueValues) {
System.out.print(value.toString() + " ");
}
// Now end the line.
System.out.println();
Check the numbers at they are entered, then keep track of which ones are unique by marking the same positions in a second (boolean) array with true if they are unique and false otherwise.
Then, when you print out the unique values, only print the value from each position in numbers[] if that position in uniques[] contains true.
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
boolean[] uniques = new boolean[10];
for(int i = 0; i < 10; i++) {
System.out.println("Please enter a value: \n" + "[" + (i + 1) + "]: ");
numbers[i] = input.nextInt();
uniques[i] = true;
for(int j = 0; j < 10; j++) {
if(numbers[i] == numbers[j] && i != j) {
uniques[i] = false;
}
}
}
System.out.println("\nThe numbers you entered were: \n");
for(int i = 0; i < 10; i++) {
System.out.println(numbers[i] + ", ");
}
System.out.println("done.\n\n");
System.out.println("\nThe uniqe numbers you entered were: \n");
for(int i = 0; i < 10; i++) {
if(uniques[i]) {
System.out.println(numbers[i] + ", ");
}
}
System.out.println("done.\n\n");
Store all numbers in an array.
For each stored number: check if number was inserted before and save that in a boolean array.
Print all numbers that are not marked in the boolean array.
java.util.Scanner input = new java.util.Scanner(System.in);
int[] numbers = new int[10];
boolean[] usedBefore = new boolean[10];
// Insert all numbers
for (int i = 0; i < numbers.length; i++) {
// Read number from console
numbers[i] = input.nextInt();
// Check if number was inserted before
usedBefore[i] = false;
for(int k = 0; k < i; k++) {
if(numbers[k] == numbers[i]) {
usedBefore[i] = true;
break;
}
}
}
// Print all numbers that were not inserted before
for(int j = 0; j < numbers.length; j++) {
if(!usedBefore[i]) {
System.out.print(String.valueOf(numbers[j])+" ");
}
}
The fastest and most concise and efficient way is to destructively parse the array for uniques using its first number as a magic value, after all other operations on it are complete:
Scanner input = new Scanner(System.in);
int magic = 0;
int[] numbers = new int[10];
for(int i = 0; i < 10; i++) {
System.out.println("Please enter a value: \n" + "[" + (i + 1) + "]: ");
numbers[i] = input.nextInt();
}
System.out.println("\nThe numbers you entered were: \n");
for(int i = 0; i < 10; i++) {
System.out.println(numbers[i] + ", ");
}
System.out.println("done.\n\n");
System.out.println("The unique numbers are: ");
magic = numbers[0];
System.out.println(magic + ", ");
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(numbers[i] == numbers[j] && j != i) {
numbers[j] = magic;
}
}
if(numbers[i] != magic) {
System.out.println(numbers[i] + ", ");
}
}
System.out.println("done.\n\n");
Yes, I have two answers - this one is significantly different from the other one, and is better, though it is much more difficult for beginners to understand. Both solutions are valid, however.

Categories

Resources