0

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");
    }
}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
RichardK
  • 3,228
  • 5
  • 32
  • 52
  • 1
    _but is there any way I can make this work with variable inside loop?_ No. You'll have to declare it outside the loop. – BackSlash Jul 30 '14 at 08:26
  • 4
    you also do not need two scanners – Scary Wombat Jul 30 '14 at 08:27
  • 2
    You can declare “First" outside the loop and still use it inside it. And by the way, you should use camel case to name your variables. – Raphaël Jul 30 '14 at 08:27
  • Thank you. Is there any other function, which could use declaration from inside of the loop ? – RichardK Jul 30 '14 at 08:27
  • 4
    @Raphaël it's actually `camelBack` for variables. `CamelCase` is for classes etc. – Mena Jul 30 '14 at 08:28
  • @user2966603 - No, there is no such function. You will have to declare the variable outside the loop. – TheLostMind Jul 30 '14 at 08:28
  • 1
    @Mena Either way, variables shouldn't start with upper case characters. (although +1 for pedantics) – Holloway Jul 30 '14 at 08:28
  • 1
    `public class HelloWorld { private int thisIsAnInteger; public static void thisIsAFunction(String thisIsAParam) {...}...}` – EpicPandaForce Jul 30 '14 at 08:29
  • As you are learning Java, you should learn about proper indentation and naming conventions. Especially variable names, which should be as per http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html. Otherwise, long time java programmers will have trouble making the distinction between class names and variables in the code. – SirDarius Jul 30 '14 at 08:35

7 Answers7

2

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.

BackSlash
  • 21,927
  • 22
  • 96
  • 136
2

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.");
}
stevecross
  • 5,588
  • 7
  • 47
  • 85
1

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);
Balduz
  • 3,560
  • 19
  • 35
0

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");
}
}
user3840692
  • 273
  • 2
  • 13
0

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.

Raphaël
  • 3,646
  • 27
  • 28
0

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?

Community
  • 1
  • 1
ngrashia
  • 9,869
  • 5
  • 43
  • 58
  • Thank you so much for your help! I've started to learn Java on monday. I hope I'm making progress :) Now I will read it all like 30 times to learn. Thanks again :) – RichardK Jul 30 '14 at 08:57
0

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