重复程序? [英] Repetition of the program?

查看:66
本文介绍了重复程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户输入y,我想循环执行程序以重复执行,但是如果用户最后输入n,则程序将停止

I want to loop my program to repeat if the user inputs y the program will repeat over and over again ,but if the user finally inputs n the program will stop

import java.util.Scanner;
public class ReverseIt {

public static void main(String[] args) {

    Scanner sc = new Scanner (System.in);

    String name;
    System.out.println("Input Name");
    name = sc.nextLine();

    StringBuilder rev = new StringBuilder(name);


    System.out.println("NAME: "+name+"\n");

    System.out.println("REVERSE:" +rev.reverse()+"\n");

    System.out.println("Would you like to do it again?(Y/N)\n");

    char repeat;

    repeat = sc.next().charAt(0);


    if(repeat == 'n'){
        System.out.println("Program  Stopped");
    }
        while(repeat == 'y'){
            System.out.println("Input Name");
            name = sc.nextLine();
            System.out.println("NAME: "+name+"\n");

            System.out.println("REVERSE:" +rev.reverse()+"\n");

            System.out.println("Would you like to do it again?(Y/N)\n");
        }

}

推荐答案

我将代码分成一个单独的函数,如果扫描程序返回"y",则调用该函数.例如:

I would separate the code into a separate function, and call that function if the scanner returns a "y". For example:

public static void main(String[] args) {
function();
}
public static void function(){
Scanner sc = new Scanner (System.in);

String name;
System.out.println("Input Name");
name = sc.nextLine();

StringBuilder rev = new StringBuilder(name);


System.out.println("NAME: "+name+"\n");

System.out.println("REVERSE:" +rev.reverse()+"\n");

System.out.println("Would you like to do it again?(Y/N)\n");

char repeat;

repeat = sc.next().charAt(0);


if(repeat == 'n'){
    System.out.println("Program  Stopped");
}
    if(repeat == 'y'){

function();

    }

}

希望有帮助

这篇关于重复程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆