【问题标题】:I must process the sentence by calling the method rather than processing the string directly in my main method! PS i need to use void method我必须通过调用方法来处理句子,而不是直接在我的 main 方法中处理字符串! PS我需要使用void方法
【发布时间】:2021-04-14 21:00:54
【问题描述】:
import java.util.Scanner;
public class PrintVertical
{

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter a sentence: ");
        String input = in.nextLine();

        int i =0;
        System.out.println("Your sentence printed vertically is:");
        for(i = 0; i < input.length(); i++) {
            char letter = input.charAt(i);
 
            System.out.println(letter);
        }
    }
}

【问题讨论】:

  • 不要把问题放在标题里,把它写在你的问题里,在标题里放一个简洁的问题,用几句话来表达。
  • 试试Stream.of(input.toCharArray()).forEach(System.out::println);
  • 非常感谢您的回复,我对我的错误感到抱歉,我也是新手。真的很抱歉,非常感谢你

标签: java methods void


【解决方案1】:

解决方案

  • 在类的主方法之外编写一个新方法,并用关键字static标记它。(类方法)
  • 给它一个字符串作为参数。使用您的用户输入调用它。

静态函数:

  public static void doVertic(String inp){   
    int i =0;
    System.out.println("Your sentence printed vertically is:");
    for(i = 0; i < input.length(); i++) {
        char letter = input.charAt(i);

        System.out.println(letter);
    }
}
  • 然后在 ma​​in 方法中使用扫描的输入调用它

在主方法中调用:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Please enter a sentence: ");
    String input = in.nextLine();
    <Classname>.doVertic(input);
}

注意: 必须是您的 Classname

【讨论】:

    猜你喜欢
    • 2016-11-21
    • 2020-02-29
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 2012-10-08
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多