I need to write a program that reads and stores an inputted file in Java in a double array. The number of values in the file is stored in the first line of the file, then the actual data values follow.
Here is what I have so far:
public static void main(String[] args) throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.print("Please enter the name of the input file: ");
String inputFileName = console.next();
Scanner in = new Scanner(inputFileName);
int n = in.nextInt();
double[] array = new double[n];
for( int i = 0; i < array.length; i++)
{
array[i] = in.nextDouble();
}
console.close();
}
Input File is as follows:
10
43628.45
36584.94
76583.47
36585.34
86736.45
46382.50
34853.02
46378.43
34759.42
37658.32
As of now, regardless of the file name I input, I am getting an exception message:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Project6.main(Project.java:33)
new Scanner(String) constructor scans the specified String. Not the file denoted by the pathname in the string.
If you want to scan the file, use
Scanner in = new Scanner(new File(inputFileName));
Check the following code. Scanner must be provided with File instead of just String as shown in the following snippet:
public class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter the name of the input file: ");
String inputFileName = console.nextLine();
Scanner in = null;
try {
in = new Scanner(new File(inputFileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int n = in.nextInt();
double[] array = new double[n];
for (int i = 0; i < array.length; i++) {
array[i] = in.nextDouble();
}
for (double d : array) {
System.out.println(d);
}
console.close();
}
}
Sample output:
Please enter the name of the input file: c:/hadoop/sample.txt
43628.45
36584.94
76583.47
36585.34
86736.45
46382.5
34853.02
46378.43
34759.42
37658.32
Related
I'm trying to create an Utility Class to take inputs from the Standard Console using java.util.Scanner
package dbasics;
import java.util.*;
public class Utils {
public static int getNumericInput() {
System.out.println("Enter a integer ");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.close();
return n;
}
public static int[] getNumericArrayInput(int n) {
//System.out.println("Enter "+n+" integers seperated by a whitespace ");
int[] numbers = new int[n];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < n; i++) {
numbers[i] =scanner.nextInt();
}
scanner.close();
return numbers;
}
}
While calling the static methods in another class the method getNumericInput() works fine however the following method getNumericArrayInput(int n) results in an exception.
package dbasics;
public class Demo {
public static void main(String[] args) {
int n = Utils.getNumericInput();
System.out.println("Number "+n);
int arr[] = Utils.getNumericArrayInput(n);
for(int i : arr) {
System.out.println(i);
}
}
}
Running this results in following exception
Enter a integer
5
Number 5
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at dbasics.Utils.getNumericArrayInput(Utils.java:21)
at dbasics.Demo.main(Demo.java:9)
The intresting thing I have noticed is if I comment out the first input procedure the array input works fine
You are closing Scanner in your function that is causing in Exception:
Try this:
import java.util.*;
class Utils {
public static int getNumericInput() {
System.out.println("Enter a integer ");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
return n;
}
public static int[] getNumericArrayInput(int n) {
int[] numbers = new int[n];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < n; i++) {
numbers[i] =scanner.nextInt();
}
scanner.close();
return numbers;
}
}
public class cn {
public static void main(String[] args) {
int n = Utils.getNumericInput();
System.out.println("Number "+n);
try{
int arr[] = Utils.getNumericArrayInput(n);
for(int i : arr) {
System.out.println(i);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
For more information please read this link
In the first method, don't close the scanner
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at PeriodicTable.elementsInt(PeriodicTable.java:54)
at PeriodicTable.findElement(PeriodicTable.java:107)
at PeriodicTable.main(PeriodicTable.java:82)
is the error i get when running this code. can anyone tell me where i went wrong? for further information, i'm trying to create a code where it pulls from the periodic table and gives you the element information according to your atomic or abbreviation.
this is the code so far:
public class PeriodicTable {
static class PeriodicElement{
int[] atomicNumber = new int[200];
double[] atomicMass = new double[200];
String[][] abbreviation = new String[200][200];
String[] theTable = new String[200];
public String[] toString(String[] arr){
String[] s = Arrays.toString(arr).split(" ");
return s;
}
public PeriodicElement(String[] pElement) {
toString(pElement);
}
}
public PeriodicTable(String[] theTable) throws IOException{
Scanner inputFile = new Scanner(new File("/Users/eddie/workspace/PeriodicTable/src/table.txt"));
while (inputFile.hasNextLine()){
int i = 0;
theTable[i] = inputFile.nextLine();
i++;
}
inputFile.close();// close the file when done
}
public static String[] readTable(String[] table)throws IOException{
PeriodicTable inputFile = new PeriodicTable(table);
return table;
}
public static int elementsInt(int found)throws IOException{
Scanner inputFile = new Scanner(new File("/Users/eddie/workspace/PeriodicTable/src/table.txt"));
while (inputFile.hasNextLine()){
int[] table = new int[200];
int i = 0;
table[i] = inputFile.nextInt();
if (found == table[i]){
System.out.println("found your number!");
return table[i];
}
else
i++;
}
inputFile.close();// close the file when done.
return found;
}
public static void main(String[] args)throws IOException { // Main Method
final int NUMBER_ELEMENTS = 0;
Scanner keyboard = new Scanner(System.in);
String yourName = "your Name";
System.out.println("Periodic Table by " + yourName);
System.out.println(" ");
System.out.println("Number of elements: " + getNumberOfElements(NUMBER_ELEMENTS));
System.out.println("1. Search atomic number ");
System.out.println("2. Search abbreviation ");
System.out.println("3. Print table ");
System.out.println("4. Exit ");
int choice = keyboard.nextInt();
switch (choice) {
case 1: System.out.print("Enter an atomic number: ");
int aNumber = keyboard.nextInt();
findElement(aNumber);
System.out.println("your atomic number is: " + findElement(aNumber) );
break;
case 2: System.out.print("Enter an abbreviation");
String abbreviation = keyboard.next();
break;
case 3: String[] everything = new String[200];
PeriodicElement print = new PeriodicElement(printTable(everything));
for(int i=0; i<everything.length ;i++){
System.out.println(print);
}
break;
case 4: break;
}
}
public static int getNumberOfElements(int num){
return num = 118;
}
public static int findElement(int e1)throws IOException {
return elementsInt(e1);
}
public static String[] printTable(String[] display)throws IOException{
PeriodicElement printAll = new PeriodicElement(printTable(display));
for(int i=0; i<display.length ;i++){
System.out.println(printAll);
}
return display;
}
}
Seems that your table.txt file contains not only numbers, that's why inputFile.nextInt() throws this exception.
From JavaDoc:
Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.
This Exception is thrown by a Scanner when either the read character isn't what its supposed to find(in this case an integer) or the found token is out of range.
Since the largest predicted Atomic number is 172(correct me if i am wrong), it is well within the range...
Thus, most probably the exception is because you have something other than integers in your table.txt file.Maybe a string, a character, "." etc.
why don't you put it in a try block and run a counter to find the line number where this error happens and check your file.
i have a function to read user input. it takes a parameter to choose reading Ints or Strings. When i try to make sure that it reads only Ints with while(!sc.hasNextInt()) it works, but only when i step it in debug mode. whenever i try to use it while program is running it throws an exception regardless of input being a number or characters.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Databaz.ctecka(Databaz.java:14)
at Databaz.main(Databaz.java:38)
this points me to sc.next(); line in my function:
static String ctecka(int volba)
{
Scanner sc = new Scanner(System.in);
String vystup = "vystup";
if(volba == 1)
{
int cislo = 0;
while(!sc.hasNextInt())
sc.next(); //this is where exception points
cislo = sc.nextInt();
vystup = Integer.toString(cislo);
}
if(volba == 2)
{
vystup = sc.nextLine();
}
sc.close();
return vystup;
}
function is being used from code:
int volba = Integer.parseInt(ctecka(1)); //it returns String so i parse it
That happens because you close your scanner sc.close(); which closes your inputStream then you try to access it again (have a look here), so to solve your problem, generalize your scanner variable, and then close it only when you finish all the ctecka() method calls, like the following:
Scanner sc;
private void some_method(){
int volba1 = Integer.parseInt(ctecka(1));
int volba2 = Integer.parseInt(ctecka(1));
int volba3 = Integer.parseInt(ctecka(2));
int volba4 = Integer.parseInt(ctecka(3));
sc.close();
}
String ctecka(int volba){
sc = new Scanner(System.in);
String vystup = "vystup";
if(volba == 1)
{
int cislo = 0;
while(!sc.hasNextInt())
sc.next();
cislo = sc.nextInt();
vystup = Integer.toString(cislo);
}
if(volba == 2)
{
vystup = sc.nextLine();
}
return vystup;
}
This is for a school project that I'm doing. I need to take data from a file and use setter methods to assign the next part of the line to different parts of a class. I have to assign all of that information for multiple instances in an array.
public static void main(String[] args) throws Exception {
//declarations and input
Scanner input = new Scanner(System.in);
System.out.println("Enter the file to read from: ");
String fileIn = input.next();
System.out.println("Enter the number of accounts in the file: ");
int number = input.nextInt();
System.out.println("Enter the file to output the distribution list to: ");
String fileOut = input.next();
//call function
Account[]students = (readFile(fileIn, number));
System.out.println("Done with File");
}
public static Account[] readFile(String file, int column) throws Exception
{
File myFile = new File(file);
Scanner fileInput = new Scanner(myFile);
Account[]students = new Account[column];
while(fileInput.hasNext())
{
for(int i=0; i<=column; i++)
{
students[i].setID(fileInput.nextInt());
students[i].setName(fileInput.next());
students[i].setUsername(fileInput.next());
students[i].setPassword(fileInput.next());
students[i].setEmail(students[i].getUsername()+"#mail.nwmissouri.edu");
}
}
return students;
}
When I test it out I get this error:
Exception in thread "main" java.lang.NullPointerException
at project6driver.Project6Driver.readFile(Project6Driver.java:36)
at project6driver.Project6Driver.main(Project6Driver.java:22)
36 is the first time I'm using the setter method inside my for loop. I don't understand why this doesn't work, can somebody point me in the right direction?
I want to know how I could take keyboard input and save it as a variable so I can use it with the code below.
Code:
public void readMaze(){
Scanner reader = null;
try {
reader = new Scanner(new FileReader("Maze.txt"));
colSize = reader.nextInt();
rowSize = reader.nextInt();
finishRow = reader.nextInt();
finishCol = reader.nextInt();
startRow = reader.nextInt();
startCol = reader.nextInt();
Instead of having "Maze.txt" I want to have a variable there that can change every time I run the program so I won't have to keep editing the program when I want to use a different file.
You can capture the file name using your Scanner itself:
System.out.println("Please input the file name to use: ");
Scanner reader = new Scanner(System.in);
String fileName = reader.next();
Then proceed with your method as usual, reusing the same Scanner variable for a new Scanner object, this time passing filename you captured earlier:
try {
reader = new Scanner(new FileReader(fileName));
...
}
With this, you'll be able to dynamically change the filename while your program is running.
I would probably use command line arguments:
public static void main(String[] args)
{
final String mazeFilename = args[0]; // perhaps check if args.length > 0
...
}
then
java YourPrgm Maze.txt
You could try scanning them in through the console and changing them from Strings to ints.
public static void main(String[] args) {
int colSize, rowSize, finishRow, finishCol, startRow, startCol = 0;
// note, through console
Scanner in = new Scanner(System.in);
System.out.print("Enter colSize:");
colSize = Integer.parseInt(in.nextLine());
System.out.print("Enter rowSize:");
rowSize = Integer.parseInt(in.nextLine());
System.out.print("Enter finishRow:");
finishRow = Integer.parseInt(in.nextLine());
System.out.print("Enter finishCol:");
finishCol = Integer.parseInt(in.nextLine());
System.out.print("Enter startRow:");
startRow = Integer.parseInt(in.nextLine());
System.out.print("Enter startCol:");
startCol = Integer.parseInt(in.nextLine());
}
}