嗨,我需要一些代码方面的帮助,我正在尝试反转用户输入的字符串,如果有人有repl.it的经验,请在此处提供代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.println("enter a number");
int i = inp.nextInt();
int o =i+i;
System.out.println(o);
}
Scanner inp = new Scanner(System.in);
System.out.print("In:");
String word = inp.nextLine();
int counter = word.length();
for(counter>0){
System.out.println(word.charAt(counter));
int counter-1;
}
}
这里是一长串错误
退出状态1Main.java:16:错误:预期
System.out.print("In:");
^
Main.java:16:错误:类型的非法开始
System.out.print("In:");
^
Main.java:19:错误:类型的非法开始
for(counter>0){
^
Main.java:19:错误:预期
for(counter>0){
^
Main.java:19:错误:';'预期
for(counter>0){
^
Main.java:19:错误:类型的非法开始
for(counter>0){
^
Main.java:19:错误:预期
for(counter>0){
^
Main.java:19:错误:';'预期
for(counter>0){
^
Main.java:20:错误:类型的非法开始
System.out.println(word.charAt(counter));
^
Main.java:20:错误:';'预期
System.out.println(word.charAt(counter));
^
Main.java:20:错误:方法声明无效;返回类型必填
System.out.println(word.charAt(counter));
^
Main.java:20:错误:预期
System.out.println(word.charAt(counter));
^
Main.java:20:错误:';'预期
System.out.println(word.charAt(counter));
^
Main.java:20:错误:类型的非法开始
System.out.println(word.charAt(counter));
^
Main.java:20:错误:预期
System.out.println(word.charAt(counter));
^
Main.java:21:错误:';'预期
int counter-1;
^
Main.java:24:错误:预期使用类,接口或枚举
}
^
17个错误
public static void main(String [] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("In: ");
String word = scanner.nextLine();
System.out.println(new StringBuilder(word).reverse());
} catch (Exception e) {
e.printStackTrace();
}
}
这是固定的最终结果
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.println("enter a number");
int i = inp.nextInt();
int o =i+i;
System.out.println(o);
Scanner in = new Scanner(System.in);
System.out.print("In:");
String word = in.nextLine();
//write your code below
int counter = word.length();
while(counter>0){
System.out.print(word.charAt(counter-1));
counter--;
}
}
}
导致此错误的原因是,您将代码置于main
方法之外。您要执行的每个代码都必须属于方法public static void main
。
这是解决方法:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.println("enter a number");
int i = inp.nextInt();
int o =i+i;
System.out.println(o);
System.out.print("In:");
String word = inp.nextLine();
int counter = word.length();
for(counter>0){
System.out.println(word.charAt(counter));
int counter-1;
}
}
}