No Such Element Exception while scanning multiple inputs - java

I am new to java programming , and i am trying to learn the usage of classes and objects in java programming , while writing the following code i got an exception
java.util.NoSuchElementException
for sample input
5
1 2 3 4 5
here first line contains number of elements (in this case its 5),and next line contains elements.
while taking input inside the for loop in the class Election ,i am getting exception.
I tried searching on stack Overflow, and other resources too,but still can't figure out how to remove this exception.
import java.io.*;
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
n = input.nextInt();
input.nextLine();
Election obj = new Election(n);
obj.getVotes();
}
}
class Election {
int n,v1,v2,v3,v4,v5,d;
public Election(int n) {
this.n = n;
v1=v2=v3=v4=v5=d=0;
}
public void getVotes() {
Scanner sc = new Scanner(System.in);
for(int i = 0 ; i < 1 ; i++) {
int var = sc.nextInt();
switch(var) {
case 1: ++v1; break;
case 2: ++v2; break;
case 3: ++v3; break;
case 4: ++v4; break;
case 5: ++v5; break;
default: ++d; break;
}
}
}
}

Looks like I'm a bit late, but since your accepted answer is more of comment rather than a solution, I'll post this anyway.
Here is a simple deviation of the code you provided, but reaches the desired result!
I'll walk you through this:
public class MyTest {
public static void main(String[] args) {
//First of all, we need an instance of an Election-type object, so
//that we can call its methods and get votes from users.
Election e = new Election();
//Now we can easily call the method getVotes(), as defined in Election class.
//What happens here, is that the program will 'jump' to the getVotes() method
//and it will execute every line of code in that method. Then it will
//'return' to where it 'left off' in the main() method. Since getVotes()
//is of type 'void', it will not return anything. It will just 'jump' back.
e.getVotes();
//Now, you can use testResult() method, to see the values of the variables.
e.testResult();
}
}
Now, let's take a look at the class Election and how it works.
public class Election {
private final int VOTES_NUM = 1;
private int v1,v2,v3,v4,v5,d;
public Election() {
v1=v2=v3=v4=v5=d=0;
//print now, just to show that all variables = 0
testResult();
}
//Simple method that prints value of each variable. We use this for testing
public void testResult(){
System.out.println("v1 = "+v1);
System.out.println("v2 = "+v2);
System.out.println("v3 = "+v3);
System.out.println("v4 = "+v4);
System.out.println("v5 = "+v5);
System.out.println("d = "+d);
}
private int getInput(){
//First of all, we need a Scanner to take user input.
//You do that in your own code too. We simply move it in this method instead.
Scanner input = new Scanner(System.in);
//You also need variable to hold the user input.
//(Always give meaningful names to all entities)
int userInput;
System.out.print("Please enter vote number here: ");
//the next part has to be in a try-catch block,
//to avoid exceptions like InputMismatchException, etc..
try{
//Get user input
userInput = input.nextInt();
}
//If user enters letter, or symbol, or something else that isn't an integer,
//then inform them of the mistake they made and recursively call this method,
//until they get it right!
catch (InputMismatchException ime){
System.out.println("Please enter only a single number");
return getInput();
}
//If all goes well, return the user input
return userInput;
}
public void getVotes() {
//'VOTES_NUM' is a constant that defines the times the
//loop will iterate (like Macros in 'C')
for(int x=0; x<VOTES_NUM; x++)
int n = getInput();
//then let the switch statement increment one of the variables
switch(userInput) {
case 1: ++v1; break;
case 2: ++v2; break;
case 3: ++v3; break;
case 4: ++v4; break;
case 5: ++v5; break;
default: ++d; break;
}
}
}

I think the code that you posted is missing. The code you posted is working properly and I achieved to get exception only when I wrote input.close() before the obj.getVotes(). When you want to close scanners you should do this after code finishes. Thus, if you close input after the obj.getVotes() you shouldn't get any error.

I tried running your code in a short main class, and I am not getting any exception. This is how I ran your method:
public static void main(String...args){
Election election = new Election(10);
election.getVotes();
System.out.println(election.v1);
System.out.println(election.v2);
System.out.println(election.v3);
System.out.println(election.v4);
System.out.println(election.v5);
System.out.println(election.d);
}
My input was 1 2 3 4 5 6 7 1 2 2 and the console output was:
2 // v1
3 // v2
1 // v3
1 // v4
1 // v5
2 // d
I did make a small change to your program. In the for loop inside the getVotes() method, I changed the condition to i<n (instead of i<1 in your posted code)

Related

How to validate input in my Java program and add the option for the user to run the program again or exit it?

So I have an assignment in my CISP 1 class that requires me to create a program that displays a bar chart comprised of asterisks based on the amount of sales 5 different stores have had. I've got a base made, but I still want to add a loop that validates the input from the user(i.e. throws an error when the user tries to enter a negative number), and I want to add the option to run the program or exit it. I'm just a little lost on how to do all of that, so I figured I'd reach out on this website and ask. I know a lot of this code could be simplified with arrays, but we haven't started studying that yet - so I'm afraid to be messing with something I don't fully understand. Below is my code:
import java.util.Scanner;
public class BarChart
{
public static void main(String[] args)
{
int store1, store2, store3, store4, store5;
Scanner keyboard = new Scanner(System.in);
System.out.println("This program will display a bar chart " +
" comprised of astericks based on five different stores' " +
"sales. 1 asterick = $100 in sales.");
System.out.print("Enter today's sales for store 1: ");
store1 = keyboard.nextInt();
System.out.print("Enter today's sales for store 2: ");
store2 = keyboard.nextInt();
System.out.print("Enter today's sales for store 3: ");
store3 = keyboard.nextInt();
System.out.print("Enter today's sales for store 4: ");
store4 = keyboard.nextInt();
System.out.print("Enter today's sales for store 5: ");
store5 = keyboard.nextInt();
System.out.println("Sales \t Bar Chart");
System.out.println("----- \t ---------");
System.out.print("\nStore 1: ");
for (int num = 0; num < store1; num += 100)
{
System.out.print("*");
}
System.out.print("\nStore 2: ");
for (int num = 0; num < store2; num += 100)
{
System.out.print("*");
}
System.out.print("\nStore 3: ");
for (int num = 0; num < store3; num += 100)
{
System.out.print("*");
}
System.out.print("\nStore 4: ");
for (int num = 0; num < store4; num += 100)
{
System.out.print("*");
}
System.out.print("\nStore 5: ");
for (int num = 0; num < store5; num += 100)
{
System.out.print("*");
}
}
}
I've tried adding if statements each time the user is asked to enter a sales amount, but that didn't work.
I still want to add a loop that validates the input from the user(i.e.
throws an error when the user tries to enter a negative number)
Here's a quick example that shows how to ask again when an invalind number is entered:
do {
System.out.print("Enter today's sales for store 1: ");
store1 = keyboard.nextInt();
if (store<0) {
System.out.println("Sales must be non-negative!");
}
while (store<0);
I want to add the option to run the program or exit it.
This would be similar to the do { ... } while( ... ); above except you'd put the whole program from below the Scanner line inside the body of the do loop. Then you just ask at the bottom if they want to start over and write your conditional statement in the while portion appropriately.
pls take the time to read through
Solution to the problem
do-while loop
What you're looking for is a while loop that this answer suggests, however you can specify whether to force the user to retry, or break the program and throw an error.
If you'd like to make the user retry and not throw an error that makes the program break, possibly with a retry message every time the user inputs negative numbers, you can use a do-while loop. The do-while loop will execute as "do this then check" rather than the while loop being "check than do this" (you can ensure that your code is more concise this way).
The do-while loop version:
int input; // Declare the variable to be initialized inside the do {} block.
int storeSales; // You can just relax and declare here.
do { // This is the start of the do-while loop
System.out.print("..."); // Your prompt goes here
storeSales = scanner.nextInt(); // Grabbing input from the user
if (storeSales < 0) { // Checking if the input is smaller than 0
System.out.print("..."); // Your message when input is invalid
}
} while (storeSales < 0); // The condition goes here
The caveat of the do-while loop for situations like this is for having conditions in the while loop that the do block will be always executed at least once, requires a variable that isn't initialized first but initialized in the loop itself. Initializing a "user input" variable but then giving it a value of "value that makes a statement work" makes the code awkward and dirty.
while loop
The while loop version will look like this:
int storeSales = -1; // You have to initialize first here, since the while is checked first.
while (storeSales < 0) { // Awkward!
System.out.print(""); // Your prompt goes here
storeSales = scanner.nextInt(); // Grabbing input from the user
if (storeSales < 0) { // Checking if the input is smaller than 0
System.out.print(""); // Your message when input is invalid
}
}
Exceptions
If instead, you'd like to break the program when the input is invalid (smaller than 0):
Introducing the throw statement:
Try this code out:
public class BarChart {
public static void main(String[] args) {
System.out.println(5 / 0);
}
}
You'll yell at me: WTF is this, you're making a program that throws ArithmeticException runtime exception! Division by 0 doesn't make sense!
Well, that's the point. Exceptions in Java are those that happen during runtime because of some condition that doesn't have to do with syntax, clear mistakes like String x = 0, etc. That's the kind of exception you're looking for. To throw such an error similar to the example above , use the throw statement and don't use a loop:
int storeSales = scanner.nextInt();
if (storeSales < 0) {
// Since the exception is related to math, you can use something like ArithmeticException. Your choice though.
throw new ArithmeticException(); // An exception is also an object, so you initialize it that way.
}
CAVEAT, Java doesn't expect exceptions in the first place, and so you have to declare that your method throws exceptions. Even main(). And when you call OTHER methods that ALSO have exceptions, you either have to handle them with a try-catch block, or leave it and add the exceptions to the method definition. But that's for another day I guess.
General improvements
You're doing the same thing, same code, same names (essentially), same print() statements a hard-coded 5 times! You can use a for loop. Unless your names have to be unique and declared separately (which I digress, you names are literally store1, store2, store3, etc.) you can just use a general, reinitialized variable name in every iteration of the for loop.
You can also scan the user input about how many stores (instead of hard-coding 5) to show the data, to make the program completely soft-coded and dynamic (The assignment probably doesn't require you this, refactor the code to your needs)
This code below will be grabbing the user input, then printing it out INSTANTLY AFTER. Now that I look at your solution, maybe it was right after all to define separate variables instead of putting the input in an array, since you want all the input at once then print everything at once.
Here's how it goes:
// You'd want to reformat the code to your preference.
import java.util.Scanner;
public class BarChart {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int storeCount = scanner.nextInt();
for (int i = 0; i < storeCount; i++) { // A loop that repeats 5 times.
// Choose one of the three solutions above and insert them here, I choose the do-while since it's the cleanest
int storeSales;
do {
// You can "concatenate" strings (numbers becomes themselves but in text)
System.out.print("Enter today's sales for store " + (i + 1) + ": ");
storeSales = scanner.nextInt();
if (storeSales < 0) {
System.out.print("Sales cannot be negative, please try again");
}
} while (storeSales < 0);
// Now that the storeSales value has been definitely initialized (or you chose the exceptions solution, I don't blame you) the printing goes here.
System.out.println("Store " + (i + 1) + "'s sales:");
for (int j = 0; j < storeSales; j += 100) {
System.out.print("*");
}
System.out.println();
}
}
}
There's not much to do with your code otherwise, since without the use of arrays, the best you can do is define separate variables, then having a method or two (a reusable piece of code with a name) to do the inputting and printing job for you to make the code cleaner and less repetitive.
In the end, just choose one of the three solutions and apply them to each of your variables. Your code is quite good (if it's intended this way). CHEERS!
oh my god someone read till the end of the post i love you
Scanner keyboard = new Scanner(System.in); // initialize scanner
while (true) { // infinite loop starts
<Do something...> // here you can do the things you need to do (e.g., change variables or record input)
if (condition) { // condition for exiting the loop (e.g., input of positive number)
break; // exiting infinite loop
} // end of IF statement
} // end of WHILE statement
You can use it as separate method and validate each input. It will not let the user to proceed until the valid value will be inputted.

How to come back to menu?

I am trying to create an issue tracking System, but I am having a bit of a problem, every time I run the code, it does not come back to the menu, it just loops. I want my code to come back to the menu whenever i describe my issue.
package com.company.TrackingSystem;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
ArrayList<TrackingSystem> tracker = new ArrayList<>();
Main myApp = new Main();
myApp.menu();
System.out.print("Select option >> ");
int option = in.nextInt();
switch (option){
case 1:
myApp.CreateIssue(tracker);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Invalid choice...!");
break;
}
}
private ArrayList<TrackingSystem> CreateIssue(ArrayList<TrackingSystem> tracker){
String issueCreator;
String a = " ";
boolean is = true;
do {
System.out.println("*** Create an Issue***");
System.out.println("Describe your Issue: ");
issueCreator = in.nextLine();
}while (is);
TrackingSystem ts = new TrackingSystem(issueCreator,false);
tracker.add(ts);
return tracker;
}
private void menu() {
boolean is = true;
System.out.println("---Menu---");
System.out.println(
"1.Create new Issue\n" +
"2.Mark Issue as solved\n" +
"3.View unsolved Issues\n" +
"4.View solved Issues\n" +
"5.Exit\n"
);
}
}
My tracking class
package com.company.TrackingSystem;
public class TrackingSystem {
private String createIssue;
private boolean issueSolved;
public TrackingSystem(String createIssue, boolean issueSolved) {
this.createIssue = createIssue;
this.issueSolved = issueSolved;
}
public String getCreateIssue() {
return createIssue;
}
public void setCreateIssue(String createIssue) {
this.createIssue = createIssue;
}
public boolean isIssueSolved() {
return issueSolved;
}
public void setIssueSolved(boolean issueSolved) {
this.issueSolved = issueSolved;
}
}
Example output:
---Menu---
1.Create new Issue
2.Mark Issue as solved
3.View unsolved Issues
4.View solved Issues
5.Exit
Select option >> 1
*** Create an Issue***
Describe your Issue:
*** Create an Issue***
Describe your Issue:
as
*** Create an Issue***
Describe your Issue:
sa
*** Create an Issue***
Describe your Issue:
as
Let's look at this function:
private ArrayList<TrackingSystem> CreateIssue(ArrayList<TrackingSystem> tracker){
String issueCreator;
String a = " ";
boolean is = true;
do {
System.out.println("*** Create an Issue***");
System.out.println("Describe your Issue: ");
issueCreator = in.nextLine();
}while (is);
TrackingSystem ts = new TrackingSystem(issueCreator,false);
tracker.add(ts);
return tracker;
}
Pay special attention to the loop condition: while(is). You declare bool is = true; but you never change it to false inside the loop. This means the loop will continue forever.
To fix this, you have to make some decisions. First, do you really want to continue looping here? Is your intention to allow the user to enter as many issues as they want? Or do you want to create only a single issue then return to the menu. If the former, then you need to figure out how the user will tell the program that they are finished entering issues. You can use this to stop the loop. If the later, then just remove the loop.
Now let's look at main():
public static void main(String[] args) {
ArrayList<TrackingSystem> tracker = new ArrayList<>();
Main myApp = new Main();
myApp.menu();
System.out.print("Select option >> ");
int option = in.nextInt();
switch (option){
case 1:
myApp.CreateIssue(tracker);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Invalid choice...!");
break;
}
}
Even after you solve the problem with your code to create an issue, you will run the program and it will exit after one action. This is because you do not loop in main(). You need to add a loop here that repeats the following steps:
Print the menu.
Get the user's choice.
Perform the action for that choice
Repeat to step 1.
Each of these steps can be a method so that you can keep main() very short. Note how the first 3 steps are inside a loop. I think this is what you were trying to do with the loop for creating a new item, but somehow put the loop in the wrong place. As you can see here, by writing out the steps in words, we get a clear idea of how to organize the code. Doing this is a great tool when writing a computer program.

java using NetBeans IDE 8.0.2

I am having trouble clearing the following error '(' or '[' expected on the second line of case 2 and case 3. The code I have written is newAnimal.displayInfo();
I am not sure why I get this error on case 2 and 3 but not case 1. Not sure what I am doing wrong. Any assistance/guidance will be appreciated.
Here is what the code looks like:
package animalinfo;
import java.util.Scanner;
public class AnimalInfo
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
Scanner input = new Scanner (System.in);
Animal newAnimal;
int quit = 4;
while(-4 != quit);
{
System.out.println("\n1) Camel" +
"\n2)Penguin" +
"\n3) Tortoise" +
"\n4) Exit Program.");
System.out.print("Please select an amimalfrom the list.");
int choice = input.nextInt();
switch (choice)
{
case 1:
newAnimal = new Camel();
newAnimal.displayInfo();
break;
case 2:
newAnimal = new Penguin
newAnimal.displayInfo();
break;
case 3:
newAnimal = new Tortoise
newAnimal.displayInfo();
break;
case 4:
System.out.println ("Thank you for making your selections.");
break;
}
}
}
}
It seems like you're missing parentheses after creating the new objects. So this:
newAnimal = new Penguin
should become this:
newAnimal = new Penguin();
This is because you're setting newAnimal to a new instance of a Penguin object, and to create that new instance you must call the constructor of the Penguin class to create the object.
Also, as Jurko stated, your while loop is set up incorrectly.
while(-4 != quit);
You must remove the semicolon, otherwise the loop will indefinitely run without executing the code you have underneath it. The correct syntax for a while loop is
while (-4 != quit) {
// Code to repeat here
}
while(-4 != quit);
Get rid of the semicolon, should just be
while (-4 != quit)
{
/*Code here*/
}
and yes, when you have new Penguin and new Tortoise, you are missing the parentheses and semicolon

java return to specific point in program

I have the next question. I have the program which has the structure:
loadContext();
showCategories(input);
showProjects(input);
showdetails();
On each step me as a user has the ability to jump to previous step. For example I press 0 and program returns to previos step. Press 1 - program starts from the very beginning. Is there any instruments in Java to come to specific point?
EDIT:
I have here the console application. Main method looks like:
loadContext();//Loads categories
showCategories(input);//shows available categories and ask for which category to show
showProjects(input);// shows all projects inside selested category and select which project to show in details
showdetails();//show selected project
Now I want to set option. For example, in showProjects(input) put 0 and see again categories, select it and see category. In showdetails() select 0 and get back to show categories, select one and so on.
You can do something like this:
Wrap all your four methods in another method:
private void programStart(){
loadContext();
showCategories(input);
showProjects(input);
showdetails();
}
Then have a method like this:
private void processUserInput(int selOption) {
if(selOption == 0){
showCategories();
}
else if(selOption == 1){
programStart();
}
else{
System.out.println("Unsupported option");
}
}
At end of each of your methods where you want to have this option available:
a. Read option from users
b. Call processUserInput(input) with input
What about a switch statement inside a while-loop? Gives the user the ability to select the step to jump to. This is the instrument for any language, and not just Java, to get to any specific point.
I have used java.util.Scanner since you want it to be a console application, although in 2015 we tend to rather use graphical user interfaces or Web pages in order to do the job:
import java.util.Scanner;
public class BackNForth {
private static int input;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("select: ");
int sel = Integer.parseInt(s.nextLine());
while (sel >= 1 && sel <= 4) {
switch (sel) {
case 1:
loadContext();
break;
case 2:
System.out.print("Cat input: ");
input = Integer.parseInt(s.nextLine());
showCategories(input);
break;
case 3:
System.out.print("Pro input: ");
input = Integer.parseInt(s.nextLine());
showProjects(input);
break;
case 4:
showdetails();
break;
}
System.out.print("select: ");
sel = Integer.parseInt(s.nextLine());
}
}
private static void loadContext() {
System.out.println("loadContext");
}
private static void showCategories(int input) {
System.out.println("showCategories " + input);
}
private static void showProjects(int input) {
System.out.println("showProjects " + input);
}
private static void showdetails() {
System.out.println("showdetails");
}
}

What is the format of calling a method from another class?

If I would like to call a method from another class to input it into the current class that I am working on, how do I format it to call the method? How is the code written to call for the method. Currently I have my floats array that is a method? written in another class and I would like to call for the function to be inputed into the class that I am working on. I honestly don't mean to sound ignorant but I am having hard tie trying to grasp how java works. Thanks.
This is what i put. The float array and the name = the name of the class? I am pretty sure it is incorrect because I am getting an error that myPickNumbers cannot be resolved.
float[] myFloats = myPickNumbers.pickNumbers();
I am trying to take this:
import java.util.InputMismatchException;
import java.util.Scanner;
public class pickNumbers {
Scanner readInput = new Scanner(System.in);
float [] pickNumbers(int choice){
float []myFloats = new float[2];
do { //do loop will continue until user enters correct response
System.out.print("Please enter 2 numbers separated by a space in the formats of floats: "); //will prompt user to enter 2 floats
try {
myFloats[0] = readInput.nextFloat(); //will read first float entered
myFloats[1] = readInput.nextFloat(); //will read second float entered
if (choice == 4 && myFloats[1] == 0.0f) {
System.out.println("Cannot complete calculation. Cannot divide by 0, please try again.");
myFloats[0] = myFloats[1] = 0.0f;
continue;
}
break;
} catch (final InputMismatchException e) {
System.out.println("You have entered an invalid input. Try again.");
readInput.nextLine(); // discard input that is not a float
continue; // loop will continue until the correct answer is found
}
} while (true);
return myFloats;
}
}
And put it into this:
public class Calculator {
public static void main(String[] args) {
String inputOperation;
String operatingWord[] = { "adding", "subtracting",
"multiplying", "dividing" };
//array of operations to display to user
Selection mySelection = new Selection();
String menu = "Welcome to John Doe's Calculator" //next line print out line for welcome
+ "\n 1. Addition"//next line option 1 for addition
+ "\n 2. Subtraction" //next line option 2 for subtraction
+ "\n 3. Multiplication" //next line option 3 for multiplication
+ "\n 4. Division" //next line option 4 for division
+ "\n 5. Exit\n"
+ "====================================\n\n"; //next line option 5 for exit then leave a blank line
Symbol.newSymbol(menu);
Symbol.displaySymbol();
while (!(inputOperation = mySelection.selectionOne()).equals("5"))
Symbol.newSymbol("\n");
Symbol.displaySymbol();
float[] myFloats = myPickNumbers.pickNumbers();
You are trying to use a variable, myPickNumbers that you neither declare nor initialize. You must first declare it and initialize it before you can use it:
pickNumbers myPickNumbers = new pickNumbers();
You should first declare a new pickNumbers object
pickNumbers myPickNumbers = new pickNumbers();
Then you can call the pickNumbers() method but you have to include a parameter of type int e.g
float[] myFloats = myPickNumbers.pickNumbers(5)

Categories