Scanner Reading Data file Java.Util.NoSuchElementException: Null - java

I'm trying to write a class that will take in numbers from a file, but I keep running into this error when I run:
Java.util.NoSuchElementException: Null(in java.util.Scanner)
This is my code:
import java.util.*;
import java.io.*;
public class finalMain
{
public static void main (String args[]) throws IOException
{
int lineNumber = 0;
Scanner sc = new Scanner (new File ("Prog349f.txt"));
System.out.println("Student Quiz 1 Quiz2 MidTerm Final Final % Grade");
while(sc.hasNextLine())
{
lineNumber++;
sc.nextLine();
}
for(int i = 1; i <= 1; i++)
{
int quizOne = sc.nextInt();
int quizTwo = sc.nextInt();
int midterm = sc.nextInt();
int finalTest = sc.nextInt();
finalGrade studentNext = new finalGrade(sc.nextInt(),sc.nextInt(), sc.nextInt(),sc.nextInt(), i);
System.out.println(studentNext);
}
sc.close();
}
}
I'm thinking maybe I need to create two scanner objects, one for each line or something but I don't know how I would go about doing that.

You have misunderstood the usage of Scanner methods : sc.nextLine(); consumes and returns the line.
That means that you're currently reading the whole file with sc.nextLine();, discarding the result, and only then you try to read 4 ints, that can't be read since the Scanner is at the end of the file.
You should instead use one of these two methods :
If you're positive that each line of your file contains 4 ints separated by space (or any other specific character), and nothing more, you can then scan 4 ints while the scanner has a next line.
If there might be variations, or useless data, you should keep your hasNextLine() and nextLine() calls as they are, then use regex, split+indexing or another Scanner to retrieve the 4 ints from the line.

Related

How can I fix string matrix index problem?

I'm trying to store name and address of persons in the form of 2d array, but when I run my code it accepts less values only. For example if I give the array 2 rows and 2 columns, it accepts only 3 values.
I've tried searching on other forums, couldn't get the proper answer.
I also changed the dimension values but it gives wrong result only.
import java.util.*;
class findme{
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
System.out.print("enter the number of person: ");
int per=scan.nextInt();
System.out.print("enter the number of address: ");
int addr=scan.nextInt();
String addrs[][]=new String[per][addr];
for(int i=0;i<per;i++){
for(int j=0;j<addr;j++){
addrs[i][j]=scan.nextLine();
}
}
}
}
You read 4 values but one is an empty line from when you press enter for int addr=scan.nextInt();
A quick fix is to read that empty line
import java.util.*;
class findme{
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
System.out.print("enter the number of person: ");
int per=scan.nextInt();
System.out.print("enter the number of address: ");
int addr=scan.nextInt();
---> scan.nextLine();
String addrs[][]=new String[per][addr];
for(int i=0;i<per;i++){
for(int j=0;j<addr;j++){
addrs[i][j]=scan.nextLine();
}
}
}
}
Edit:
Or you can use scanner.skip Skip newline character while reading from Scanner class
In addition to the other answer here is how your code should look like:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of people: ");
int iPeople = scanner.nextInt();
System.out.print("Enter the number of address: ");
int iAdresses =scanner.nextInt();
scanner.nextLine();
String data[][] = new String[iPeople][iAdresses];
for(int i=0; i < iPeople; i++)
{
for(int j=0; j < iAdresses; j++)
{
System.out.printf("Enter %d address for person %d:%n", j + 1, i + 1);
data[i][j] = scanner.nextLine();
}
}
And try to follow these conventions:
Use proper Java naming conventions
Make your code more readable by providing appropriate empty lines between lines you feel are too cluttered or belong to different groups based on what operation are they trying to accomplish.
If you want to understand why, the behavior of nextLine is explain here : Java Scanner doesn't wait for user input
You can also replace nextLine by next to avoid this.

How to use Scanner in both main and method

I'm trying to get input in both my main and other methods, but I'm not clear on how to get the scanner working in both.
It gives me a weird error:
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.nextDouble(Unknown Source)
at Hwk11.getRainData(Hwk11.java: 28)
at Hwk11.main(Hwk11.java: 18)
Code:
import java.util.Scanner;
public class Hwk11 {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
System.out.println("How many weeks of data do you have?");
int numWeeks = stdin.nextInt();
if (numWeeks <= 0 || numWeeks > 52) {
System.out.println("Invalid number of weeks.");
}
else {
double[] rainWeeks = new double [numWeeks];
getRainData(rainWeeks);
showRain(rainWeeks);
}
}
public static void getRainData(double[] rainFall) {
Scanner stdin = new Scanner(System.in);
System.out.println("Enter the weekly rainfall for each week.");
for (int index = 0; index < rainFall.length; index++) {
System.out.println("Week number " + (index + 1) + ":");
rainFall[index] = stdin.nextDouble();
}
}
public static void showRain(double[] rainFall) {
for (int index = 0; index < rainFall.length; index++) {
System.out.print(rainFall[index] + " ");
}
}
}
People are saying "works for me".
The problem that the behavior (whether it works or not) depends on exactly how input is provided.
If you provide input interactively, it will probably work.
If you provide input by redirecting standard input like this:
java Hwk11 < input.txt
then it won't.
The problem is that a Scanner will read-ahead and buffer any characters available from its input stream. That is fine normally, but in your code you have created two distinct Scanner objects to read from System.in. Thus when standard input is redirected:
The first Scanner.nextInt call will cause most / all of the input to be buffered in the first Scanner
When the second Scanner is created and Scanner.nextDouble is called, it won't see the input buffered in the first Scanner and that will lead to an exception ... when it runs out of input characters "too soon".
The solution is to NOT create multiple Scanner objects for the same input stream. Use one Scanner and either put it in a field, or pass it as a parameter to all of the places that it needs to be used.
Works for me. Don't enter anything but a double if you asking for next double so no "2.3 cm", just pass 2.3 and add cm when you print in
I am assuming your showRain(double[] rainFall) method probably executes before getRaindata(double[] rainFall) is able to finish and populate the array. Array you passsing to showRain(double[] rainFall) might be empty.
Try putting your method call for showRain(double[] rainFall) after loop in getRanData(double[] rainFall)
Alternitivly try passing the whole Scanner object to method.
public static void getRainData(double[] rainFall, Scanner stdin) {
//Scanner stdin = new Scanner(System.in);
System.out.println("Enter the weekly rainfall for each week.");
for (int index = 0; index < rainFall.length; index++) {
System.out.println("Week number " + (index + 1) + ":");
rainFall[index] = stdin.nextDouble();
}
showRain(rainFall);
}
Don't forget to close it when you done with scanner.

How to take array elements as input

My program is to accept words (given as number of test cases) and print them out in reversed order. The problem is that whatever input of array size I may give, it only accepts just one word (and rest as blank). Can anyone help me figure out why? Here's the code:
import java.util.*;
public class terrible {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int test = input.nextInt();
while(test>0){
String str = input.nextLine();char c[] = str.toCharArray();
for(int i=0;i<str.length();i++){
System.out.print(c[str.length()-i-1]);
}
System.out.println();
test--;
}
}
}
Certain versions of Java don't let you take an int and then a string as input from the same Scanner. You can create another Scanner, like
Scanner input2 = new Scanner(System.in);
and then do
String str = input2.nextLine();

Taking int as input in java

I tried using following code for reading int input
import java.util.*;
public Add{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> arr = new ArrayList<>();
while(scan.hasNextInt()){
arr.add(scan.nextInt());
}
System.out.println(arr);
}
}
When I run the program with any input say -
1 2 4
It does not stop till I press CTRL+c. I have also tried some other variations(for example tried to read it as array of String but that also did not work) but they are the same.Problem is that I don't want to give the size of the input in advance. How can I parse int from console input?
You will need to check for certain input and break from the loop as hasNextInt will wait for input from keyboard. You could solve it by following:
int number;
while(scan.hasNextInt()){
number = scan.nextInt();
if (number == -1) {//if user types in -1, then you will come out of the loop.
break;
}
arr.add(number);
}
Since you are using scanner, you may try the following trick instead of using the ArrayList -
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
while (sc.hasNextInt()) {
int num = sc.nextInt();
System.out.println("Your entered number is: " + num);
}
If you use hasNextInt() then you don't have to think about the parsing of number. A token that is not a integer will break out you from the loop.

Scanner object behaves differently for Integer vs String inputs [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Scanner issue when using nextLine after nextInt
In the following two code snippets, I first ask for the number of inputs required and let the user input that many inputs of a particular kind. When the required inputs are String types, it takes one less input unless I use s.next() first, while for Integers it works fine. I don't understand why. Can someone please explain?. Thanks
First Code with String inputs and nextLine function:
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int num = s.nextInt();
String[] inputs = new String[num];
for (int i = 0; i < inputs.length; i++) {
inputs[i]=s.nextLine();
}
System.out.println("end of code");
}
Second Code with Integer inputs and nextInt function:
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int num = s.nextInt();
Integer[] inputs = new Integer[num];
for (int i = 0; i < inputs.length; i++) {
inputs[i]=s.nextInt();
}
System.out.println("end of code");
}
It is because of the following line:
int num = s.nextInt();
Your next INT only returns the INT until it gets to the \n character.
If you had a test file like this:
4
1
2
3
4
Your character code will look like this:
4'\n'
1'\n'
2'\n'
3'\n'
4'\n'
So when you grab the integer, it will grab the 4 for your "nextInt()" method on the scanner. When you tell it to grab the next line "nextLine()", it will grab the remainder of that line which is just '\n' and store nothing into the first value into your array.
On the reverse side, if you tell it to grab the next integer "nextInt()", it will search until it finds the next integer, which will cause the 1 to go into the first value into the array.

Categories