【发布时间】:2016-12-16 01:25:36
【问题描述】:
对于这个程序,我正在努力在返回方法(“notString”)中创建一个 for 循环。我试图让程序六次询问姓名;但是,我收到一个错误,告诉我添加一个返回值,它位于 for 循环内。
这是我必须创建程序的语句:给定一个字符串,返回一个新字符串,其中“not”已添加到前面。但是,如果字符串已经以“not”开头,则返回原样的字符串。
import java.util.*;
public class practice1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String answer= notString(sc);
System.out.println(answer);
}
public static String notString(Scanner sc){
for(int i=0; i<=6;i++){
System.out.println("Input Name: ");
String name= sc.nextLine();
if(name.startsWith("not")){
return name;
}else
return "not"+name ;
}
}
}
【问题讨论】:
-
如果您查看您的代码,您会发现它在 for 循环中无条件地是
returning - 有一个循环有什么意义? -
您是要实际记录六个姓名,还是计划允许对某个输入最多进行六次尝试?
-
我正计划从扫描仪获取多个输入。
-
所以它应该将名称存储在字符串数组中?
-
是的,我认为我应该这样做。