我在为旧程序添加for循环时遇到问题。我必须这样做,最后用户可以选择再次提问。这就是我到目前为止所拥有的 如果问题是愚蠢的话,也开始学习循环对不起
答案 0 :(得分:1)
你的问题不是愚蠢的,我想你在这里有错误的想法。
无论如何,这里是你的代码,可编辑和可复制的
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个括号符号。
现在,关于你的实际问题,一个让所有这一切成为可能的简单方法就是抛出那个你希望程序重复的东西(和我添加的方法以确保它的数字) ),这就是我的意思。
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;
}
}
}
}