• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

如何在一个方法上使用控制语句?如果可能的话

java 来源:Ahmed Abdullahi 5次浏览

我不知道怎么说如何在一个方法上使用控制语句?如果可能的话

if money(); < 1000 and house();是==小打印你的可怜

if money(); > = 1000和< 5000和house();是==为正常打印你好,你太富有

package ArrayTest; 

import java.util.Scanner; 

/** 
* Created by quwi on 02/12/2017. 
*/`enter code here` 
public class Happyness { 
    private static Scanner scanner = new Scanner(System.in); 


    public static void main(String[] args) { 
//  house(); 
//  money(); 
     comparison(); 


    } 

    private static void house() { 


     //  getting user input and using the switch statement to see the size 
     //  of their house 

     System.out.println("Please enter the size of your house "); 
     String cap = scanner.next(); 

     switch (cap) { 
      case "small": 
       System.out.println("you have a small house it means your poor"); 
       break; 
      case "normal": 
       System.out.println("your house normal, it mean your not poor nor rich"); 
       break; 
      case "large": 
       System.out.println("your house is big it means your rich"); 
       break; 
      default: 
       System.out.println("please choose between: small, normal or large"); 
       break; 
     } 
    } 


    private static void money() { 

     System.out.println("please enter a number"); 
     int wage = scanner.nextInt(); 
     if (wage < 1000) { 
      System.out.println("your poor"); 
     } else if (wage >= 1000 && wage < 5000) { 
      System.out.println("your not poor, your OK"); 
     } else if (wage > 5000) { 
      System.out.println("your rich, Give me money"); 
     } else { 
      System.out.println("please enter a number nothing else"); 
     } 
    } 

    private static void comparison() { 


     System.out.println("please enter a number"); 
     int decision = scanner.nextInt(); 

     switch (decision) { 
      case 1: 
       money(); 
       break; 
      case 2: 
       house(); 
       break; 
      case 3: 
       money(); 
       house(); 
       break; 

      default: 
       System.out.println("Please choose 1, 2 or 3"); 
     } 
    } 

} 


===========解决方案如下:

使用从两者的返回值进行比较。

private static String money() { 

    System.out.println("please enter a number"); 
    int wage = scanner.nextInt(); 
    if (wage < 1000) { 
     return "poor"; 
    } else if (wage >= 1000 && wage < 5000) { 
     return "ok"; 
    } else if (wage > 5000) { 
     return "rich"; 
    } else { 
     //ask for input again or exit, whatever 
    } 
} 

house()做同样的事情。然后,比较两种方法的返回值。


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)