Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print every other number?

Tags:

java

I am new to java, just started learning the basics concepts of it, I am now trying to develop a program where users enter two numbers and the program prints every other number between these two numbers, I have tried several methods but I just can grasp how to do it, I know this might seem really easy, but I have been spending the past two days trying to figure it out with no luck at all. I would really appreciate any help. I manage to write the code enabling the inputs of values but after that, it is just blank, and I am not able to proceed:/

This is how far I came with my code which is probably way off.

public class EveryOther {
  public static void main(String[] args) {

    int FirstNumber = 0;
    int SecondNumber = 0;

    Scanner scanner = new Scanner(System.in);
    System.out.print("FirstNumber: " );
    scanner.nextInt();

    Scanner scanner2 = new Scanner(System.in);
    System.out.print("Second Number: ");
    scanner.nextInt(); {

        while (FirstNumber <= SecondNumber + 2);
        System.out.println(SecondNumber * FirstNumber +2);
        SecondNumber++;

    }
}
like image 618
GTech7 Avatar asked Mar 04 '23 02:03

GTech7


2 Answers

  1. FirstNumber and SecondNumber are assigned to 0, but we actually want to get it assigned from Scanner. here are some useful examples. https://www.w3schools.com/java/java_user_input.asp

  2. the while loop does nothing because the conditional code is an empty statement. the link might be very helpful. https://www.tutorialspoint.com/java/java_while_loop.htm

    import java.util.Scanner;
    
    public class EveryOther {
    
        public static void main(String[] args) {
    
            int FirstNumber = 0;
            int SecondNumber = 0;
    
            Scanner scanner = new Scanner(System.in);
            System.out.print("FirstNumber: " );
            FirstNumber = scanner.nextInt();
    
            System.out.print("Second Number: ");
            SecondNumber = scanner.nextInt();
    
            while (FirstNumber < SecondNumber){
                System.out.println(FirstNumber);
                FirstNumber = FirstNumber + 2;
            }
        }
    

    }

like image 178
Leogao Avatar answered Mar 08 '23 12:03

Leogao


So suppose you have your firstNumber = 5 and secondNumber = 10 then every other number starting from firstNumber in this case will be 5,7,9 that means you just have to increase firstNumber's value by 2 in every iteration of loop. It can be done as follows:

while (firstNumber < secondNumber ){
        System.out.println(firstNumber );
        firstNumber = firstNumber + 2;
}

Hope it helps you understand.

like image 33
Himanshu Singh Avatar answered Mar 08 '23 14:03

Himanshu Singh