2d arraylist NoSuchElementException - java

I am trying to create a 2D ArrayList and add values to it. For some reason I keep getting a NoSuchElementException.
Here is the problem I am trying to solve: https://www.hackerrank.com/challenges/java-arraylist
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner input = new Scanner(System.in);
int TestCases = input.nextInt();
ArrayList<ArrayList<Integer>> listOfLists = new ArrayList<ArrayList<Integer>>();
List<ArrayList<Integer>> Sdarraylist = new ArrayList<ArrayList<Integer>>();
//ArrayList<ArrayList<String>> 2darraylist = new ArrayList<>();
//ArrayList<String> 1darraylist=new ArrayList<>();
for(int i=0;i<TestCases;i++){
ArrayList<Integer> Fdarraylist=new ArrayList<Integer>();
//size of Arraylist
int NumbersOnCurrentLine = input.nextInt();
for(int j=0;i<NumbersOnCurrentLine;j++){
//add numbers on the current line to the list
Fdarraylist.add(input.nextInt());
}
Sdarraylist.add(Fdarraylist);
}
// data.add(new ArrayList<String>());
//data.get(0).add("String");
}
}

That exception occurs when you try to read from an input, but no input is available. One workaround would be to use use the hasNextInt() method to make sure there is readable input available.
ex)
if (input.hasNextInt()) {
Fdarraylist.add(input.nextInt());
}
This could be the result of the input saying there are three numbers on the current line, when in reality there are only two.
1
3 1 4 <= would cause exception.

Related

Java issues with Scanner and hasNextLine() while reading a file

I am having an issue with this unfinished program. I do not understand why this returns a "no Line found exception" when I run it. I have a while loop set up whose purpose is checking for this but I have done something wrong. I am trying to store information from a file into a 2d array for class.
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
import java.util.Arrays;
public class LabProgram {
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
int NUM_CHARACTERS = 26; // Maximum number of letters
int MAX_WORDS = 10; // Maximum number of synonyms per starting letter
String userWord = (scnr.next()) + ".txt"; //Get word user wants to search
char userChar = scnr.next().charAt(0); //Get char user wants to search
String[][] synonyms = new String[NUM_CHARACTERS][MAX_WORDS]; // Declare 2D array for all synonyms
String[] words = new String[MAX_WORDS]; // The words of each input line
File aFile = new File(userWord);
Scanner inFile = new Scanner(aFile);
while(inFile.hasNextLine()) {
for(int i = 0; i < synonyms.length; i++) {
words = inFile.nextLine().trim().split(" ");
for(int wordCount = 0; wordCount < words.length; wordCount++) {
synonyms[i][wordCount] = words[wordCount];
}
}
}
}
}
The issue is with this for loop:
for (int i = 0; i < synonyms.length; i++) {
words = inFile.nextLine().trim().split(" ");
....
}
You're iterating from i=0 upto synonym.length-1 times, but that file does not have these much lines, so, as soon as your file is out of lines but the for loop has scope to iterate more, the inFile.nextLine() gets no line and thus throw the exception.
I don't know what you are exactly doing here or want to achieve through this code, but this is what causing you the trouble.
Hope that answers your query.
Basically your problem is that you're only checking hasNextLine() before the for loop starts, and you're actually getting the next line on every iteration of the loop. So if you run out of lines while in the middle of your for loop an exception is thrown.
I'm actually not quite sure what your code is supposed to do but at the very least you need to add a hasNextLine() check every time before you actually run nextLine() to avoid errors like this.

Getting number of elements from user input?

I've been googling this but I still don't understand why this doesn't work. The user would enter an array of integers and I need to find how many elements are in that array.
Scanner s = new Scanner(System.in);
int n = 0; //# of elements in list
while(s.hasNextInt()) {
n++;
s.next();
}
System.out.println(n);
I looked up if using variable outside the scope works, and I've been answers saying that if you're gonna use the variable outside the scope, you should declare and initialize outside the scope (in this case, the while loop). However, this still doesn't work for me. My code right now won't even print "0". Any help would be greatly appreciated.
When you read from command line you have to signal EOF (end of file), otherwise how will your program know if you have stopped entering your elements or not? On windows you can press Ctrl-D and your scanner will stop reading, for example.
You can break out of the loop with the condition that a word is entered, such as "exit" since you want to get an int count. Your code works to count the number of integers entered into a scanner, but you never declared an array to hold all the values.
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList array = new ArrayList(); //declare your array
Scanner s = new Scanner(System.in);
int n = 0; //# of elements in list
while(s.hasNextInt())
{
n++;
s.next();
array.add(s);//store the array value
if (s.hasNext("exit"))//allow an exit to the loop
break;
}
System.out.println(array.size()); //better, use the size of the array
}
}
Your code works fine.
Check this link. https://ideone.com/vrnoEz
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner s = new Scanner(System.in);
int n = 0; //# of elements in list
while(s.hasNextInt()) {
n++;
s.next();
}
System.out.println(n);
}
}

How to convert string text from notepad into array line by line?

I am a beginner in programming. I am currently learning how to convert texts from notepad into array line by line. An instance of the text in notepad,
I am a high school student
I love banana and chicken
I have 2 dogs and 3 cats
and so on..
In this case, the array[1] will be string 'I love banana and chicken'.
The lines in the notepad can be updated and I want the array to be dynamic/flexible. I have tried to use scanner to identify each of the lines and tried to transfer them to array. Please refer to my code:
import java.util.*;
import java.io.*;
import java.util.Scanner;
class Test
{
public static void main(String[] args)
throws Exception
{
File file = new File("notepad.txt");
Scanner scanner = new Scanner(file);
String line;
int i = 0;
int j = 0;
while (scanner.hasNextLine()) {
i++;
}
String[] stringArray = new String[i];
while (scanner.hasNextLine()) {
line = scanner.nextLine();
stringArray[j] = line;
j++;
}
System.out.println(stringArray[2]);
scanner.close();
}
}
I am not sure why there is runtime-error and I tried another approach but still did not produce the result that I want.
The first loop would be infinite because you check if the scanner has a next line, but never advance its position. Although using a Scanner is fine, it seems like a lot of work, and you could just let Java's nio package do the heavy lifting for you:
String[] lines = Files.lines(Paths.get("notepad.txt")).toArray(String[]::new);
You can simply do it by creating an ArrayList and then converting it to the String Array.
Here is a sample code to get you started:
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("notepad.txt"));
List<String> outputList = new ArrayList<>();
String input = null;
while (in.hasNextLine() && null != (input = in.nextLine())) {
outputList.add(input);
}
String[] outputArray = new String[outputList.size()];
outputArray = outputList.toArray(outputArray);
in.close();
}
Since you want array to be dynamic/flexible, I would suggest to use List in such case. One way of doing this -
List<String> fileLines = Files.readAllLines(Paths.get("notepad.txt"));

I cant seem to use .split right, what am i doing wrong

I am trying to split a read in file and put it into a 2d array. The file has 3 strings on each
line seperated by a comma, the overall idea is to arrange this with a sorting algorithm but i cant split the strings, its driving me nuts, can anyone help.
/**
*
*
* #author (your name)
* #version (a version number or a date)
*/
import java.util.*;
import java.lang.String;
import java.util.ArrayList;
import java.util.Arrays;
public class Example2{
public static void main(String args[]){
FileIO reader = new FileIO();
Scanner scan = new Scanner(System.in);
String[] inputs = reader.load("C:/ratings.csv");
String[] sep = new String[inputs.length];
for(int i=0;i<inputs.length;i++){
sep[i]=inputs.split(",");
System.out.println(sep[i]);
}
try{
reader.save("C://somefile.csv",inputs);
}catch (Exception e){
System.out.println(e.getClass());
}
}
}
splitis a method in the String class, and inputs is an array of strings. An array access is expected there. You probably just forgot to add [i] in the code. Also, since you are splitting a string in a loop, you are creating a 2D array of strings, which means sep should be a String[][]. Have a go with this.
public class Example2{
public static void main(String args[]){
FileIO reader = new FileIO();
Scanner scan = new Scanner(System.in);
String[] inputs = reader.load("C:/ratings.csv");
String[][] sep = new String[inputs.length][];
for(int i=0;i<inputs.length;i++){
sep[i]=inputs[i].split(",");
System.out.println(Arrays.toString(sep[i]));
}
}
// ...
}
}
I don't know what are you returning but .split will split sep into a list
this code is correct
sep[i]=inputs.split(",");
but here is your problem
String[] sep = new String[inputs.length];
this is 1 dimensional array but you need 2 dimensional array
answer:
String[][] sep = new String[inputs.length][];
this is just to fix the .split problem

How to read in multiple arrays in one loop?

Here are my directions:
This program will use two arrays - these are called parallel arrays. You will NOT be using an array of objects.
You will have a minimum of 6 methods in this application (including main())
inputData() - input from the data file into two arrays - the data file is below, call it "population.txt"
remember to check for the existence of the file before associating the Scanner object to it
displayCountries() - display all of the countries - just the countries
Can you please tell me why this will not run? I need to have the value of the population and the country name together so I can write it in a table later. So I am thinking that I need to read the first value into countryName and the first value into populationNum instead of reading them all in at the same time. The text that I am reading in is below the code. I do not know how to do that though. I am also wondering if I need the [25] when I instantiate. It gives me this error:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Population.inputData(Population.java:32)
at Population.main(Population.java:13)
This is my code:
import java.io.*;
import java.util.Scanner;
import java.io.IOException;
import java.text.DecimalFormat;
public class Population{
public static void main(String [] args)throws IOException{
//Arrays
String [] countryNames = new String [25];
int [] populationNum = new int [25];
//Input data from file into the array
inputData(countryNames, populationNum);
//Displays and calculations
displayCountries(countryNames);
} //end main()
//this class gets the input for arrays from the file
public static void inputData(String [] countryNames, int [] populationNum) throws IOException{
File infile = new File("population.txt.");
int index = 0;
Scanner scan = new Scanner(infile);
while(scan.hasNext())
for(int i = 0; i < countryNames.length; i++)
countryNames[i] = scan.nextLine();
for(int i = 0; i < populationNum.length; i++)
populationNum[i] = scan.nextInt();
} //end inputData()
//this class displays the countries
public static void displayCountries(String [] countryNames) {
for(int i = 0; i < countryNames.length; i++)
System.out.println(countryNames[i]);
} //end displayCountries()
}//end class
Ghana
24333000
Brazil
193364000
Australia
23480970
Nigeria
170123000
Papua New Guinea
6888000
Mexico
108396211
Egypt
79221000
Iran
75078000
Myanmar
50496000
Belgium
10827519
Tuvalu
10000
russia
141927297
You need to read into both arrays in the same loop, like this:
int i = 0;
while(scan.hasNext()) {
countryNames[i] = scan.nextLine();
if (scan.hasNext()) populationNum[i] = scan.nextInt();
if (scan.hasNext()) scan.nextLine(); // Go to the next line
i++;
}
The two for loops inside the while are incorrect (not to mention that the second for loop is not even part of the while, because you omitted curly braces).
Demo.
You need { after while(scan.hasNext()) and closing } after two for loops. What is happening is while loop scans all data then the for loops try to do scan.next when the scanner is already at end of file. Hope this helps

Categories

Resources