13 Replies - 453 Views - Last Post: 29 June 2020 - 02:46 PM Rate Topic: -----

#1 flyingKakapo   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 21
  • Joined: 11-April 20

NoSuchElementException because of Scanner. Why is this error occuring?

Posted 08 May 2020 - 02:11 PM

Alright so I have this code below. In my main function, I am getting a NoSuchElementException for my scanner but I'm just at a total loss as to why. I tried debugging it but in Eclipse I don't understand whats all happening within the Scanner class when I go into it. I tried my loop as a while loop, I changed it to a do while loop manipulating where "userTask" was, but nothing is fixing it. I set userTask to a default value of 2 and found that I got the same error in the test1.getData(test1) section of my code, but again, I just cannot for the life of me figure out what's going wrong.

Here is the total error I get currently:

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at cs256final.InventoryApp.main(InventoryApp.java:27)

				
			else if (userTask == 2)
				{
					test1.getData(test1);
					invCollection.add(test1);
					System.out.println(invCollection.get(0));
					System.out.println();

				}



package cs256final;
import java.util.Scanner;
import java.util.ArrayList;

public class InventoryApp
{

	public static void main(String args[]) throws java.io.IOException 
	{
		ArrayList<Inventory> invCollection = new ArrayList<>();
		String[] leftColumn = new String[5];
		String[] rightColumn = new String[5];

		Inventory test1 = new Inventory(); //default constructor

		Scanner scanner = new Scanner(System.in);

		int userTask = 0;
	do	{
			System.out.printf("%-20s\n", "Inventory Management Program");
			System.out.println("Main Menu\n");
			System.out.println("1) Display Inventory Records");
			System.out.println("2) Add an Item to Inventory");
			System.out.println("3) Find an Inventory Record (by Part Number)");
			System.out.println("4) Exit Program");

			userTask = Integer.valueOf(scanner.nextLine());
			if (userTask == 1)
				{
					System.out.println();
					for (Inventory inv : invCollection)
						{
							System.out.println(inv);
						}
				}
			else if (userTask == 2)
				{
					test1.getData(test1);
					invCollection.add(test1);
					System.out.println(invCollection.get(0));
					System.out.println();

				}
			else if (userTask == 3)
				{

				}

		} while (userTask != 4);

	}
}




package cs256final;
import java.util.*;

public class Inventory
{
	String partNo;
	String prodDesc;
	int quantity;
	double unitPrice;
	int reorderPoint;
	String[] leftColumn = 
			{
					"Item #:",
					"Description:",
					"Quantity:",
					"Unit Price:",
					"Reorder Point:"
			};

	//constructors

	public Inventory() //default constructor
	{
		partNo = "AA0000";
		prodDesc = "Test Item";
		quantity = 0;
		unitPrice = 5.0;
		reorderPoint = 0;
	}

	public Inventory(String part, String prod, int quant, double price, int reorder) 
	{
		partNo = part;
		prodDesc = prod;
		quantity = quant;
		unitPrice = (Math.round((price * 100.0)) / 100.0); //round to get it to 2 decimal points
		reorderPoint = reorder;
	}

	//setters

	public void setPartNo(String part) 
	{
		partNo = part;
	}

	public void setProductDescription(String product) 
	{
		prodDesc = product;
	}

	public void setQuantity(int quant) 
	{
		quantity = quant;
	}

	public void setUnitPrice(double price) 
	{
		unitPrice = price;
	}

	public void setReorderPoint(int reorder)
	{
		reorderPoint = reorder;
	}

	//getters

	public String getPartNo() 
	{
		return partNo;
	}

	public String getProductDescription() 
	{
		return prodDesc;
	}

	public int getQuantity() 
	{
		return quantity;
	}

	public double getUnitPrice()
	{
		return unitPrice;
	}

	public int getReorderPoint()
	{
		return reorderPoint;
	}

	public String getIntAsString(int num) 
	{
		return Integer.toString(num);
	}

	public String getDoubleAsString(double num) 
	{
		return Double.toString(num);
	}

	/*
	 * This is the base method that prints out the organized lists
	 * procured from the custructors.
	 */

	public void showPart()
	{
		/*
		 * had to adjust show part to be a getter method because I couldn't
		 * place the whole array as an element within my arraylist on the 
		 * main method since void cannot convert to string. performing it
		 * this way allows for the entire array to be placed in as one element
		 * within each index.
		 */
		String[] leftColumn = {"Item #:", "Description:", "Quantity:",
				"Unit Price:", "Reorder Point:"};
		String[] rightColumn = {getPartNo(), getProductDescription(), 
				getIntAsString(quantity), getDoubleAsString(unitPrice), 
				getIntAsString(reorderPoint)};

		int i = 0; //incrementor for the second array
		for (String lc : leftColumn)
			{
				System.out.printf("%-15s%-10s%n", lc, rightColumn[i++]); //prints both arrays side by side
			}

	}

	//booleans

	public boolean checkDescrip(String str)
	{
		if (str.length() > 5 && str.length() < 26)
			{
				return true;
			}
		else
			{
				return false;
			}
	}

	public boolean checkQty(int num)
	{
		if (num > 0 && num < 1000)
			{
				return true;
			}
		else
			{
				return false;
			}
	}

	public boolean checkPrice(double num)
	{
		if (num >= 0.0)
			{
				return true;
			}
		else
			{
				return false;
			}
	}

	public boolean checkReorder(int num)
	{
		if (num > 0 && num < 500)
			{
				return true;
			}
		else
			{
				return false;
			}
	}

	//returns boolean value if the part number meets the parameters
	public boolean checkPartNo(String str)
	{
		Character.isLetter(str.charAt(0));
		if (str.length() == 6 
				&& 
				Character.isLetter(str.charAt(0)) 
				&& 
				Character.isLetter(str.charAt(1)))
			{
				return true;
			}
		else
			{
				return false;
			}
	}

	/*
	 * capitalizes the letters in the string by splitting into an
	 * array, then capitalizing the characters, the putting back together
	 */
	public String capitalize(String str)
	{
		String[] array = new String[6];

		for (int i = 0; i < array.length; i++)
			{
				//splits up the entire string, then force capitalizes the letters
				array[i] = String.valueOf(Character.toUpperCase(str.charAt(i)));
			}

		//combines the whole split array
		str = array[0] + array[1] + array[2] + array[3] + array[4] + array[5];

		return str;

	}

	//Asks for user input to apply to constructor and create new inventory object
	public String getData(Inventory inv)
	{
		Scanner scanner = new Scanner(System.in);
		System.out.println("Provide the item #:"
				+ "\n6 characters long, the first 2 are Letters, last 4 are Numbers.");
		do
			{
				this.partNo = scanner.nextLine();
			} while (inv.checkPartNo(this.partNo) == false); //checks to verify if it meets the parameters set

		this.partNo = capitalize(this.partNo); //capitalizes the values in case they weren't

		System.out.println("Provide the item description: ");
		do
			{
				this.prodDesc = scanner.nextLine();
			} while (inv.checkDescrip(this.prodDesc) == false);

		System.out.println("Provide the item quantity: ");
		do
			{
				this.quantity = scanner.nextInt();
			} while (inv.checkQty(this.quantity) == false);

		System.out.println("Provide the item price: ");
		do
			{
				this.unitPrice = scanner.nextDouble();
			} while (inv.checkPrice(unitPrice) == false);
		System.out.println("Provide the quantity reorder point: ");
		do
			{
				this.reorderPoint = scanner.nextInt();
			} while (inv.checkReorder(this.reorderPoint) == false);


		scanner.close();
		return "";
	}

	public String toString()
	{
		return String.format("%-15s%-15s\n%-15s%-15s\n%-15s%-15d\n%-15s%-15.02f\n%-15s%-15d",
				this.leftColumn[0], this.partNo,
				this.leftColumn[1], this.prodDesc,
				this.leftColumn[2], this.quantity,
				this.leftColumn[3], this.unitPrice,
				this.leftColumn[4], this.reorderPoint);
	}


}





I forgot to add. When I was using scanner.nextInt(), I was getting more errors so I though .nextLine() may be closer to fixing it. Here is what I get with .nextInt():

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 cs256final.InventoryApp.main(InventoryApp.java:27)

Is This A Good Question/Topic? 0
  • +

Replies To: NoSuchElementException because of Scanner. Why is this error occuring?

#2 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 832
  • View blog
  • Posts: 6,392
  • Joined: 25-December 13

Re: NoSuchElementException because of Scanner. Why is this error occuring?

Posted 08 May 2020 - 02:20 PM

How are you executing the program? What environment is it in?
IDE, command prompt or ?
Was This Post Helpful? 0
  • +
  • -

#3 flyingKakapo   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 21
  • Joined: 11-April 20

Re: NoSuchElementException because of Scanner. Why is this error occuring?

Posted 08 May 2020 - 02:33 PM

View PostNormR, on 08 May 2020 - 02:20 PM, said:

How are you executing the program? What environment is it in?
IDE, command prompt or ?


I'm doing everything in Eclipse. I'm using JRE 1.8.
Was This Post Helpful? 0
  • +
  • -

#4 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 832
  • View blog
  • Posts: 6,392
  • Joined: 25-December 13

Re: NoSuchElementException because of Scanner. Why is this error occuring?

Posted 08 May 2020 - 02:43 PM

Don't ever close System.in. That terminates all input from that device.

This post has been edited by NormR: 08 May 2020 - 02:45 PM

Was This Post Helpful? 1
  • +
  • -

#5 flyingKakapo   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 21
  • Joined: 11-April 20

Re: NoSuchElementException because of Scanner. Why is this error occuring?

Posted 08 May 2020 - 02:44 PM

View PostNormR, on 08 May 2020 - 02:20 PM, said:

How are you executing the program? What environment is it in?
IDE, command prompt or ?


I figured it out! I had a scanner declared and closed inside my "getData" method within my Inventory class. Turns out that closes out the scanner in my main method as well for some reason (I'm assuming?). That is why I was getting the error in the getData method with the userTask set as a constant number without a scanner. I just decided to try it with a simple print statement.

Now it's successfully looping as I intended! Thanks for taking the time to look into it!
Was This Post Helpful? 0
  • +
  • -

#6 flyingKakapo   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 21
  • Joined: 11-April 20

Re: NoSuchElementException because of Scanner. Why is this error occuring?

Posted 08 May 2020 - 02:51 PM

View PostNormR, on 08 May 2020 - 02:43 PM, said:

Don't ever close System.in. That terminates all input from that device.


I was never aware of that. I honestly think this was the first time I ever actually put a scanner in a method and I thought because it was giving me the symbol "scanner not closed" that I should close it in the method. Regardless, I appreciate you looking it over!
Was This Post Helpful? 0
  • +
  • -

#7 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3698
  • View blog
  • Posts: 16,952
  • Joined: 20-September 08

Re: NoSuchElementException because of Scanner. Why is this error occuring?

Posted 09 May 2020 - 02:59 AM

Quote

and I thought because it was giving me the symbol "scanner not closed" that I should close it in the method.

That's bad advice from the IDE ;) Don't close Scanners opened on System.in

This post has been edited by g00se: 09 May 2020 - 02:59 AM
Reason for edit:: typo

Was This Post Helpful? 0
  • +
  • -

#8 idlewild   User is offline

  • New D.I.C Head

Reputation: 3
  • Posts: 35
  • Joined: 19-June 20

Re: NoSuchElementException because of Scanner. Why is this error occuring?

Posted 28 June 2020 - 12:47 AM

try to use the format every time ( below ) to avoid such errors

int jkl=new Scanner(System.in).nextInt();


or

String str =new Scanner(System.in).nextLine();


or as such
Was This Post Helpful? 0
  • +
  • -

#9 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 832
  • View blog
  • Posts: 6,392
  • Joined: 25-December 13

Re: NoSuchElementException because of Scanner. Why is this error occuring?

Posted 28 June 2020 - 05:03 AM

Creating new instances of Scanner with System.in is not a good idea. For example if there is more data that has not been read out of Scanner's buffer, it will be lost.
Was This Post Helpful? 2
  • +
  • -

#10 idlewild   User is offline

  • New D.I.C Head

Reputation: 3
  • Posts: 35
  • Joined: 19-June 20

Re: NoSuchElementException because of Scanner. Why is this error occuring?

Posted 28 June 2020 - 06:32 PM

View PostNormR, on 28 June 2020 - 05:03 AM, said:

Creating new instances of Scanner with System.in is not a good idea. For example if there is more data that has not been read out of Scanner's buffer, it will be lost.


but is not it a good remedy for simple programs?
Was This Post Helpful? 0
  • +
  • -

#11 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3698
  • View blog
  • Posts: 16,952
  • Joined: 20-September 08

Re: NoSuchElementException because of Scanner. Why is this error occuring?

Posted 29 June 2020 - 02:48 AM

Quote

but is not it a good remedy for simple programs?

No. It's not a remedy for anything because there's not a problem. The only problem occurs from doing it
Was This Post Helpful? 1
  • +
  • -

#12 mattpyguy   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 25-June 20

Re: NoSuchElementException because of Scanner. Why is this error occuring?

Posted 29 June 2020 - 02:20 PM

View PostNormR, on 28 June 2020 - 05:03 AM, said:

Creating new instances of Scanner with System.in is not a good idea. For example if there is more data that has not been read out of Scanner's buffer, it will be lost.


Now I'm confused too.
In the book I'm working through it has suggested the format:

Scanner keyboard = new Scanner(System.in);
keyboard = nextInt();



Is that the format you're saying to never use?

Sorry, I mis-typed that and can't figure out if I can edit. Sorry.

Scanner keyboard = new Scanner(System.in);
int number = keyboard.nextInt();


Was This Post Helpful? 0
  • +
  • -

#13 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 832
  • View blog
  • Posts: 6,392
  • Joined: 25-December 13

Re: NoSuchElementException because of Scanner. Why is this error occuring?

Posted 29 June 2020 - 02:31 PM

Sorry, I meant to say was that creating a new instance everytime you want to read user input is wrong. It should only be done once and then reused as needed.

What you posted would be OK.
Was This Post Helpful? 0
  • +
  • -

#14 mattpyguy   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 25-June 20

Re: NoSuchElementException because of Scanner. Why is this error occuring?

Posted 29 June 2020 - 02:46 PM

Ok, that makes sense then. I open one scanner keyboard and continue to use the same scanner every time I need input.
Thanks for the clarification.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1