MickeyMoise
MickeyMoise

Reputation: 259

How to get the previous number in a while loop and double it? Java

I am making a program that has to read an integer, and then read other integers until it finds one that's the same as the first one. It then has to output the doubled value of the previous one, and i cant seem to find a way to get the previous value.

enter code here

    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();

    while(n!=0){
        int n2 = scan.nextInt();
        if(n2==n){
            System.out.println(n2);
            break;
        }
    }

Upvotes: 2

Views: 2153

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79155

You need to store the previous number to a variable (e.g. the variable, previous in the following code) before you ask for the next input.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = scan.nextInt();
        System.out.println("Enter more numbers (the first number to stop): ");
        int previous = n;
        int next;
        while (true) {
            next = scan.nextInt();
            if (next == n) {
                System.out.println(2 * previous);
                break;
            }
            previous = next;
        }
    }
}

A sample run:

Enter a number: 5
Enter more numbers (the first number to stop): 
10
15
20
25
5
50

Upvotes: 2

lettomobile
lettomobile

Reputation: 316

Try this:

Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int previousValue = n;

while (n != 0) {
    int n2 = scan.nextInt();
    if (n2 == n) {
        break;
    }
    else
        previousValue = n2;
}
System.out.println(previousValue*2);

Upvotes: 0

Related Questions