我的代码在使用扫描仪的每一行上都给我一个NoSuchElementException。我的其余代码工作正常。
import java.io.*;
import java.util.*;
import java.util.StringTokenizer;
import java.util.Scanner;
public class Store
{
public static void main(String [] args)
{
Scanner nameScanner = new Scanner(System.in);
System.out.println ();
System.out.println ("Enter your name: ");
String name = nameScanner.next();
Scanner whatToBuy = new Scanner (System.in);
System.out.println ();
System.out.println ("What would you like to purchase from the store? Please list your items separated by commas: ");
String purchase = whatToBuy.nextLine();
Scanner howManyToBuy = new Scanner (System.in);
System.out.println ();
System.out.println ("How many would you like to purchase from each item? You must purhase more than one of each item. Please list your items separated by commas. : ");
String howMany = howManyToBuy.nextLine();
}
}
谢谢!
答案 0 :(得分:1)
您的代码没有问题,您可以显示跟踪吗? java.util.StringTokenizer有问题吗? 顺便说一句,您只能使用一个Scanner实例。 例如
import java.io.*;
import java.util.*;
import java.util.StringTokenizer;
import java.util.Scanner;
public class Store {
public static void main(String[] args) {
try(Scanner scanner = new Scanner(System.in)){
System.out.println();
System.out.println("Enter your name: ");
String name = scanner.next();
System.out.println();
System.out.println(
"What would you like to purchase from the store? Please list your items separated by commas: ");
String purchase = scanner.next();
System.out.println();
System.out.println(
"How many would you like to purchase from each item? You must purhase more than one of each item. Please list your items separated by commas. : ");
String howMany = scanner.next();
System.out.printf("name:%s purchase:%s howMany:%s",name,purchase,howMany);
}
}
}
答案 1 :(得分:0)
许多IDE不提供标准输入流。执行窗口是一个虚拟环境,其中Java应用程序在后台运行,其输出被捕获并显示在窗口中,但是没有输入(没有System.in)。尝试在命令提示符窗口(在Windows中)或Shell终端窗口(在Mac中)中运行应用程序。