對於這個程序,我努力在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循環中無條件返回的 - 什麼是循環的意義? –
您是否想要實際記錄六個名字,或者您打算允許多達六次嘗試進行某個輸入? –
我打算從掃描儀上接受多個輸入。 –