简体   繁体   中英

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;
        }
    }

You need to store the previous number to a variable (eg 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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM