简体   繁体   中英

Java “while” - variable inside the loop

Sorry if this question was asked (probably many times), but I couldn't find an answer. I'm learning Java and I've made a simple code. It's asking for 2 numbers, comparing it and uses If to give some results. It's working good, but I try to loop it. gram is in loop while i give first number value as 10. This won't work like this, because "First cannot be resolved to a variable" because it's inside a loop. Ok I understand, but is there any way I can make this work with variable inside loop ?

import java.util.Scanner; 

public class Loop {

    public static void main(String[] args) {
        do {    
            System.out.println("give me 2 numbers: ");
            String FirstNum, SecNum;
            Scanner FirstRead = new Scanner(System.in);
            Scanner SecRead = new Scanner(System.in);
            FirstNum = FirstRead.nextLine();
            SecNum = SecRead.nextLine();
            int First = Integer.parseInt(FirstNum); // changing String to int
            int Second = Integer.parseInt(SecNum); // changing String to int

            // Playing with loop

            if (First == Second) {
                System.out.println("First " + First + " is same as "+ Second);
            }
            else {
                System.out.println("Number " + First + " is different then " + Second);
            }   
        }
        while(First == 10); 
        System.out.print("We're done here, because first number is 10");
    }
}

but is there any way I can make this work with variable inside loop?

No. You'll have to declare it outside the loop.

You can also declare a boolean variable and use it intead of First . Something like:

public static void main(String[] args) {
    boolean check = false;
    do {    
        [...]
        check = First == 10;
    }

    while(check); 

    System.out.print("We're done here, because first number is 10");
}

But as you can see, you need to declare it outside the loop.

As the others said, you have to declare the condirional variable outside of the loops scope. You can also apply some other improvements to your program:

public static void main(final String[] args) {
    // You need only one scanner for both numbers. I t can be reused, so
    // declare it outside the loop.
    final Scanner scanner = new Scanner(System.in);
    // Also the number variables can be reused.
    int first, second;

    do {
        System.out.println("Give me two numbers:");

        // Scan the integers directly without parsing the lines manually.
        first = scanner.nextInt();
        second = scanner.nextInt();

        if (first == second) {
            System.out.println("The first number (" + first + ") is the same as the second (" + second + ").");
        } else {
            System.out.println("The first number (" + first + ") is different from the second (" + second + ").");
        }
    } while (10 != first);

    scanner.close();

    System.out.println("We are done here, because the first number is 10.");
}

First of all, please use lowerCamelCase to name variables. The first letter always lowercase.

And no, you cannot declare a variable inside the loop and use it as the condition. When you use variables, you need to be aware of the scope where it was defined. If you define it inside the loop, it will only be available inside the loop. Therefore, the only thing you can do is define the variable outside the loop, and then use it inside the loop.

int first = 0;

do {
    ...
    first = Integer.parseInt(FirstNum); // changing String to int
    ...
} while (first == 10);

No you have to declare the variable outside of the loop

you can do this

public class Loop {
public static void main(String[] args) {
    int first = 0; //declare first outside of the loop
    do {    
        //...
        first = Integer.parseInt(FirstNum); // parse int to string
        //....
    }
    while(first == 10); 

    System.out.print("We're done here, because first number is 10");
}
}

You should declare first and your scanners outside the loop.

import java.util.Scanner; 

public class Loop {
    public static void main(String[] args) {
        int first = 0;
        final Scanner scanner = new Scanner(System.in);
        do {    
            System.out.println("Give me 2 numbers: ");
            final String firstNum = scanner.nextLine();
            final String secNum = scanner.nextLine();
            first = Integer.parseInt(firstNum); // changing String to int
            final int second = Integer.parseInt(secNum); // changing String to int

            if (first == second) {
                System.out.println("First " + first + " is same as "+ second);
            } else {
                System.out.println("Number " + first + " is different then " + second);
            }   
        // Playing with loop
        } while(first != 10); 

        System.out.print("We're done here, because first number is 10");

        // Free resources (should be done in a try/finally clause)
        scanner.close();
    }
}

Your while clause was wrong. If you loop while first == 10 , it means that your program will quit if "first" is different than 10.

Note: Declaring a variable inside ANY loop (for, while do-while) is very bad programming practice and should be avoided.

But For your question: but is there any way I can make this work with variable inside loop?

You can use break statement as below if it suits what you want.

public static void main(String[] args) {
 do {    
      int First = Integer.parseInt(FirstNum); // changing String to int

      if (First == 10)
      {  break; }

   } while (true)
   System.out.print("We're done here, because first number is 10");

Better to use a while loop as below:

   while (true)
   {    
      int First = Integer.parseInt(FirstNum); // changing String to int

      if (First == 10)
      {  break; }

   } 
   System.out.print("We're done here, because first number is 10");

Reference: Break DO While Loop Java?

Work around will do it, not recommended. As you posted but is there any way I can make this work with variable inside loop ?

import java.util.Scanner;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner sc = new Scanner(System.in);
        do {
            System.out.println("Enter first no. ");
            int first = sc.nextInt();
            System.out.println("Enter second no. ");
            int second = sc.nextInt();
            if(first == second) {
                System.out.printf("First and second both are equal i.e: %d\n", first);
            } else {
                System.out.printf("First: %d and second: %d both are different\n", first, second);
            }
            if(10 == first) {
                break;
            }
        } while(true);
        System.out.println("Done, since value of first is 10");
    }
}

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