import java.util.*;
public class App {
public static void main(String[] args){
Scanner user=new Scanner(System.in);
int i,j;
for(i=0;i<=3;i++){
String s1=user.nextLine();
int x=user.nextInt();
user.nextLine();
String space =" ";
for(j=0;j<=15-s1.length();j++){
space =space+" ";
}
if(x<100){
System.out.println("================================\n");
String.valueOf(x);
String new_x="0"+x;
System.out.println(s1+space+new_x+"\n");
System.out.println("================================\n");
}
else if(x<10){
System.out.println("================================\n");
String.valueOf(x);
String new_x="00"+x;
System.out.println(s1+space+new_x+"\n");
System.out.println("================================\n");
}
else{
System.out.println("================================\n");
System.out.println(s1+space+x+"\n");
System.out.println("================================\n");
}
}
user.close();
}
}
黑客等级中的问题讨论了在输入中写入字符串和整数以及在字符串和整数之间留出空格。
空格+字符串必须等于15索引,我将黑客排名问题的链接放在代码下。
这是黑客排名链接:https://www.hackerrank.com/challenges/java-output-formatting/problem?isFullScreen=true
我尝试使用 Java 解决他们网站上的 HackerRank 问题,并且在 VS Code 中成功运行。
但是,当我尝试在 HackerRank 上运行相同的代码时,遇到了运行时错误。
当我删除代码中的所有 for 循环时,它给出了错误的答案,而不是运行时错误。
最佳答案
-
for(int i = 0; i <= 3; i++)
- 您应该迭代恰好 3 次。正确的是for(int i = 0; i < 3; i++)
. - 另一个大问题,您不应该关闭扫描仪
user.close();
。它不是外部资源,这是内置的javaSystem.in
。您关闭扫描仪,即关闭此流,任何人都无法再使用它。但你是后来的 HackerRank 框架。
附注顺便说一下。让我向您展示更优雅、更高效的解决方案。您可以使用String.format()
构建所需的字符串。
public static void main(String... args) {
Scanner sc = new Scanner(System.in);
System.out.println("================================");
for (int i = 0; i < 3; i++) {
String s1 = sc.next();
int x = sc.nextInt();
System.out.println(String.format("%-15s%03d", s1, x));
}
System.out.println("================================");
}
关于java - 如何解决在VScode中成功运行相同代码而在黑客等级中出现运行时错误问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76739007/