类的简单Java程序

时间:2014-08-27 06:30:39

标签: java

我想知道如何处理在我的程序中输入1个妻子,1个麻袋等的用户。为了获得生物量,我将它们相乘,但它不能解释用户输入“1”的事实,因为它只是乘以。如果用户为任何值输入“1”,则答案将不正确。

import java.util.Scanner;

public class Program2 {
public static void main(String[] args){
    Scanner keyboard = new Scanner(System.in);

    int wives;
    int sacks;
    int cats;
    int kits;

    System.out.println("St. Ives Program. Press 'Enter' to continue.");  
    try{
        System.in.read();
    } catch(Exception e){}  

    System.out.println("How many wives does the man have?");
    wives = keyboard.nextInt();

    System.out.println("How many sacks per wife?");
    sacks = keyboard.nextInt();

    System.out.println("How many cats per sack?");
    cats = keyboard.nextInt();

    System.out.println("How many kits per cat?");
    kits = keyboard.nextInt();

    System.out.println("As I was going to St. Ives,");

    //This makes it so if a user inputs "1", the correct usage of the word is displayed
    if (wives == 1){
        System.out.println("I met a man with " + wives + " wife,");
    }else{
        System.out.println("I met a man with " + wives + " wives,");
    }

    if (sacks == 1){
        System.out.println("Every wife had " + sacks + " sack,");
    }else{
        System.out.println("Every wife had " + sacks + " sacks,");
    }

    if (cats == 1){
        System.out.println("Every sack had " + cats + " cat,");
    }else{
        System.out.println("Every sack had " + cats + " cats,");
    }

    if (kits == 1){
        System.out.println("Every cat had " + kits + " kit,");
    }else{
        System.out.println("Every cat had " + kits + " kits,");
    }   

    System.out.println("Kits, cats, sacks, and wives,");
    System.out.printf("%d living things were going to St. Ives. %n", (wives * sacks * cats * kits));
    //el fin
    }
}

3 个答案:

答案 0 :(得分:0)

因为你必须添加妻子,猫,它基本上

1 + wives + (wives * sacks * cats) + (wives * sacks * cats * kits)

1 + (wives * (1 + (sacks * cats * (1 + kits)))

1 +代表该男子)

答案 1 :(得分:0)

生活事物=男人数+妻子数+猫数+套数

Number of Men = 1
Number of Wives = (Number  of Wives) * (Number of Men) = (Number  of Wives)
Number of Cats = (Number  of Wives) * (Number  of Sacks for each wife) * (Number of Cats in each Sack)
Number of Kits = Number of Cats * (Number of Kits per Cat)

答案 2 :(得分:0)

如果您更喜欢简洁

   //This makes it so if a user inputs "1", the correct usage of the word is displayed
   System.out.println("I met a man with " + wives + (wives==1?" wife,":" wives,"));

你的公式错了,你只显示了套件的数量,
你需要增加猫的数量和妻子的数量。

该男子是否也去圣艾夫斯?