如何在返回方法中使用for循环?
问题描述:
对于这个程序,我努力在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 ;
}
}
}
答
有两个方面对这一问题。
第一个方面是Java编译器告诉你,它“认为”你的方法有很多方法可以在不做显式返回的情况下结束。
事实上,事实并非如此。有可能证明循环之后的代码(如写入)无法达到。
然而,根据JLS 代码的可达性,该编译器以实现所需规则,所以能够达到该方法的结束。因此,必须是 a return
循环后的语句。
但更深的一面是,你所做的是错误的。你写的将不会要求串六次,因为它是必需的。
实际上做的只是询问一次后“放弃”。 return
声明表示“立即返回”。并且在您放置return
声明的位置,如果某物是true
或者它是false
,那么您将返回“NOW”即总是。
如果你要问六倍,那么:
- 没有从环路的中间返回,或者
- 动循环的主要方法。
我不能告诉你哪个是正确的方法,因为你对程序应该/要求做什么的解释是不完整的。
答
是的,你必须有一个方法notString()的return语句,它承诺在方法签名中返回一个String。下面的程序将编译和运行(虽然我不知道这是否会是你最后的方案):
修改程序:
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) {
String answer = "";
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;
}
}
return answer; // Problem 2: missed a return statement
} // Problem 1: missed a closing brace
}
答
该程序在语法和构造上都是错误的。在这种情况下,没有办法传递扫描器对象。如果你只是想打印6个输入,当他们来做这件事时。
import java.util.*;
public class practice1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
for(int i=0; i<=6;i++){
String temp = sc.nextLine();
String answer = temp.startsWith("not")?temp : "not" + temp;
System.out.println(answer);
}
scanner.close();
}
}
,如果你想将它们存储在数组中,并打印出来后马上做到这一点。
import java.util.*;
public class practice1 {
public static void main(String[] args) {
String[] names = new String[6];
Scanner sc=new Scanner(System.in);
for(int i=0; i<=6;i++){
String temp = sc.nextLine();
String answer = temp.startsWith("not")?temp : "not" + temp;
names[i] = answer;
}
scanner.close();
for(String name : names){
System.out.println(name);
}
}
}
如果你看看你的代码,你会发现它是在for循环中无条件返回的 - 什么是循环的意义? –
您是否想要实际记录六个名字,或者您打算允许多达六次尝试进行某个输入? –
我打算从扫描仪上接受多个输入。 –