NoSuchElementException reffers to first scanner when another is created - java

so there is probably someone in the group who has similar problem but i couldn't find close one as mine. I cant make 2 scanners work, one after another... adding 2nd scanner makes 1st go nuts and throw
"NoSuchElementException"
at the start of the scanner command.
here is my code:
public class Stiklainiai {
static Scanner program = new Scanner(System.in);
static Scanner name_input = new Scanner(System.in);
public static void main(String[] argumentai){
System.out.println("Welcome to Java IDE !");
name();
jar();
}
public static String name() {
String name_select;
System.out.println("name yourself");
name_select = name_input.next();
name_input.close();
return name_select;
}
public static int jar(){
int jar_select; // input variable (1-6) for "if" statement
int jar_weight_assigned = 0; //unassigned capacity (applied by default if error occurs (outside 1-6 bounds))
String jar_name_assigned = ""; //unassigned name (applied by default if error occurs (outside 1-6 bounds))
int custom_jar_cap = 0; //custom "int" variable (custom jar)
String custom_jar_name = ""; //custom "String" variable (custom jar)
int[] jar_weight_arr = new int[5]; //jar capacity array
String[] jar_name_arr = new String[5]; //jar name array
jar_weight_arr[0] = 9;
jar_weight_arr[1] = 99;
jar_weight_arr[2] = 999;
jar_weight_arr[3] = 9999;
jar_weight_arr[4] = 99999;
jar_name_arr[0] = "bybiene22";
jar_name_arr[1] = "bybiene44";
jar_name_arr[2] = "bybiene66";
jar_name_arr[3] = "bybiene88";
jar_name_arr[4] = "bybiene000";
jar_select = program.nextInt();
...
...
...
and so on goes the rest of the code.
when i run it i can input a name but afterwards i get "NoSuchElementException" that refers to:
jar_select = program.nextInt(); (where the scanner opens)
followed by the declared method error in main method:
jar();
rest of the code works fine with just one scanner...
my point is to make one method with separate scanner that assigns name to the
"x" variable, and returns the value to main method. Then, the second runs the rest of the program in the other method, using the "x" variable with the value imputed
anyone knows the cause, i'm fairly fresh in java :)

The problem is hidden behind Scanner.close. Whenever you close the Scanner, you also close the underlying System.in, so it wont be available the text time your access it using your second scanner.
Solution: Do not close the first Scanner.

Related

How to use the Scanner in a separate method without calling it multiple times

what the program does: The program I'm trying to create takes a name a user inputs, and finds how many characters they type, uses that information to generate a random number that acts as an ID, and then the program stores the name the user inputted earlier and the random number it generated inside of two separate arrays, and then prints out the array.
What i'm trying to do: Instead of using the scanner class in the main, I'm using it in it's own method that method is called personName().
The problem that I am facing: the problem am i facing is when I run the program I have to type the name twice, if I dont it throws me an exception.
the cause of the problem: I know what's causing the problem, I just dont know how to fix it. The problem arise when I call personName() twice in two different methods, but I need to call it twice so i can get the data from it. The first time i called it is in the id() method. I did this so i can get how many characters the name has. The second time i called it when it's in the yourArrays() method. I did this because I needed to store the name inside of an array. I called it twice by using the variable String yourName = personName(); inside the id() method and I called it again using the variable String name = personName(); inside the yourArrays(); method.
what have I tried: I tried to close the scanner but it still just throws the exception since it's still getting called twice, and since it is closed there's no way to get the data anyway.
What answer am I looking for: The answer I want is how do I stop the system from asking the user to input the name twice, or is there a way to get the name the user inputted without calling the method?
the code:
import java.util.*;
public class IdMaker {
public static void main(String[] args) {
System.out.println("Hello welcome to our new system of generating your ID!");
System.out.print("Please enter your name: ");
yourArrays(); //outputs the arrays
}
public static int randomNumber(int a) { //the method that generates the random number
Random rand = new Random();
int ID = rand.nextInt(a)+1000;
return ID;
}
public static String personName() { //the method that gets and stores the user's name
Scanner name = new Scanner(System.in);
String yourName = name.nextLine();
return yourName;
}
public static int id() { //the method that takes the user name, computes the length of the characters of the name to use for the number generator
String yourName = personName(); //personName() called once
int length = yourName.length();
int id = randomNumber(length);
return id;
}
public static void yourArrays() {// the method that takes the ID and the name and stores it into the arrays
String name = personName(); //personName() called twice
int yourId = id();
String[] nameArray = {name};
Integer[] idArray = {yourId};
for(int i = 0; i < nameArray.length; i++) {
System.out.println("the names are: " + nameArray[i] + " ");
}for(int i = 0; i < idArray.length; i++) {
System.out.println("the IDs are: " + idArray[i] + " ");
}
}
}
the output:
this is how it looks when the user have to enter it twice
Hello welcome to our new system of generating your ID!
Please enter your name: chris
chris
the names are: chris
the IDs are: 1001
the output if you dont enter the name twice
Hello welcome to our new system of generating your ID!
Please enter your name: chris
Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Random.java:388)
at IdMaker.randomNumber(IdMaker.java:14)
at IdMaker.id(IdMaker.java:34)
at IdMaker.yourArrays(IdMaker.java:41)
at IdMaker.main(IdMaker.java:7)
Rather than calling personName() again, which will cause the user to be asked for input again, id should accept a name as a parameter, and use that generate an ID:
public static int id(String name) {
int length = name.length();
int id = randomNumber(length);
return id;
}
You can then pass the name returned by yourName to id in the yourArrays method:
public static void yourArrays() {
String name = personName();
int yourId = id(name);
...

Import these scanners into another class?

Again I am very new to Java, and I have this code here:
package Final;
import java.util.Scanner;
public class Position {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner MyPos = new Scanner(System.in);
System.out.println(" Enter Position: ");
String Pos = MyPos.nextLine();
System.out.println("Position: "+Pos);
Scanner MyMains = new Scanner(System.in);
System.out.println("Enter Mains: ");
String Mains1 = MyMains.nextLine();
System.out.println("Mains: "+Mains1);
Scanner WScore = new Scanner(System.in);
System.out.println("Enter Ward Score: ");
String score = WScore.nextLine();
System.out.println(" Average Ward Score is:"+score);
}
}
I was curious if there was a way to possibly import all 3 of my scanners to another class without moving all the actual code from this class? The class I'm trying to move it to is a class called "Player.java". There aren't any problems with my code, but additional input is always appreciate to help me understand and improve my code!
You don't need a new scanner for each variable. What you do need to do is close() a scanner when you are done using it.
You are thinking of the Scanner itself being associated with a variable - when in fact it is associated with System.in...
So, every time you want another variable, just do:
Scanner sc = new Scanner(System.in);
String firstThing = sc.nextLine();
String secondThing = sc.nextLine();
sc.close(); // Do this when you're done storing input from System.in!
Once you have declared your scanner. I'm not sure why you would want to pass the scanner to another class. What you can do easily is pass the variables that you grab from your scanner into a player object.
Just do Player p1 = new Player(stringYouScanned); assuming that you have your constructor in your Player class accept a String.
Or, look up getter and setter methods. Then you can do something like: `p1.setPosition(4);' (you could replace 4 with an int you scanned in, you get the idea).
If for some reason you want to scan input from within the Player, I'd just initialize a new Scanner, but make sure you are doing sc.close(); after you are done processing your input.

Needing help to get the next line from the scanner and assign the value to the Array element at position i

I'm really new to programming and I am having trouble trying to figure out how to write this line of code that I have to read the next line from the scanner and as assign the value to the candyArray at position i. I am also told that I need to incorporate the readLine() to advance the input cursor past the first line.
public static void main(String[] args) throws FileNotFoundException {
// File containing candy names
File f = new File("candy.txt");
Scanner sc = new Scanner(f);
// Array of candy names
String[] candyNames;
// Number of names
int numNames = sc.nextInt();
// Move to the next line
sc.nextLine();
// Set the array size
candyNames = new String[numNames];
// Read each line and copy to array element
for (int i = 0; i < numNames; i++) {
// Add the missing statement
//The statement should get the next line from the scanner and assign
//the value to the candyArray element at position i.
candyNames[i].readLine(numNames);
System.out.println("Adding " + candyNames[i]);
}
There is no readLine() method in String class . Replace candyNames[i].readLine(numNames) with candyNames[i]=sc.nextLine();
The method nextLine() is only available on the scanner. So if you ever need to call it, you need to do a:
sc.nextLine()
and it will return a string. You need to assign it to something, just like you assign a regular string.
candyNames[i] = "test";
// or
candyNames[i] = sc.nextLine();
Then the rest of the code should work, as you are using candyNames[i] as a string in the print statement.

Java - Scanner not asking for input, and then crashing

I am trying to get input from the Scanner class, but every time I call it, it crashes the entire program. When trying to catch the exception and print the message, nothing shows up, so I am not even sure what the root of the problem is. Some background info is that this class is being called by the main method, which also has a Scanner that was running, but is closed before this class's method is called.
public class UserHandler {
static Scanner userInput1 = new Scanner(System.in);
static void addInterface() throws IOException, FileNotFoundException{
boolean addMore = true;
while(addMore){
System.out.println("Please enter restaurant name: ");
String name = userInput1.next();
if(!FileHandler.containsName(name)){
System.out.println("Name already exists!");
}else{
String[] tags = new String[5];
System.out.print("\nPlease enter tags seperated by spaces: ");
for(int i = 0; i < tags.length; i++){
if(userInput1.hasNext()){
tags[i] = userInput1.next();
}
else{
break;
}
}
FileHandler.addName(name,tags);
}
}
}
}
I have tried several times, and was not able to reproduce this issue. I am assuming it is something to do with syntax, or something that is just not called properly. Either way I have spent quite some time trying to fix it, but to no avail.
I suppose that you get the access to the command-line from the first call to the Scanner(System.in), then you close it and when you try to access it the second time you receive IllegalStateException.
Try to use the same instance of the Scanner(System.in) in both situation.
For more info refer to http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

Java Quick Array Error

I'm having a little trouble with a simple code. It is suppose to be a program where people can add Notes that get stored in an array. I know this code is long but hopefully some can help me out.
public class NoteOrganizer {
int action = 0;
public static Note[] myArray;
public static void addNotes(int num)
{
String note;
String date;
for(int z = 0; z <= num; z++)
{
Scanner getLi = new Scanner(System.in);
System.out.println("Please enter a note (max 140 characters): \n");
note = getLi.nextLine();
System.out.println("Please enter a date:\n");
date = getLi.nextLine();
Note test = new Note();
test.id = z;
test.myNote = note;
test.date = date;
myArray[z] = test; // THE ERROR IS IN THIS LINE, NOT THE LINE MENTIONED BEFORE
}
}
public static void main(String[] args)
{
int action = 0;
int y = 0;
Scanner getLi = new Scanner(System.in);
System.out.println("Please press 1 to add notes, 2 to delete notes or 3 to view "
+ "all notes:\n");
action = getLi.nextInt();
if(action == 1)
{
System.out.println("How many notes would you like to add: \n");
int d = getLi.nextInt();
//myArray = new Note[d];
addNotes(d);
//System.out.println(myArray[0].print());
}
else if(action == 3)
{
System.out.println(Arrays.toString(myArray));
}
}
}
The error that I am getting is the
Exception in thread "main" java.lang.NullPointerException
at note.organizer.NoteOrganizer.addNotes(NoteOrganizer.java:46)
at note.organizer.NoteOrganizer.main(NoteOrganizer.java:95)
Java Result: 1
I commented which line the error was in.
Any help is greatly appreciated.
Thanks,
You haven't initalized your Note array. It seems you've commented out that line for some reason:
//myArray = new Note[d];
public static Note[] myArray;
myArray[z] = test;
You did not initialize the array, so it is still null.
Once you know the length you need (seems to be num), you can do
myArray = new Note[num];
before using the array.
(It seems you already had code to that effect, but it is commented out for some reason).
You've never set myArray to anything, so you can't write into it.
You're trying to automatically expand an array by writing to it, but that doesn't work in Java. However, an ArrayList does support writing at the end (but not any further), and reallocates its internal array as neccessary:
ArrayList<Note> myList = new ArrayList<Note>();
Then, instead of
myArray[z] = test;
use
myList.add(test);
(which will automatically append to the end of the List, wherever it is)
then read from the list as
myList.get(index)
You need initialize your array, I suggest use the class ArrayList, that is like a dynamic array.
myArray = new Note[length];

Categories

Resources