在while循环中调用方法

时间:2016-05-17 02:44:29

标签: java

package com.Bruno;

import java.util.Scanner;
public class Main {


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

        System.out.print("How Many:");
        int numberOne = Integer.parseInt(reader.nextLine());




        while ((numberOne >=0) && (numberOne <=7)) {
            System.out.print(printText() + "\n" );
            numberOne--;
       }

    public static void printText() {
        System.out.println("In the beginning there were the swamp, the hoe and Java." + "/n");
    }



    }
}

1 个答案:

答案 0 :(得分:1)

  1. 您尝试将printText()方法称为嵌套,这是不允许的。
  2. 即使你将printText()从main中取出,它也会出错,因为类型不匹配。 printText()打印到输出流并且不返回任何内容。它不能直接在另一个方法中使用,因为它什么都不返回。
  3. 使用可以输入到其他方法的返回类型的方法来解决问题
  4. 代码:

    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) {
            Scanner reader = new Scanner(System.in);
    
            System.out.print("How Many:");
            int numberOne = Integer.parseInt(reader.nextLine());
    
            while ((numberOne >= 0) && (numberOne <= 7)) {
                System.out.print("" + printText() + "\n");
                numberOne--;
            }
    
        }
    
        public static String printText() {
            return "In the beginning there were the swamp, the hoe and Java." + "/n";
        }
    }