-2

I executed the below code in Eclipse, but the GOTO statements in it are not effective. How do I use it?

How do I rewrite the above code using the Break and Continue statements without using the goto statement?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 */

/**
 * @author Home
 *
 */
public class student
{
    /**
    * @param args
    */
    String average(float sub1,float sub2,float sub3)
    {
        float average = (sub1+sub2+sub3)/3;
        if( average > 50)
            return "PASS";
        else
            return "FAIL";
    }

    String addName(String name)
    {
        return name;
    }

    public static void main(String[] args) throws NumberFormatException, IOException
    {
        // TODO Auto-generated method stub
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        student stu = new student();
        int loop_option = 0;
        do
        {
            System.out.println("--------------STUDENT DETAILS---------------");
            System.out.println("Choose the operation from the following options.");
            System.out.println(" 1.ADDNAME");
            System.out.println(" 2.AVERAGE_RESULT");
            System.out.println(" 3.EXIT");
            System.out.println("CHOOSE THE OPERATION U WANT:");

            int option = Integer.parseInt(br.readLine());
            switch(option)
            {
                case 1:
                    System.out.println("Enter the name");
                    String name = br.readLine();
                    System.out.println("The Inserted student name is " +stu.addName(name));
                break;

                case 2:
                    outsideloops:
                    System.out.println("Enter the marks (in 100):");
                    System.out.println("Subject 1:");
                    float sub1 = Float.parseFloat(br.readLine());
                    if (sub1 >= 101)
                        goto outsideloops;
                    System.out.println("Subject 2:");
                    float sub2=Float.parseFloat(br.readLine());
                    System.out.println("Subject 3:");
                    float sub3=Float.parseFloat(br.readLine());
                    System.out.println("The Student is "+stu.average(sub1,sub2,sub3)+ "in the examinations");
                    break;

                case 3:
                    System.exit(0);

                default:
                    System.out.println("Please choose the valid option");
                    //break;
            }
            System.out.println("if U want 2 use further press 1 to continue...");
           loop_option=Integer.parseInt(br.readLine());
        }
        while (loop_option == 1);
        System.out.println("The STUDENT program is terminating now.");
    }
}

By the following code as suggested by one of the Stack Overflow members made me to write the following code:BUT that is also wrong.. I am thinking why the deleted the GOTO statements in Java?

This is not working either.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    String average(float sub1,float sub2,float sub3)
    {
        float average=(sub1+sub2+sub3)/3;
        if( average>50)
            return "PASS";
        else
            return "FAIL";
    }

    String addName(String name)
    {
        return name;
    }

    public static void main(String[] args) throws NumberFormatException, IOException {
        // TODO Auto-generated method stub
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Main stu = new Main();

        float sub1 = 0;
        int goThere = 0;

        do {
            switch(goThere){
                case -1:
                    System.out.println("if U want 2 use further press 0 to continue...");
                    goThere = Integer.parseInt(br.readLine());
                    continue;

                case 0:
                    System.out.println("--------------STUDENT DETAILS---------------");
                    System.out.println("Choose the operation from the following options.");
                    System.out.println(" 1.ADDNAME");
                    System.out.println(" 2.AVERAGE_RESULT");
                    System.out.println(" 3.EXIT");
                    System.out.println("CHOOSE THE OPERATION U WANT:");

                    goThere = Integer.parseInt( br.readLine() );
                    continue;

                case 1:
                    System.out.println("Enter the name");
                    String name = br.readLine();
                    System.out.println("The Inserted student name is " + stu.addName(name));
                    goThere = -1;
                    continue;

                case 2:
                    System.out.println("Enter the marks (in 100):");
                    System.out.println("Subject 1:");
                    sub1 = Float.parseFloat(br.readLine());
                    goThere = 4;
                    continue;

                case 4:
                    {
                        if( sub1 >= 101)
                        {
                            goThere = 2;
                        }
                        else {goThere = 3;}
                    }
                    continue;

                case 3:
                    System.out.println("Subject 2:");
                    float sub2=Float.parseFloat(br.readLine());
                    goThere =5;
                    continue;

                case 5:
                    {
                        if( sub2 >= 101)
                        {
                            goThere = 3;
                        }
                        else {
                            goThere = 6;
                        }
                    }
                    continue;

                case 6:
                    System.out.println("Subject 3:");
                    float sub3 = Float.parseFloat(br.readLine());
                    goThere = 7;
                    continue;

                case 7:
                    {
                        if( sub3 >= 101)
                        {
                            goThere = 6;
                        }

                    }
                    continue;

                    System.out .println("The Student is " + stu.average(sub1,sub2,sub3) + "in the examinations");
                    goThere = -1;
                    continue;
            }
            break;
        } while(true);
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dinesh Kumar
  • 1,469
  • 4
  • 27
  • 46

7 Answers7

21

There is no goto in Java as of yet. It's a reserved word, in case there ends up being the need for it, but as far as I know, they haven't used it yet.

Probable equivalent code:

case 2:
    float sub1 = 0.0;
    do {
        System.out.println("Enter the marks (in 100):");
        System.out.println("Subject 1:");
        sub1 = Float.parseFloat(br.readLne());
    } while (sub1 >= 101);

    ... rest of the code ...

Note, this code would be equivalent for this particular situation. There's no universal replacement for goto; if there were, they'd just call it goto and be done with it. Each case will be different, and the replacement will depend entirely on how the goto would have been used.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
cHao
  • 84,970
  • 20
  • 145
  • 172
  • I think I read somewhere that they did this to prevent programmers from naming a variable `goto`. – Goran Jovic Dec 28 '10 at 16:53
  • 1
    That's pretty much the point of it, yes. If they let people name something `goto`, they'd have to call their statement something else if they ever implemented it. – cHao Dec 28 '10 at 16:58
  • 1
    I wouldn't be surprised if they did this to prevent programmers from using goto statements at all. If you need to use a goto, you're doing it wrong. – rownage Dec 28 '10 at 16:59
  • is there any equivalent way , that can be used instead of GOTO statement in my java program to implement its concept – Dinesh Kumar Dec 28 '10 at 17:01
  • 2
    @rownage: There are very occasional good uses for a `goto`, although I can't remember the last time I wrote one personally. Making one's own loop structure when there's a perfectly good one in the language is not a good use. – David Thornley Dec 28 '10 at 17:03
  • `goto` (together with `if`) could be used to emulate any control structure existing in the language. Which one to use in its place depends on how you wanted to use it. See my edited post for more-or-less equivalent code for this particular case. – cHao Dec 28 '10 at 17:04
  • I can't think of one reason in Java that you'd use `goto`. Maybe in C for error handling, but that's why you have exceptions in Java. – rownage Dec 28 '10 at 17:15
  • The #1 reason i can think of for *not* using `goto` in Java, is that *it doesn't exist*. :) Which seems to work OK; `break`, `continue`, exceptions, and loop labels allow for most of the cases that would require a `goto` (or logical contortions) in other languages – cHao Dec 28 '10 at 17:17
  • how to rewrite the above code using the Break and Continue statements ?? Plz help me – Dinesh Kumar Dec 28 '10 at 17:51
  • The above code does not need `break` or `continue`. The `do`...`while` loop does the same thing as the label...`if`...`goto`, and is probably the best way to do that. `break` and `continue` should not be added for their own sake; they should only be added if they add readability, which is not the case here. If you insist, you could say `while (true) { /* ...print prompt, read in sub1... */ if (sub1 < 101) break; }`. But that's ugly, and unnecessary -- you have a loop that's made for the job, so that's what you should use. – cHao Dec 28 '10 at 21:31
  • @cHao: If you're handling your loop correctly, it's not ugly and necessary. In your code, can go just one line. Aboved code, required three cheking of marks. Using three loop (do..while) is make sense or is not ugly? – miqbal Dec 29 '10 at 04:43
  • @moses: The three do/while loops (assuming there will be one for each mark) could easily be replaced with one `for` loop that gets three numbers into an array, and the one do/while nested within. That it's three separate groups of prompt/input is what causes the ugliness you seem to be referring to, but that's another issue. *There is no need for `goto` here*, or `break`, or `continue`, or loop labels, or misusing `switch` as a jump table, or anything even remotely tricky. Simple, straightforward loops are prettier than 'clever' tricks. – cHao Dec 29 '10 at 05:08
  • @cHao: Which isn't simple isn't ugly. moses – miqbal Dec 29 '10 at 05:18
  • @moses: That which *by necessity* isn't simple isn't *necessarily* ugly. But unnecessary complexity *is*. – cHao Dec 29 '10 at 09:31
  • 1
    @djaqeel: As Far As I Know. (editing it now...) – cHao Nov 13 '11 at 12:29
6

You don't have to use goto (already there isn't) Ok. Let's think for this problem. I think this is may be useful

public class Goto
{

    public static void main(String[] args)
    {
        int goThere = 0;

        do
        {
            switch(goThere)
            {
                case 0:
                case 1:
                    System.out.println("Foo");
                    goThere = 3;
                    continue;

                case 2:
                    System.out.println("Baz");
                    goThere = -1;
                    continue;
                case 3:
                    System.out.println("Bar");
                    goThere = 2;
                    continue;
             }
        } while(false);
    }
}

Try this. And may be you can extend that code.

miqbal
  • 2,213
  • 3
  • 27
  • 35
  • Every time I write this in C/C++ I have to go change it to real goto statements to be maintainable. Some people believe this kind of thing doesn't normally happen. It does say every 200,000 lines so not being afraid of goto is a good thing. – Joshua Dec 28 '10 at 17:06
  • Define all of case in same switch statment. Printing "Enter this", "Type this" lines put other new cases. Etc. case 0: System.out.println("Enter the name"); String name=br.readLine(); goThere = x; // number of proccessor case – miqbal Dec 28 '10 at 17:22
  • how to rewrite the above code using the Break and Continue statements ?? Plz help me – Dinesh Kumar Dec 28 '10 at 17:54
5

According to this:

In Java, goto is a reserved word, but is unusable.

David Weiser
  • 5,190
  • 4
  • 28
  • 35
5

As others pointed, there is no goto statement in Java. I want to add that labels are a slight alternative.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
5

Jumping forward

label: if (true) {
    // Do stuff
    if (check)
        break label;
    // Do more stuff
}

Jumping backward

label: do {
    // Do stuff
    if (check)
        continue label;
    // Do more stuff
    break;
} while(true);

It is not to be used in any sensible piece of software ;-)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
  • You will need a `while(true)` there (and a `break` at the end of the loop), not `while(false)`, otherwise this is also a simple forward jump. – Paŭlo Ebermann Jun 16 '11 at 14:33
2

While goto is a reserved keyword in Java, there is no goto statement.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Joshua
  • 40,822
  • 8
  • 72
  • 132
1

Rewrite for your code is here,

Put your "Student" class in the same package then Main.java;

package MyPackage

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws NumberFormatException, IOException {
        // TODO Auto-generated method stub
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Student stu = new Student();

        float sub1 = 0;
        int goThere = 0;

        do {
            switch(goThere){
                case -1:
                    System.out.println("if U want 2 use further press 0 to continue...");
                    goThere = Integer.parseInt(br.readLine());
                continue;

                case 0:
                    System.out.println("--------------STUDENT DETAILS---------------");
                    System.out.println("Choose the operation from the following options.");
                    System.out.println(" 1.ADDNAME");
                    System.out.println(" 2.AVERAGE_RESULT");
                    System.out.println(" 3.EXIT");
                    System.out.println("CHOOSE THE OPERATION U WANT:");

                    goThere = Integer.parseInt( br.readLine() );
                continue;

                case 1:
                    System.out.println("Enter the name");
                    String name = br.readLine();
                    System.out.println("The Inserted student name is " + stu.addName(name));
                    goThere = -1;
                continue;

                case 2:
                    System.out.println("Enter the marks (in 100):");
                    System.out.println("Subject 1:");
                    sub1 = Float.parseFloat(br.readLine());
                    goThere = 4;
                continue;

                case 4:
                    if( sub1 >= 101){
                        goThere = 2;
                        continue;
                    }

                    System.out.println("Subject 2:");
                    float sub2=Float.parseFloat(br.readLine());
                    System.out.println("Subject 3:");
                    float sub3=Float.parseFloat(br.readLine());
                    System.out.println("The Student is " + stu.average(sub1,sub2,sub3) + "in the examinations");
                    goThere = -1;
                continue;
             }
            break;
        } while(true);
    }
}
miqbal
  • 2,213
  • 3
  • 27
  • 35