我在向旧程序中添加 for 循环时遇到问题。我必须做到这一点,以便最终用户可以选择再次提出问题。这就是我到目前为止所拥有的 也刚刚开始学习 for 循环,如果问题很愚蠢,抱歉
最佳答案
你的问题并不愚蠢,我认为你只是有错误的想法。
无论如何,这是您的代码,可编辑且可复制
import java.util.Scanner;
public class DogYears
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter your dog's age in human years: ");
int age = scan.nextInt();
int dogAge = age * 7;
System.out.println("Your dog is " + age + " in human years and " + dogAge
+ " in dog years!");
// scan.close(); <--- don't close it, you want to be able to do it again, right??
if(dogAge>=150)
{
System.out.println("Likely story");
}
else if(dogAge>=80 && dogAge<150)
{
System.out.println("Hello grand-dog");
}
else if(dogAge>=40 && dogAge<80)
{
System.out.println("Boring!");
}
else if(dogAge>=20 && dogAge<40)
{
System.out.println("Get a job!");
}
else if(dogAge<20)
{
System.out.println("Just a pup!");
}
}
}
/*
this is the code you had trouble including
for(int age = scan.nextInt(); int dogAge = age * 7; i++);
{
System.out.print("Enter your dog's age in human years: ");
}
*/
无论如何,这就是你的代码。您所需要做的就是复制粘贴,然后突出显示所有代码,然后按文本字段上方小框中的 2 个括号符号。
现在,对于您的实际问题,使这一切成为可能的一个简单方法是,将 for 循环围绕您希望程序重复的所有内容(以及我添加的方法以确保它是数字的),这里是我的意思是。
import java.util.Scanner;
public class DogYears
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter your dog's age in human years. ");
int age = scan.nextInt();
for(int i = 0; i < 10000; i++)
{
int dogAge = age * 7;
System.out.println("Your dog is " + age + " in human years and " + dogAge
+ " in dog years!");
// scan.close(); <--- don't close it, you want to be able to do it again, right??
if(dogAge>=150)
{
System.out.println("Likely story");
}
else if(dogAge>=80 && dogAge<150)
{
System.out.println("Hello grand-dog");
}
else if(dogAge>=40 && dogAge<80)
{
System.out.println("Boring!");
}
else if(dogAge>=20 && dogAge<40)
{
System.out.println("Get a job!");
}
else if(dogAge<20)
{
System.out.println("Just a pup!");
}
System.out.print("Enter your dog's age in human years. (Enter a negative number to stop the program)\n");
String response = scan.next();
age = Integer.parseInt(response);
if(age < 0)
{
i = 10001;
}
}
}
}
关于java - 在程序中添加 for 循环时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26051236/