对于这个程序,我努力在return方法(“notString”)中创建一个for循环。我试图让程序要求一个名字六次;但是,我收到一个错误,告诉我要添加一个返回值,它位于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循环中无条件返回的 - 什么是循环的意义? –
您是否想要实际记录六个名字,或者您打算允许多达六次尝试进行某个输入? –
我打算从扫描仪上接受多个输入。 –