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)
Related
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)
I have a problem with my program is not with the code is how I am going to do it that's the confusing part that I am stuck with. just to let you know I am a basic java coder I do not understand complicated stuff so bear in mind that my code isn't the best.
----------------------------------------------------------- program explaintion-----------------------------------------------------------------
let's get into the point of explaining how it works before I show you my problem, ok when you execute the program it prompts you a sort of like a menu in a video game but it's a text-based, it shows you different options like enter player details, play the math game show score and then quit. enter player details it tells player 1 to enter he/she name and then tells another one to input he/she player name then prompts you back to the menu. play the math game is where a player 1 is asked to input he/she math equation after that player 2 has to solve it if he gets it right he gets 10 points if no the player gets no points at all. then repeats for another player to input he/she math equation then prompts you back to the menu. show scores it shows who got the most scores in the math game it calculates who's got the most if both of them got the same score then means a tie then prompts you back to the menu. and the last thing the quit option when you choose that option it stops the program. if the player chooses a wrong choice he gets an error message and puts you back to the menu
ok here is the first class called menu and other class which is connected with menu called game factions
menu:https://gist.github.com/LOLMEHA/86ff28b038d85030e346785e953644e0
gamefactions:https://gist.github.com/LOLMEHA/f05a51e07c8823a0e65cebbf81cc52ef
so this section of code that I have trouble fingering it out myself
import java.util.*;
public class Gamefunctions // this is a core when player choosess one of these options from the menu
{
String[] player =new String[2];
double scorea = 0; // verribles of all the objects
double scoreb = 0;
int i;
Scanner input = new Scanner(System.in);
double answer = 0;
double numA, numB;
char operator;
char operator2;
boolean quit = false;
double sum1;
double sum2;
public void enterDetails(){ // if player select enter details
for ( i=0;i<2;i++) {// tell's player to input he/she's name and stores them
int c=i;
System.out.println("Welcome to the maths quiz game please input player name "+c++);
player[i] = input.next();
}
}
public void mathGame(){ // if player select enter details
System.out.println("Please enter your equation please "+player[0]+" press enter for each number and mathematical symbol"); // tells the player 1 to input
System.out.println("");
System.out.println("such as for ex input a number or how many you like, then hit enter and input such as /*-+^ hit enter, then input any number one or how many you like ");
String s=input.next();
numA = Double.parseDouble(s); // numa and numb and operator is the aera of player to input he/she equation
operator = input.next().charAt(0);
numB = input.nextDouble();
if () {
if (operator == '+') {// this is if operator is one of these like +-*/^ and then it works out the sum
answer = numA + numB;
}
if (operator == '-') {
answer = numA - numB;
}
if (operator == '*') {
answer = numA * numB;
}
if (operator == '/') {
answer = numA / numB;
}
if (operator == '^') {
answer = Math.pow(numA, numB);
}
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
System.out.println("");
System.out.println(player[1]+"\t solve the equation"); // tells other player to slove the equation
sum2 = input.nextDouble();
if (sum2 == answer){// checks if the answer from the player is good or not if its good he/she gets 10 points if he/she gets it wrong gets no points and shows the right answer so the player learns from his/she mistakes
scoreb = scoreb + 10.00;
System.out.println("correct you got 10 points to your score");
System.out.println("");
} else{
System.out.println("incorrect you got no points the correct answer was:"+"" + answer);
}
you know when the program ask to player to input his math eqtion and outputs this and continues with the program and waiting for the user to input
public void mathGame(){ // if player select enter details
System.out.println("Please enter your equation please "+player[0]+" press enter for each number and mathematical symbol"); // tells the player 1 to input
System.out.println("");
System.out.println("such as for ex input a number or how many you like, then hit enter and input such as /*-+^ hit enter, then input any number one or how many you like ");
String s=input.next();
numA = Double.parseDouble(s); // numa and numb and operator is the aera of player to input he/she equation
operator = input.next().charAt(0);
numB = input.nextDouble();
let's say that the player inputs like this 10+10 enter but it will not work since they are stored in numA which is an int, I want to make a error message saying that you can not input like this 10+10 you have to input like this 10 enter + enter 10 enter so it will be able to work
if the player inputs it correctly it will continue the program
so if you have any problems with my explaintion of my plroblem pls ask so I can edit it thank you for time :)
Here’s the bit of your code I’m going to be looking at:
String s = input.next();
numA = Double.parseDouble(s);
operator = input.next().charAt(0);
numB = input.nextDouble();
if (/* Some condition */) {
// Calculate answer
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
First up, a couple nitpicks: Java is not C. You don’t need to declare all your variables at the beginning of your code blocks. numA, numB and operator are never used outside this bit of code, so it makes sense to declare them in here as well.
You’re also using input.next() with Double.parseDouble() once, then input.nextDouble() the next time. Stick to one or the other, it’ll make debugging easier if something doesn’t work properly.
And finally, what happens if someone enters 10 +1 0? The error is silently ignored because the 1 gets picked up as part of the operator string then discarded by charAt(0). A more resilient parsing method here would be to fetch the entire String first, then check for length == 1 before calling charAt(0).
double numA = input.nextDouble();
String operatorString = input.next();
char operator;
if (operatorString.length() == 1) {
operator = operatorString.charAt(0);
} else {
// Handle error
}
double numB = input.nextDouble();
if (/* Some condition */) {
// Calculate answer
} else {
System.out.println("error input like for an example '10' enter '+' enter '10'");
}
Onto your question then: how do we detect an invalid input? Take a look at the documentation for Scanner#nextDouble() (emphasis mine):
public double nextDouble()
Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.
So we know nextDouble() can detect the invalid input for us. It does this in the form of an exception, which we can listen for (or catch) using a try ... catch statement:
try {
double numA = input.nextDouble();
} catch (InputMismatchException e) {
System.err.printf("Invalid input! Expected number, found '%s'.\n", input.next());
}
We could extend this and wrap the entire section of code in a single try ... catch, but then the user would have to start again if they make one mistake. A more user-friendly solution would be this:
double numA;
while (1) {
try {
numA = input.nextDouble();
break;
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected number, found '%s'.\n", input.next());
}
}
Note the even if you don’t print it, the call to input.next() is necessary to prevent an infinite loop.
Now we just need to do something similar for operator:
char operator;
while (1) {
String operatorString;
try {
operatorString = input.next();
if (operatorString.length() != 1) {
throw new InputMismatchException();
}
operator = operatorString.charAt(0);
break;
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected character, found '%s'.\n", operatorString);
}
}
This seems very similar to the previous snippet for a number - let’s try to refactor some of the common code here into a method:
#FunctionalInterface
public interface ScannerGetter<T> {
T apply() throws InputMismatchException;
}
public <T> T getValueFromScanner(ScannerGetter<T> getter, String type) {
while(1) {
try {
return getter.apply();
} catch (InputMismatchException e) {
System.err.printf("Invalid input, try again! Expected %s.");
}
}
}
There’s a lot going on in these few lines. The first part declares a functional interface - this is a basically a custom type of lambda function. We’ll come back to that in a moment.
The method itself (getValueFromScanner()) is a generic method. It allows us to use the same method with different types in place of the generic parameter (T) without duplicating it.
This is how you’d use the above method to retrieve your three inputs:
double numA = this.<Double>getValueFromScanner(() -> input.nextDouble(), "number");
char operator = this.<Char>getValueFromScanner(() -> {
operatorString = input.next();
if (operatorString.length() != 1) {
throw new InputMismatchException();
}
return operatorString.charAt(0);
}, "operator");
double numB = this.<Double>getValueFromScanner(() -> input.nextDouble(), "number");
// Once your code gets here, all three variables will have valid values.
So basically have an Array and am using the Joption input system so the user has to input a int between 1 and 3. Basically how do I use this int I to divide the number of objects in my array? Also not necessary but it would help if you could advise me how do I stop people inputting a number less than 1 and greater than 5.
Rain[] drops = new Rain [3000]; // WANT TO DIVIDE INT INTO ARRAY
import javax.swing.*;
void setup() {
noCursor();
JOptionPane.showInputDialog( "Please enter a number between one and three","2");
}
So can I use the output from this to adjust the number of objects created by my array ?
Java cannot convert between strings and number by itself, you have to use specific functions, just use:
int ans = Integer.parseInt(JOptionPane.showInputDialog(...))
For your other question you may wanna do something like the following:
boolean inputAccepted = false;
while(!inputAccepted) {
try {
int answer = Integer.parseInt(JOption....
// do some other validation checks
if (answer < 1 || answer > 3) {
// tell them it's still a bad number
} else {
// a good value
inputAccepted = true;
}
} catch(NumberFormatException e) {
// input is bad. popup something
// some communication
// saying what you expect the user to enter.
}
... do stuff with good input value
Since you tagged this with processing, I'll assume you're using the Processing language.
Processing has an int() function that converts from a String to an int.
float f = 65.0;
int i = int(f);
println(f + " : " + i); // Prints "65.0 : 65"
char c = 'E';
i = int(c);
println(c + " : " + i); // Prints "E : 69"
More info on this and related functions can be found in the Processing reference.
You could try this
String ans_s = JOptionPane.showInputDialog( "Please enter a number between one and three","2");
int ans = Integer.parseInt(ans_s);
Please wrap this in try{ }catch(NumberFormatException nfe){}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The object that is created by the constructor in the following code can be called multiple times. Have I written the code badly by doing so I hope it is written to the proper conventions
import java.util.Scanner;
/**
* this class uses the scanner to take input from the keyboard
* test if the input is a variable of type double if it is store in a
* variable called numOne then take next input test again for type double
* store in variable numTwo, then add the two variables together in the form
* of variable answer and return to the screen. The user then is asked for
* continuation as Y/N then appropriate action is taken
*/
public class Calc {
/**
* this constructer does not throw InputMismatchException
*/
public Calc() {
Scanner in = new Scanner(System.in); // create scanner object
System.out.println("please enter 1st "
+ "number then press enter"
+ "\nthen enter 2nd number then "
+ "press enter again");
/*test for a double returns true */
boolean myBool = in.hasNextDouble();
/*the actual test for a double*/
if(myBool == false) {
System.out.println("wrong format");
/**
* call constructer and instantiate as new object
* by creating a new object i hope to have overwriten
* the original object stored in memory there by getting
* around the problem of hasNextDouble not allowing the
* scanner to advance
*/
Calc c = new Calc();
} else { // 1st else
double numOne = in.nextDouble(); // keyboard input
/*test for a double returns true */
boolean myBool2 = in.hasNextDouble();
/*the actual test for a double*/
if(myBool2 == false) {
System.out.println("wrong format start again");
/**
* call constructer and instantiate as new object
* there by removing need for InputMismatchException
*/
Calc c = new Calc();
} else { // 2nd else
double numTwo = in.nextDouble(); // keyboard input
double answer = numOne + numTwo; // the maths
for(int i = 0; i<35; i++) { // print pattern
System.out.print("*");
}
System.out.println("\n**** "
+ "Your 1st number is "
+ numOne + " ****");
System.out.println("**** " // print operator
+ " " + "+"
+ " ****");
System.out.println("**** "
+ "Your 2nd number is "
+ numTwo + " ****");
System.out.println("**** " // print line
+ " ______ ****");
System.out.println("**** "
+ "The answer is "
+ answer + " ****");
for(int i = 0; i<35; i++) { //print pattern
System.out.print("*");
}
System.out.println("\nDo you have "
+ "more calculations Y or N");
String reply = in.next(); //keyboard input
if(reply.equalsIgnoreCase("Y")) {
Calc c = new Calc();
} else {
System.out.println("OK bye then");
in.close(); //close scanner
} //end else
} // end 1st else
} // end 2nd else
} // end constructor
public static void main(String[] args) {
Calc c = new Calc(); // call constructor
} // end main
} // end class
// just in case i do something wrong thanks in anticipation Simon.
Calling the constructor from within the same constructor, and without any parameters, looks like a sure way to get infinite loop and stack overflow. So, yes, it's wrong.
And since it doesn't look as if you are doing anything with all the instances of Calc that you create within the constructor, it's pointless.
It is usually seen as bad practice to do any work in a constructor that is not directly related to instantiating that object. Consider moving your logic into another method on the Calc. That way you can use a single instance of Calc, and using fields on that instance you might have better luck overwriting the values your comments mention that you want to overwrite.
As Eran mentioned, your current pattern uses recursive calls, which are prone to stack overflows if not done right. I wouldn't go so far as to say recursive calls are always a bad thing, but you should carefully consider whether that's the best pattern for what you're doing.
Although you (probably) won't get an error, this is bad practice in many ways.
First of all, you should not do any of this in a constructor. A constructor is supposed to create an object or throw an Exception, that's it. If the constructor requires any input, read it in advance and pass it as an argument to the constructor. Constructors are not made for user interaction.
The next point is error handling. If the user makes an invalid input, there is absolutely no need to use recursion. Sure, you won't get a StackOverflowError (unless your user fails a few thousand times), but a loop is a better solution.
System.out.print("Enter a double please: ");
while(!scanner.hasNextDouble()) {
System.out.print("Invalid input. Please try again: ");
scanner.next(); //discard invalid input
}
double input = scanner.nextDouble();
Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.
I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
And continue on with my program, and everything works fine.
Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).
How can I make the code more robust, where it would verify that only an int was entered?
These are the results I'm hoping for:
Lets say the input was:
23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc
Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.
In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
scan.next();
}
int input = scan.nextInt();
Here's a simple example with prompts and comments.
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer: "); // Initial prompt for input
// Repeat until next item is an integer
while (!scan.hasNextInt())
{
scan.next(); // Read and discard offending non-int input
System.out.print("Please enter an integer: "); // Re-prompt
}
// At this point in the code, the user has entered an integer
int input = scan.nextInt(); // Get the integer
// And now you can use the input variable.
Use scan.hasNextInt() to make sure the next input is an int.
I have written an example that ensures that the program will continue only if a number and not an invalid value is entered. Do not worry, I added the desired explanation.
The program asks the user to input a number. A loop ensures that the processing will not go on until a valid number is entered. Before that I have defined a variable "inputAccepted" that has false as default value. If he enters a number, the variable "inputAccepted" is set to true and the program leaves the loop. But if he enters something else than a number, an exception is thrown right in this moment, and the line that sets the variable "inputAccepted" to true will not be executed. Instead a message will be printed out that tells the user that his input is not valid. Since "inputAccepted" could not be set to true, the loop will do the same stuff again until the string can be converted to a number.
You can test the program here.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean inputAccepted = false;
while (!inputAccepted) {
try {
System.out.print("Please enter a number: ");
Integer.valueOf(input.nextLine());
inputAccepted = true;
} catch (NumberFormatException e) {
System.out.println("Not a valid number.");
}
}
System.out.println("Thank you!");
}
}
Just get "anything" and parse it:
Scanner scan = new Scanner(System.in);
Integer number = null;
while (number == null) {
try {
number = Integer.parseInt(scan.next());
} catch (NumberParseException e) {
System.out.println("bad input: " + input);
}
}
Without any code and just in English, I'd say there's two things you have to test or look out for. First that the input is an int, second that the int is within the correct range.
In terms of pseudocode, the first thing to do is make sure it's an int. Declaring an int named "input", I would put a try / catch block, where you try to scan in the user input as an int, with parseInt(). If the try part fails, you know it's not an int and can return an error message.
Then, now that you know that "input" is an int, you can test whether it is less than 1 or more than 150, and return an error message if so!
public class Sample {
/**
* author CLRZ
*/
public static void main(String[] args) {
int a; // variable
Scanner in = new Scanner(System.in); // scans your input
System.out.println("Enter your number's choice:");
int sem1 = in.nextInt(); // reads next integer
if (sem1 == 1) // conditioned if your choice number is equal to 1
System.out.println("Hello World1"); // output wil be Hello World
int b;
System.out.println("Enter your number's choice:");
int sem2 = in.nextInt();
if (sem2 == 2)
System.out.println("Hello World2");
int c;
System.out.println("Enter your number's choice:");
int sem3 = in.nextInt();
if (sem3 == 3)
System.out.println("Hello World3");
}
}