HackerRank扫描器类的Java
问题描述:
这个代码是用于打印链表和在Eclipse做工精细: -HackerRank扫描器类的Java
import java.util.Scanner;
public class HackerAss {
static Scanner scan;
static Node head;
static Node current;
public static void main(String[] args) {
int q=1,count=0;
while(q==1){
scan = new Scanner(System.in);
q = scan.nextInt();
if(q==0)
break;
else{
int element = scan.nextInt();
if(count == 0)
current = new Node(element);
else{
head = new Node(element);
head.node = current;
current = new Node(element);
}
}
count++;
}
while(head!=null){
System.out.println(head.data);
head=head.node;
}
}
static class Node{
int data;
Node node;
public Node() {
data=0;
node=null;
}
public Node(int data) {
this.data=data;
node=null;
}
}}
但HackerRank它显示的错误: - 螺纹
异常 “主” 的java.util .NoSuchElementException
错误的原因是什么,什么是解决方案。我有作业提交。
答
你的问题来自你的代码,而不是你的IDE。
首先,你应该定义一次扫描:
while(q==1){
scan = new Scanner(System.in);
q = scan.nextInt();
...
}
这是一个非常糟糕的主意,东阳,你甚至不知道是否有东西流中,你不得不使用扫描仪这样的:
scan = new Scanner(System.in);
while(scan.hasNextInt()){
q = scan.nextInt();
...
}
后,java.util.NoSuchElementException
来自您调用nextInt(事实)两次:
scan = new Scanner(System.in);
q = scan.nextInt();
...
int element = scan.nextInt();
在文档nextInt()
当输入耗尽时抛出java.util.NoSuchElementException
:https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29
答
此错误来自nextInt()。你必须避免这种情况,如下面的代码
import java.util.Scanner;
public class HackerAss {
static Scanner scan;
static Node head;
static Node current;
public static void main(String[] args) {
int q=1,count=0;
scan = new Scanner(System.in);
while(q==1){
if(scan.hasNextInt()) {
q = scan.nextInt();
}
if(q==0)
break;
else{
if(scan.hasNextInt()) {
int element = scan.nextInt();
}
if(count == 0)
current = new Node(element);
else{
head = new Node(element);
head.node = current;
current = new Node(element);
}
}
count++;
}
while(head!=null){
System.out.println(head.data);
head=head.node;
}
}
static class Node{
int data;
Node node;
public Node() {
data=0;
node=null;
}
public Node(int data) {
this.data=data;
node=null;
}
}}
另外'scan = new Scanner(System.in);'应该从'while'循环移出 – Solorad