I have an assignment about MAGIC SQUARE:
But i need to rewrite it.
This is my code at the moment:
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num= input.nextInt();
//Number must be ODD and not less than or equals to one to continue
while((num%2==0)||(num<=1)){
System.out.println("Enter a valid number: ");
num= input.nextInt();
}
int[][] magic = new int[num][num];
int row = num-1;
int col = num/2;
magic[row][col] = 1;
for (int i = 2; i <= num*num; i++) {
if (magic[(row + 1) % num][(col + 1) % num] == 0) {
row = (row + 1) % num;
col = (col + 1) % num;
}
else {
row = (row - 1 + num) % num;
// don't change col
}
magic[row][col] = i;
}
// print results
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
if (magic[i][j] < 10) System.out.print(" "); // for alignment
if (magic[i][j] < 100) System.out.print(" "); // for alignment
System.out.print(magic[i][j] + " ");
}
System.out.println();
}
Currently, my program output is:
My expected/desired output:
What I need is for the starting number (1) to be in the upper middle of the row x col then the pattern is up then left.
If the starting number should be the upper element is the only condition you are missing then iterating the print result row loop in reverse order will solve the problem. So instead of printing rows in order 0, 1, 2, ..., n, try to print rows in order n, n-1, n-2, ..., 1, 0.
Apply same logic to columns to get the output same as the goal output.
Related
I am having a hard time figuring out the solution to this problem. I need to write a program that gets an input n (via scanner), then goes with a for loop till that input number, checks if the numbers are divisible by 13 and then multiplies the digits of each number.
So for an example, if the input number is 40, the divisible numbers by 13 would be 13, 26, 39
1+3 = 4,
2+6 = 8,
3+9 = 12
so that's 4*8*12 = 384.
My current code, but I'm stuck here. I probably didn't do it right, too:
Scanner myScanner = new Scanner(System.in);
int num = myScanner.nextInt();
int sum = 0;
for (int i = 0; i < 30; i = i + 1) {
if (i % 13 == 0) {
while (i > 0) {
int add = i % 10;
sum = sum + add;
i = i / 10;
}
}
}
You're computing the sum of the digits, not the product. Also, you're loop is going to 30, not to num. (There's also no reason to start the loop at 0 instead of 1.) Finally, you shouldn't be changing i inside the loop itself; that will screw up the iteration logic. Use an auxiliary variable. Something like this (untested) should work:
Scanner myScanner = new Scanner(System.in);
int num = myScanner.nextInt();
int prod = 1;
for (int i = 1; i < num; i++) {
if (i % 13 == 0) {
int j = i,
sumOfDigits = 0;
while (j > 0) {
int digit = j % 10;
sumOfDigits += digit;
j /= 10;
}
prod *= sumOfDigits;
}
}
Your whole code is messy. You need to work more on loops and variable assignments and scopes.
Given below is the correct code.
Scanner myScanner = new Scanner(System.in);
int num = myScanner.nextInt();
int mul = 1;
for (int i = 1; i < num; i = i + 1) {
if (i % 13 == 0) {
int sum = 0;
int number = i; // = some int
while (number > 0) {
sum = sum + (number % 10);
number = number / 10;
}
mul = mul * sum;
}
}
System.out.println(mul);
myScanner.close();
Another way to do it, change the number that are divisible to char array, then add and multiply.
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt();
int prod = 1;
for (int i = 1; i < num; i++) {
if (i % 13 == 0) {
String number = String.valueOf(i);
char[] digits1 = number.toCharArray();
int sum = 0;
for (char ii:digits1) {
sum = Character.getNumericValue(ii) + sum;
}
prod = prod*sum;
}
}
System.out.println(prod);
This code is designed to list off the prime numbers between a minimum and maximum input by the user. When the numbers are output at the end of the code, they are all on the same line. I would like there to be ten numbers per line, so I assume that it takes a loop of some kind to indent every ten numbers, however I don't know how to do this. While I have the code posted here, other, unrelated feedback would be helpful.
String primenumbers = "";
System.out.println("Prime Number Generator.");
System.out.print("Minimum: ");
int oldmin = s.nextInt();
s.nextLine();
int min = oldmin;
System.out.print("Maximum: ");
int max = s.nextInt();
s.nextLine();
System.out.println();
for (min = min; min <= max; min++)
{
int counter=0;
int num = min;
for(num = min; num >= 1; num--)
{
if(min % num == 0)
{
counter = counter + 1;
}
}
if (counter == 2)
{
primenumbers = primenumbers +min+ " ";
}
}
System.out.println("Primes Between "+oldmin+" & "+max+":");
System.out.print(primenumbers);
Instead of concatinating prime numbers into a string, you can add them into a list and iterate the list in the end, e.g.:
primenumbers = primenumbers +min+ " "; will be replaced with
List<Integer> primenumbers = new ArrayList<>();
primenumbers.add(min);
After System.out.println("Primes Between "+oldmin+" & "+max+":"); statement, you can do the following:
for(int i=0 ; i < primenumbers.size() ; i++){
System.out.print(primenumbers.get(i) + " ");
if(i+1 % 10 == 0){
System.out.println();
}
}
As a class exercise I have to code using methods a program that:
1) Calculates the average of even and odd numbers in an array.
I expect on using one method to find the average of even and odd numbers. However, I'm having trouble on returning the right average. For example, if I enter only odd numbers I get an error, and vice versa.
This error:
"java.lang.ArithmeticException: / zero"
Also, if it were possible I would like to get some help on coding the rest of the exercise which asks for:
2) Print the highest and lowest number in the array
3) Allow the user to modify any of the numbers of the array
So far I have this code:
public static void main (String args[]){
int x[] = new int[4];
Scanner input = new Scanner(System.in);
for(int i = 0; i < x.length ; i++){
System.out.println("Enter a number: ");
x[i] = input.nextInt();
}
System.out.println("Average of even numbers: " + getAverage(x));
System.out.println("Average of odd numbers: " + getAverage(x));
}
public static int getAverage(int a[]){
int add_even = 0;
int counter_even = 0;
int average_even = 0;
int add_odd = 0;
int counter_odd = 0;
int average_odd = 0;
for(int i = 0; i < a.length; i++){
if(a[i] % 2 == 0){
add_even += a[i];
counter_even++;
}
else if(a[i] % 2 == 1) {
add_odd += a[i];
counter_odd++;
}
}
if (add_even % 2 == 1 && add_odd % 2 == 1){
average_even = 0;
average_odd = add_odd / counter_odd;
return average_even;
}
else if (add_even % 2 == 0 && add_odd % 2 == 0){
average_even = add_even / counter_even;
average_odd = 0;
return average_even;
}
else{
average_even = 0;
average_odd = add_odd / counter_odd;
return average_odd;
}
}
Thank you!
Your get average looks more complicated then it needs to be.
First off the getAverage(x):
System.out.println("Average of even numbers: " + getAverage(x));
System.out.println("Average of odd numbers: " + getAverage(x));
will return the same value, so if you wanted to get the average for odds or evens the method should require a boolean arg to represent odd or even.
In your method you should loop through all the numbers and check if it is even. If it is even and you are averaging evens add it to a "total" and add one to a counter. At the end divide "total" by the counter and return the value. The average will most likely include a decimal value, so you should return a double or a float.
Example:
public static double getAverage(int a[], boolean even){
double total = 0;//These are doubles so dividing later does not require casting to retain a decimal (this can be an int if you only want to return integers)
double counter = 0;
for(int i = 0; i<a.length; i++){
if(a[i] % 2 == 0 && even){//even
counter++;
total += a[i];
}else{//odd
counter++;
total += a[i];
}
}
if(total == 0){//Avoid dividing by 0.
return 0; //You can also throw an exception instead of returning 0.
}
return total / counter; //Returns the average for even or odd numbers.
}
For the second part of your question you need to loop through the numbers and find the highest and lowest while looping.
Example:
int highest = 0;
int lowest = 0;
for(int i = 0; i<x.length; i++){
if(x[i] > highest){
highest = x[i];
}
if(x[i] < lowest){
lowest = x[i];
}
if(i == 0){
highest = x[i];
lowest = x[i];
}
}
You have a divide by zero error cropping up here.
else if (add_even % 2 == 0 && add_odd % 2 == 0){
average_even = add_even / counter_even;
average_odd = 0;
return average_even;
}
0 % 2 == 0 so even if add_even is 0 (and as a result, so is counter_even) you're attempting to use it to divide. You'll need to account for that in your code by checking if counter_even is 0.
else if (counter_even != 0 && add_even % 2 == 0 && add_odd % 2 == 0){
1)Using one method to get the average of the even and odd numbers isn't proper because you only return one int. It would be simpler to use two methods but if you're insistent on using one method you could add a boolean as a parameter like this to decide which to do. To handle the ArithmeticException just return 0 if there are no values.
public static int average(int[] n, boolean even) {
int total = 0;
int count = 0;
for (int i = 0; i < n.length; i++) {
if (even == (n % 2 == 0)) {
total += n;
count ++;
}
}
if (count == 0)
return 0;
return total / count;
2)To check find the max and min value simply loop through the array like this
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < x.length; i++) {
if (x[i] < min)
min = x[i];
if (x[i] > max)
max = x[i];
}
3)To allow the user to modify the array, you could print the values and prompt them as to which value they would like to change like this.
System.out.print("Array: ");
for (int i = 0; i < x.length; i++) {
System.out.print(i + ",");
}
System.out.println();
System.out.println("Which value would you like to change?");
int index = input.nextInt();
System.out.println("What do you want the new value to be?");
int value = input.nextInt();
You can then run a method that changes the value of the array
edit(x, index, value);
public static int edit(int[] n, int index, int value) {
n[index] = value;
return n;
}
I used JS for this task, you can just rewrite my code to Java language.
A number is divisible by 2 if the result of its division by 2 has no
remainder or fractional component - in other terms if the result is an
integer. Zero is an even number because when 0 is divided by
2, the resulting quotient turns out to also be 0 - an integer (as a
whole number that can be written without a remainder, 0 classifies as
an integer).
function compareEvenOddAverage(arr) {
let even = 0,
odd = 0,
evenCounter = 0,
oddCounter = 0,
str = '';
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
even += arr[i];
evenCounter++;
} else {
odd += arr[i];
oddCounter++;
}
}
if (even / evenCounter > odd / oddCounter) {
str += 'Average value of even numbers is greater';
} else if (even / evenCounter < odd / oddCounter) {
str += 'Average value of odd numbers is greater';
} else {
str += 'Average values are equal';
}
return str;
}
console.log(compareEvenOddAverage([0, 1, 2, 3, 4, 5]));
I have a problem with a program I am trying to write. A user inputs a positive odd integer, otherwise the program prompts the user until they do. When they do, the program prints a diamond shape corresponding to the user input.
I have this piece so far that prints the left hand diagonal of such a figure, but cannot figure out how to print the rest of it. Here is the code:
import java.util.Scanner;
public class DrawingProgram {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the drawing program:");
System.out.println("Please Input a Positive Odd Integer:");
char userAnswer;
int userInput;
userInput = keyboard.nextInt();
if (userInput%2 == 0){
System.out.println("That is not a Positive Odd Integer!");
}
else if (userInput < 0){
System.out.println("That is not a Positive Odd Integer");
}
else if (userInput%2 == 1){
for (int row = 1; row<= userInput; row++){
for (int col = 1; col<= userInput; col++ ){
if (row+col==userInput-1 )
System.out.print( "*");
else
System.out.print( " ");
}
System.out.print("\n");
}
}
}
}
A user inputs a positive odd integer, otherwise the program prompts
the user until they do
You need to scan in a loop
do
{
userInput = keyboard.nextInt();
if (userInput % 2 == 0)
System.out.println("That is not an Odd Integer!");
if(userInput < 0)
System.out.println("That is not a Positive Odd Integer");
} while(userInput < 0 || userInput %2 == 0);
Now you can remove that validation else if (userInput%2 == 1){
Now the first thing I realize when checking at your loop is if (row+col==userInput-1 || ) which won't compile as you have a comparison operator with nothing following.
Note that you can replace System.out.print("\n"); with System.out.println("") but that's not really important...
Now replace your loop condition so that they start as 0
for (int row = 0; row <= userInput; row++){
for (int col = 0; col <= userInput; col++ ){
Now since you want a Diamond, you need to have 4 diagonal, so 2 loops (one for top and bottom)...
for (int i = 1; i < userInput; i += 2)//Draw the top of the diamond
{
for (int j = 0; j < userInput - 1 - i / 2; j++)//Output correct number of spaces before
{
System.out.print(" ");
}
for (int j = 0; j < i; j++)//Output correct number of asterix
{
System.out.print("*");
}
System.out.print("\n");//Skip to next line
}
for (int i = userInput; i > 0; i -= 2)//Draw the bottom of the diamond
{
for (int j = 0; j < userInput -1 - i / 2; j++)
{
System.out.print(" ");
}
for (int j = 0; j < i; j++)
{
System.out.print("*");
}
System.out.print("\n");
}
So the final code would look like this
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the drawing program:");
System.out.println("Please Input a Positive Odd Integer:");
char userAnswer;
int userInput;
do
{
userInput = keyboard.nextInt();
if (userInput % 2 == 0)
{
System.out.println("That is not an Odd Integer!");
}
if (userInput < 0)
{
System.out.println("That is not a Positive Odd Integer");
}
} while (userInput < 0 || userInput % 2 == 0);
for (int i = 1; i < userInput; i += 2) //This is the number of iterations needed to print the top of diamond (from 1 to userInput by step of two for example with 5 = {1, 3, 5} so 3 rows.
{
for (int j = 0; j < userInput - 1 - i / 2; j++)//write correct number of spaces before, example with 5 = j < 5 - 1 -i / 2, so it would first print 4 spaces before, with 1 less untill it reach 0
{
System.out.print(" ");//write a space
}
for (int j = 0; j < i; j++)
{
System.out.print("*");//write an asterix
}
System.out.println("");
}
// Same logic apply here but backward as it is bottom of diamond
for (int i = userInput; i > 0; i -= 2)
{
for (int j = 0; j < userInput -1 - i / 2; j++)
{
System.out.print(" ");
}
for (int j = 0; j < i; j++)
{
System.out.print("*");
}
System.out.print("\n");
}
}
Hi I created a Magic Square program in java
It works fine if you input a number 3 but if i input 5 and so on
there's a problem occurring..
The pattern becomes wrong.
Please help me to find out what's wrong in my code:
Here's my code:
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = input.nextInt();
// Number must be ODD and not less than or equals to one to continue
while ((num % 2 == 0) || (num <= 1)) {
System.out.println("Enter a valid number: ");
num = input.nextInt();
}
int[][] magic = new int[num][num];
int row = 0;
int col = num / 2;
magic[row][col] = 1;
for (int i = 2; i <= num * num; i++) {
if (magic[(row + 5) % num][(col + 2) % num] == 0) {
row = (row + 5) % num;
col = (col + 2) % num;
} else {
row = (row + 1 + num) % num;
}
magic[row][col] = i;
}
for (int x = 0; x < num; x++) {
for (int j = 0; j < num; j++) {
System.out.print(magic[x][j] + "\t");
}
System.out.println();
}
}
It's correct when i Input 3,
here's the output:
But when i type a number like 5:
It becomes:
UPDATED!
You seem to be trying to implement the Method for constructing a magic square of odd order.
The method prescribes starting in the central column of the first row with the number 1.
You seem to have that right.
After that, the fundamental movement for filling the squares is diagonally up and right, one step at a time.
I would code this as:
int newRow = row - 1;
int newCol = col + 1;
When an "up and to the right" move would leave the square, it is wrapped around to the last row or first column, respectively.
This is clearly:
if ( newRow < 0 ) {
newRow = num - 1;
}
if ( newCol > num - 1 ) {
newCol = 0;
}
If a filled square is encountered, one moves vertically down one square instead, then continues as before.
if (magic[newRow][newCol] != 0) {
newRow = row + 1;
newCol = col;
}
I know this doesn't actually solve your problem but I hope it gets you somewhere towards your goal. See how I take the words of the algorithm and match them as accurately as possible with code.