Hello I am trying to scan the numbers 1-113 and do the following
I. If the number is odd, print “x is odd”
II. If the number is divisible by 5, print “hi five”
III. If the total of a number (x) and its subsequent number (x+1) is a value divisible by 7, print “wow”
IV. If the number is prime, print “prime”.
else just print number
Each of these statements are supposed to be separated by commas. The functions must remain as they are to match the provided API and the problem right now is that my current code is displaying all on separate lines
1 is odd,
Prime
2,
3 is odd,
Prime
wow
when it should display like this
1 is odd, Prime,
2,
3 is odd, Prime, wow
I would appreciate any advice on how to proceed thank you.
import java.util.ArrayList;
public class Number
{
//check if by number is prime
public static boolean isPrime(int n){
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
//check if number is odd
public static boolean isOdd(int n){
if(n % 2 == 0){
return false;
}
return true;
}
//checks if number is divisible by 5
public static boolean isDivisibleBy5(int n){
if(n % 5 == 0){
return true;
}
return false;
}
//checks if number is divisible by 7
public static boolean isDivisibleBy7(int n){
if(n % 7 == 0){
return true;
}
return false;
}
//Each number from 1 to 113 is checked and if
public static ArrayList<String> iterate(){
//initialize arraylist of strings
ArrayList<String> al = new ArrayList<String>();
//for each number between 1 and 113 do the following
for(int i=1; i< 113; i++){
if (isOdd(i) == true){
al.add(i+" is odd, ");
}
else{
al.add(i+", ");
}
if (isDivisibleBy5(i) == true){
al.add(" high 5, ");
}
if(isPrime(i) == true){
al.add("Prime");
}
if(isDivisibleBy7(i+(i+1))==true ){
al.add("wow");
}
}
return al;
}
public static void main(String[] args) {
ArrayList<String> numbers;
numbers = iterate();
for(int i=0; i < numbers.size(); i++){
System.out.println(numbers.get(i));
}
}
}
So if you're trying to describe a number with multiple properties, you're not doing it correctly.
list.add(i+"something");
list.add("Prime");
creates
{"isomething", "Prime"}
when what you want it
{"isomething,Prime"}
but all you're doing is growing the list by 1 element every time you call .add
try changing to
for(int i=1; i< 113; i++){
String numberString = "" + i;
if (isOdd(i) == true){
numberString += ", is odd";
}
else{
numberString += ",";
}
if (isDivisibleBy5(i) == true){
numberString += ", is even"
}
if(isPrime(i) == true){
numberString += "Prime";
}
if(isDivisibleBy7(i+(i+1))==true ){
numberString += "wow";
}
al.add(numberString);
}