J
J
Jonibek2015-08-20 15:01:54
Java
Jonibek, 2015-08-20 15:01:54

How to implement return to the beginning of a class in Java?

Friends, I recently started learning Java. Now I am writing a small program. Please tell me how to implement a return (transfer of control) to the beginning of the class in the program? For example, at the end of the program, it is asked if the user wants to start over, and when the appropriate character is entered, the program should start again, that is, start from the Main class. How can this be implemented? Thanks in advance to everyone for the replies.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evhen, 2015-08-20
@EugeneP2

How is it usually done

package ru.toster.java.q241826;

import java.util.Date;
import java.util.Scanner;

public class App {

  public static void main(String[] args) {

    Scanner scnr = new Scanner(System.in);

    while (true) {

      System.out.print("enter command>");
      String command = scnr.nextLine();

      if ("help".equals(command)) {
        printListCommand();
      } else if ("date".equals(command)) {
        printDate();
      } else if ("time".equals(command)) {
        printTime();
      } else if ("exit".equals(command)) {
        System.out.println("Good Bye!");
        break;
      } else {
        System.out.println("Unknown command! Please enter 'help'");
      }

    }		
    scnr.close();
  }
  
  private static void printTime() {
    System.out.printf("%1tT\n", new Date());		
  }

  private static void printDate() {
    System.out.printf("%1tY-%1$tm-%1$td\n", new Date());		
  }

  private static void printListCommand() {
    System.out.println(
        "'help'\tprint list commands;\n" + 
        "'exit'\texit from programm;\n" + 
        "'date'\tprint today's date;\n" + 
        "'time'\tprint current time;");
  }
}

M
Marina, 2015-08-20
@MJee

I would do like this:

class MyClass  {
  public static void main (String [] args) {
    start();
  }

  private void start() {
    // do something
    // ask user if he want to start again
    if (needStartAgain == true) {
      start();
    }
  }
}

O
Oleg Wock, 2015-08-20
@OlegWock

if you have everything in one method, then you can either throw it into an infinite loop or call the method recursively

// Variant 1
class Lol {
    public void main(String[] args) {
        while(true) {
            // prog code
           // ввод от пользователя. Если символ не тот -- break
        }
    }
}

// Variant 2
class Lol2 {
    public void main(String[] args) {
        // prog code
        // ввод от пользователя. Если символ тот -- this.main(args)
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question