This question already has answers here:
Scanner NoSuchElementException
(2 answers)
Closed 2 years ago.
I am running into an error within my program when trying to get input from user. Basically what the program is, it is to pull data from two different exported txt files which I will then cross reference from each of them. At this point I am just trying to test out the file information gathering that the program is going to do prior to cross referencing.
What is happening, I read the one file which is "FromFile.txt" and then it will print out everything and then ask what the other file name that we need to test. At this point it will then throw that error the 2nd time it asks for the input from the user.
I am having difficulties trying to figure out why this is throwing the error
This is the error that is being thrown.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at CrossReferencingTool.getInputString(CrossReferencingTool.java:98)
at CrossReferencingTool.main(CrossReferencingTool.java:23)
Below is the code where it is having the error.
public static String getInputString() {
Scanner input = new Scanner(System.in);
String string;
string = input.next(); <----------------- This is the line where it is throwing the error
input.close();
return string;
}
below is the overall code that is being ran.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class CrossReferencingTool {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<ArrayList<String>> list1 = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> list2 = new ArrayList<ArrayList<String>>();
System.out.println("What is the filename of the file you want to cross reference from:");
File file1 = new File(getInputString());
populateList(file1, list1);
printList(list1);
System.out.println("\nwhat is the filename of the file you want to cross reference with:");
File file2 = new File(getInputString());
populateList(file2, list2);
printList(list2);
}
private static void printList(ArrayList<ArrayList<String>> list) {
String row;
for(int x = 0; x < list.size(); x++) {
row = "";
for(int y = 0; y < list.get(x).size(); y++) {
row += list.get(x).get(y);
if( (y + 1) < (list.get(x).size())) {
row += ", ";
}
}
System.out.println(row);
}
}
private static void populateList(File file, ArrayList<ArrayList<String>> list) throws FileNotFoundException {
Scanner reader = new Scanner(file);
String splitLine[];
String line;
ArrayList<String> internalList;
while(reader.hasNextLine()) {
internalList = new ArrayList<String>();
line = reader.nextLine();
splitLine = line.split(",");
for(int x = 0; x < splitLine.length; x++) {
internalList.add(splitLine[x]);
}
list.add(internalList);
internalList = null;
}
reader.close();
}
public static String getInputString() {
Scanner input = new Scanner(System.in);
String string;
string = input.next();
input.close();
return string;
}
}
Figured out this was because I closed out the scanner on each time I would use the getInputString() function. this would create and then also close out a scanner everytime it is called I do not know why this is causing this though.
could you try to use input.nextLine() instead of input.next() inside your getInputString() method?
Related
public class HelloWorld{
public static void main(String [] args){
boolean found = false;
inputInfo = "do";
String temp = "yes/no/do/you";
Scanner scan = new Scanner(temp); // caseS scanner class
scan.useDelimiter("/"); // Delimiter
String[] caseArray = new String[100];
while (scan.hasNext()) {
for (int i = 0; i < caseArray.length; i++) {
caseArray[i] = scan.next();
}
for(int j = 0; j< caseArray.length; j++) {
if(caseArray[j].equals(inputInfo)) {
found = true;
break;
}
}
if(found){
System.out.print("product found");
} else{
System.out.print("product not found");
}
}
}
}
I have a variable called temp which stores a String value, which is separated by a Delimiter("/"). I would like to go through all the elements in the String and print "product found" if the element exists and print "product not found" if the elements doesn't exists.
While running the program I got an error like:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
Could someone tell as to why this error occurs and how to correct it?
caseArray has a hundred elements and you're next() for each even though the string you're splitting only has four elements in it.
Since the temp string is hard coded, you don't really need a scanner there. In fact, it would be much simpler to hold it as an array or a list to begin with:
List<String> cases = Arrays.asList("yes", "no", "do", "you");
found = cases.contains(inputInfo);
We have file with a few words, try safe word with word have 2,4,6 or 8 letters in array but then save in screen write null and null+good word.
What did I write wrong, and why does it show null?
public static void lyginis () throws IOException {
Path path = Paths.get("words.txt");
Scanner scanner = new Scanner(path);
int kiek = 0;
while (scanner.hasNext()) {
scanner.next();
kiek++;
}
Scanner scanner1 = new Scanner(path);
String[] atrinkti = new String[kiek];
String scan = "";
for (int i = 0; i < kiek; i++) {
scan = scanner1.next();
if (scan.length() % 2 == 0) {
atrinkti[i] += scan ;
}
System.out.println(atrinkti[i]);
}
}
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Hello {
public static void main(String[] args) throws IOException {
File file = new File("words.txt");
Scanner scanner = new Scanner(file);
int kiek = 0;
while (scanner.hasNext()) {
scanner.next();
kiek++;
}
Scanner scanner2 = new Scanner(file);
String[] atrinkti = new String[kiek];
String word = "";
for (int i = 0; i < kiek; i++) {
word = scanner2.next();
if (word.length() % 2 == 0) {
atrinkti[i] = word;
System.out.println(atrinkti[i]);
}
}
}
}
Output
$ cat words.txt
hi
hello
whats up
chicken
duck
goose
$ javac Hello.java; java Hello
hi
up
duck
The issues were:
Path was used instead of File
The += was used within the if statement instead of just =
The System.out.println() function was called outside of the if statement so when the word's length was not divisible by 2, the current array element would print the default initialized value of the array of null
I am trying to do a Java program that will let me input 10 words, and then the words should be repeated in reverse order (the last first etc).
This is my current code:
import java.util.Scanner;
import java.lang.String;
public class Words {
public static void main(String[] args){
String word[] = {};
for(int x = 0; x < 10; x+=1) {
System.out.println("Input any word");
Scanner input = new Scanner(System.in);
word = new String[] { input.next() };
}
for(int y = 9; y >= 0; y-=1) {
System.out.println(word[y]);
}
}}
It gives me the following error when trying to compile:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9 at Words.main(Words.java:21)
I am new to Java and would appreciate help, thanks in advice.
That's not how arrays work.
Change String word[] = {}; to String word[] = new String[10];
Also, change word = new String[] { input.next() }; to word[x] = input.next().
It is also a good idea to move Scanner input = new Scanner(System.in); outside of the for loop. You should read up on how arrays work to make sure this doesn't happen again.
You could try use an ArrayList to do this like so:
import java.util.*;
public class HelloWorld
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
ArrayList al = new ArrayList();
do{
System.out.println("Enter word");
String word = sc.nextLine();
al.add(word);
if(al.size()==10){
System.out.println("Words in reverse order");
for(int i = al.size()-1; i>= 0; i--){
System.out.println(al.get(i));
}
}
}while(al.size()<10);
}
}
I think this answers your question properly.
All the best
Sean
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I try to read text file such this one:
23 0 5 6
28 1 9 5 4 0 3
90 3 6 4 7
-1
I want to read and convert each row individually as integer vector and stop reading when value = -1. I get this code:
importjava.io.FileReader;
importjava.io.IOException;
importjava.util.Scanner;
public class T3 {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("e:\\test.txt");
int[] integers = new int[100];
int[] I = new int[100];
int i = 0;
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
integers[i] = input.nextInt();
i++;
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
for (i = 0; i < 10; i++) {
System.out.println(integers[i]);
}
}
}
But it is useless. Please, I need help.
Modify the while as shown below
Scanner s = new Scanner("file path");
while (s.hasNextLine()) {
//read each line in the file and split the line content on the basis of space
String[] eachLine = s.nextLine().split("\\s+");
}
Once you have the eachLine String array - use it to initialize the Integer vector. Also, following this approach you can avoid the -1 which you are putting explicitly to tell the Scanner the end of line/ file/ input.
Use eachLine.lenght to define the length of each Vector.
For example,
28 1 9 5 4 0 3
90 3 6 4 7
Scanner s = new Scanner("file path");
while (s.hasNextLine()) {
String[] eachLine = s.nextLine().split("\\s+");
//import java.util.Arrays;
System.out.println(Arrays.toString(eachLine));
}
Path path = get("test.txt");
List<int[]> list = new ArrayList<>();
try (BufferedReader reader = newBufferedReader(path)) {
String line;
while ((line = reader.readLine()) != null && !line.contains("-1")) {
if (line.isEmpty()) continue;
String[] strings = line.split(" ");
int[] integers = new int[strings.length];
for (int i = 0; i < strings.length; i++) {
integers[i] = parseInt(strings[i]);
}
list.add(integers);
}
}
Edit:
import static java.nio.file.Files.newBufferedReader;
import static java.lang.Integer.parseInt;
import static java.nio.file.Paths.get;
Lets get you on the right track.
I think the problem with your code is that you assume each next character is an integer. Which is not the case as you have spaces as delimiter.
An approach I would do is read in line by line with the nextLine method. Then use a StringTokenizer to cut all integers apart from eachother by specifying the delimiter (space in your case).
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class EgoStroker {
private static final String DELIMITER = " ";
private static final int MINUS_ONE = -1;
private static final String INPUT_FILE_NAME = "input.txt";
public static void main(String[] args) {
// List containing the integers read.
final List<Integer> integers = new ArrayList<>();
FileReader fileReader = null;
try {
fileReader = new FileReader(INPUT_FILE_NAME);
} catch (FileNotFoundException exc) {
exc.printStackTrace();
}
final Scanner scanner = new Scanner(fileReader);
// Boolean that will become false when -1 is encountered and
// is then used to stop the reading process.
boolean cont = true;
while(cont && scanner.hasNextLine()) {
final String line = scanner.nextLine();
final StringTokenizer tokenizer = new StringTokenizer(line, DELIMITER);
while(cont && tokenizer.hasMoreTokens()) {
final int number = Integer.parseInt(tokenizer.nextToken());
if(number == MINUS_ONE) {
cont = false;
} else {
integers.add(number);
}
}
}
int index = 0;
for(int integer : integers) {
++ index;
System.out.println(index + ". " + integer);
}
}
}
You could replace the List with an array but you don't know in advance how many objects you will have at most so its more safe to use a dynamic List.
CSV File:
515.30,516.81
516.81,514.27
516.74,517.68
517.54,516.72
517.61,517.64
517.22,516.99
517.21,517.33
516.99,516.92
516.96,517.5
517.38,516.91
No blank lines in between.
My program so far:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class CSVRead
{
public static void main(String arg[]) throws Exception
{
double[][] test = new double[9][2];
String[] testStr = new String[19];
String delimiter = ",";
Scanner sc = new Scanner("kort.csv");
while (sc.hasNextLine())
{
String line = sc.nextLine();
testStr = line.split(delimiter);
}
for (int i=0; i<10; i++)
{
for (int j=0; j<2; j++)
{
test[i][j] = Double.parseDouble(testStr[2*i+j]);
}
}
for (int y=0; y<10; y++)
{
for (int x=0; x<2; x++)
{
System.out.print(test[y][x] +" ");
}
}
} //main()
} // CSVRead
Exception in thread "main" java.lang.NumberFormatException: For input string: "AEX2008kort.csv"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.parseDouble(Double.java:540)
at CSVRead.main(CSVRead.java:26)
Java Result: 1
Change to
Scanner sc = new Scanner(new File("kort.csv"));
You want to parse the content of the file, not the String "kort.csv"
After you have done what Alex mentioned, you need to change the way testStr is being used. In your current code, testStr will always have the last line elements (517.38 and 516.91). What you probably want to do is to store the Double numbers in a List perhaps,
List<Double> mynumbers = new ArrayList<Double> ();
and use it later on to populate your 2D array. Once you have split the line into testStr, you should add these numbers to the list,
mynumbers.add(testStr[0]);
mynumbers.add(testStr[1]);
Finally, in the parseDouble method, instead of passing testStr you should pass your list:
mynumbers.get(index_you_want);