Something to get me started?
How would I do something like this:
Write a java program with a class called evenAndOdds. Your program should take input from the user whether the program should print even or odd numbers. If the user inputs even your program should use a loop to print out all even numbers in the range 1-50 in ascending order then use another loop to print out the even numbers from 50-100 in descending order. If the user enters odd, your program should do the same thing except print out the odd numbers instead.
I'd prefer if I was given a little something to get started, but not necessarily the complete answer.
Re: Something to get me started?
Sounds like a homework assignment...
Break it down into smaller components first. First write a program that displays all odds, or all evens. (Hint, a number is even if it is divisible by 2, which can be determined using the % operator.)
When you have that part down, expand it to prompt the user first, and based on what they input, call either the even method or the odd method. Or better yet, write one method that takes a boolean parameter and displays either evens or odds, and you would determine what boolean you pass it based on user input.
Re: Something to get me started?
This is what I have managed to come up with, but I am getting some errors and not really sure how to properly fix them
import java.util.Scanner;
public class evenAndOdds
{
public static void main(String[] args)
{
System.outprintln("Enter even or odd");
Scanner scannerObject = new Scanner(System.in);
String s1;
s1 = scannerObject.nextLine( );
if (s1==even);
{
for (int i = 0; i <=50; i + 2)
System.out.println(i);
for (int j = 50; j <=100; j - 2)
System.out.println(j);
}
else if (s1==odd);
{ for (int r = 1; r <=50; r + 2)
System.out.println(r);
for (int t = 1; t <=100; t - 2)
System.out.println(t);
}
else
System.out.println("you did not enter even or odd for the query");
}
}
I'm getting errors saying that r + 2, t - 2, etc, are not statements. What's the proper way to subract or add 2? I know -- or ++ adds by 1.
Re: Something to get me started?
The problem when learning about for loops is that n00bs are given the example of i++ eg for(int i = 0; i < 10; i++) and they think that i++ is the only thing you can place there. In reality you can use just about any legal statement.
Code:
int num = 10;
.......
System.out.println(num);
What line of code can you replace the dots with so the output is 8? Once you have done that you have answered your own question.