java重新执行代码,如何在用户输入数据后重新运行java代码

Hey I have a basic java 'app' showing if people are an adult or teen etc.. I am starting out with java and I can't find how to make it so after a user has input an age, and the string of what they are classified as shows I would like it to re run the whole thing again so someone else can have a go. I have been looking into doing a loop but that hasn't worke dout for me.. Here is the code:

public static void main(String[] args)

{

//Declare local variables

int age;

Scanner in = new Scanner(System.in);

//Prompt user for Age

System.out.print("Enter Age: ");

age = in.nextInt();

if(age > 17)

{

System.out.println("This persons age indicates that they an adult");

}

else if (age > 12)

{

System.out.println("This persons age indicates that they are a teenager");

}

else if (age >= 0)

{

System.out.println("This persons age indicates that they are a child");

}

else

{

System.out.println("That age is invalid");

}

//Close input

in.close();

}

Any help would be greatly appreciated. I am sure it is super simple and I have missed something.

解决方案

You can put it in a loop such as

public static void main(String[] args)

{

//Declare local variables

int age;

Scanner in = new Scanner(System.in);

while(true){

//Prompt user for Age

System.out.print("Enter Age: ");

age = in.nextInt();

if(age > 17)

{

System.out.println("This persons age indicates that they an adult");

}

else if (age > 12)

{

System.out.println("This persons age indicates that they are a teenager");

}

else if (age >= 0)

{

System.out.println("This persons age indicates that they are a child");

}

else

{

System.out.println("That age is invalid");

}

}

//Close input

in.close(); //Note that this happens outside the loop

}

or put the needed code in a method

public static void ageCheck()

{

//code that is currently in main method

}

it would be called from the main method by

this.ageCheck();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
算法与数据结构涵盖了以下主要内容: 数据结构(Data Structures): 逻辑结构:描述数据元素之间的逻辑关系,如线性结构(如数组、链表)、树形结构(如二叉树、堆、B树)、图结构(有向图、无向图等)以及集合和队列等抽象数据类型。 存储结构(物理结构):描述数据在计算机中如何具体存储。例如,数组的连续存储,链表的动态分配节点,树和图的邻接矩阵或邻接表表示等。 基本操作:针对每种数据结构,定义了一系列基本的操作,包括但不限于插入、删除、查找、更新、遍历等,并分析这些操作的时间复杂度和空间复杂度。 算法: 算法设计:研究如何将解决问题的步骤形式化为一系列指令,使得计算机可以执行以求解问题。 算法特性:包括输入、输出、有穷性、确定性和可行性。即一个有效的算法必须能在有限步骤内结束,并且对于给定的输入产生唯一的确定输出。 算法分类:排序算法(如冒泡排序、快速排序、归并排序),查找算法(如顺序查找、二分查找、哈希查找),图论算法(如Dijkstra最短路径算法、Floyd-Warshall算法、Prim最小生成树算法),动态规划,贪心算法,回溯法,分支限界法等。 算法分析:通过数学方法分析算法的时间复杂度(运行时间随数据规模增长的速度)和空间复杂度(所需内存大小)来评估其效率。 学习算法与数据结构不仅有助于理解程序的内部工作原理,更能帮助开发人员编写出高效、稳定和易于维护的软件系统。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值