gpt4 book ai didi

java - 返回语句在 Java 中不起作用?

转载 作者:行者123 更新时间:2023-11-29 07:01:05 24 4
gpt4 key购买 nike

你好我正在尝试使用返回类型“String”的方法打印一系列字符。下面提到的是逻辑。我得到的错误是:

 prog1.java:34: error: missing return statement
}
^
1 error

下面提到的是代码。它应该打印字符..我可以使用“void”类型,但我不能使用返回类型“int”。任何建议将不胜感激。

import java.util.*;

class prog1
{

public static void main(String[] args)
{
double height;
double width;
String fillcharac;
Scanner sc = new Scanner(System.in);
System.out.println("enter a value for height");
height = sc.nextDouble();
Scanner sc1 = new Scanner(System.in);
System.out.println("enter a value for width:");
width = sc.nextDouble();
Scanner sc2 = new Scanner(System.in);
System.out.println("enter the character value:");
fillcharac = sc2.next();
String x = print(height, width, fillcharac);
System.out.println(x);
}

public static String print(double height, double width, String fill)
{
for (double i = 1; i <= height; i++)
{
for (double j = 1; j <= width; j++)
{
return fill;
}
}

}
}

最佳答案

您的内部 for 循环似乎应该“构建”一个在循环结束后返回的字符串。

也许该方法应该命名为 build 而不是 print 因为打印是稍后完成的?

类似于:

public static String build( double height, double width, String fill ) {
String result;
for( double i=1; i<=height; i++) {
for(double j=1; j<=width; j++) {
// Build your string here using i, j and fill
// result = ...
}
}
return result;
}

然后你可以这样做:

//  Build the output string
x = build( height, width, fillcharac );

// Print the output string
System.out.println( x );

关于java - 返回语句在 Java 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26044492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com