I have some methods that should incorporate user Input. I put the scanner in the main method, but the values entered by the user are not getting returned, nor getting used in the code. How can I turn the user input into a var that can be accessed by the methods?
for example:
import java.util.Scanner;
public class example {
int variableOne;
int variableTwo;
int variableResultFromUserInput;
public int variableResultFromUserInput(int variableOne, int variableTwo) {
this.variableResultFromUserInput = variableOne * variableTwo;
return this.variableResultFromUserInput;
}
public static void main(String[]args) {
example myexample = new example();
Scanner keyboard = new Scanner(System.in);
System.out.println("What's your variable one? ");
variableOne = keyboard.nextInt(); //this is the variable that causes trouble
System.out.println("Whats your variable two?");
variableTwo = keyboard.hasNextInt(); //this is the second variable that causes trouble
System.out.println(myexample.variableResultFromUserInput); //this is also wrong
}
}
So there are a lot of things going on in your code that are incorrect, so I will list out the problems:
myexample
and set the instance variables of variableOne
and variableTwo
, and pass them as a parameter to an instance method. This is completely redundant and serves no purpose, you already have access to them from within variableResultFromUserInput()
. Access them with this.variableOne
(though the this
is optional, but clarifies what is going on).variableOne
and variableTwo
from the static
context of main
using the instance, AKA use myexample.variableOne = keyboard.nextInt()
not variableOne = keyboard.nextInt()
.myexample.variableResultFromUserInput()
with parenthesis and the correct number of parameters accordingly. This variable can be completely removed as it is redundant currently.myexample
should be myExample
, and the class should be Example
.variableTwo = keyboard.hasNextInt();
should be keyboard.nextInt()
not hasNextInt()
. hasNextInt
only checks to see if there is an integer available, but it does not actually read the integer, it returns a boolean
instead that is true
or false
.Here is code with all the changes made below:
public class Example {
int variableOne;
int variableTwo;
public int variableResultFromUserInput() {
return this.variableOne * this.variableTwo;
}
public static void main(String[]args) {
Example myExample = new Example();
Scanner keyboard = new Scanner(System.in);
System.out.println("What's your variable one? ");
myExample.variableOne = keyboard.nextInt(); //this is the variable that causes trouble
System.out.println("Whats your variable two?");
myExample.variableTwo = keyboard.nextInt(); //this is the second variable that causes trouble
System.out.println(myExample.variableResultFromUserInput()); //this is also wrong
}
}