write a java program for the following question: Write a method printSquares tha
ID: 3591263 • Letter: W
Question
write a java program for the following question:
Write a method printSquares that has an integer parameter n, and prints the squares of the integers from 1 to n, separated by commas. It should print the squares of the odd integers in descending order first and then following with the squares of the even integers in ascending order. It does not print a newline character. It should throw an IllegalArgumntException if the specified integer is less than 1. For example, printsquares (4) should print 9, 1, 4, 16 printSquares (1) should print 1 printsquares (7) should print 49, 25, 9, 1, 4, 16, 36Explanation / Answer
Please check the below code. Please give command line argument for max number.
Squares.java
package com.maths;
public class Squares {
public static void printsquares(int maxnum){
int len=0;
if(maxnum%2==0){
len = maxnum/2;
}else{
len = maxnum/2+1;
}
int[] evenNum = new int[len];
int[] oddNum = new int[len];
int evencount=0;
int oddCount=0;
for(int i=1;i<=maxnum;i++){
if(i%2==0){
evenNum[evencount]=i;
evencount++;
}else{
oddNum[oddCount]=i;
oddCount++;
}
}
String printText="";
for(int j=oddCount-1;j>=0;j--){
oddNum[j] = oddNum[j]*oddNum[j];
if(printText.isEmpty()){
printText = String.valueOf(oddNum[j]);
}else{
printText += ", " +String.valueOf(oddNum[j]);
}
}
for(int m=0;m<evencount;m++){
evenNum[m] = evenNum[m]*evenNum[m];
if(printText.isEmpty()){
printText = String.valueOf(evenNum[m]);
}else{
printText += ", " +String.valueOf(evenNum[m]);
}
}
System.out.println("printsquares("+maxnum+") is "+printText);
}
public static void main(String args[]){
int maxnum = Integer.parseInt(args[0]);
if(maxnum<1){
throw new IllegalArgumentException("Illegal Argusment passed");
}
printsquares(maxnum);
}
}
Thank you. All the best.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.