(For a beginner Java class)
The assignment specifies that i only make one Scanner instance, and I need it in more than one method, so i declared it outside of main. I declare an array and try to equate it with a method call, initialCash(), like I would in Python. The problem is if I make the initialCash method static, I can't use Scanner. If initialCash() isn't static, Eclipse is kind enough to tell me that it "cannot make a static reference to the non-static method." (in the money = initialCash(); line)
How do I get around this?
package proj1;
import java.util.Scanner;
public class Project1
{
Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{
int[] money = new int[4];
money = initialCash();
}
public int[] initialCash()
{
int[] initialMoney = new int[4];
while(true)
{
System.out.print("Ones: ");
initialMoney[0] = scanner.nextInt();
System.out.print("Fives: ");
initialMoney[1] = scanner.nextInt();
System.out.print("Tens: ");
initialMoney[2] = scanner.nextInt();
System.out.print("Twenties: ");
initialMoney[3] = scanner.nextInt();
if((initialMoney[0]>=0)&&(initialMoney[1]>=0)&&(initialMoney[2]>=0)&&(initialMoney[3]>0))
{
return initialMoney;
}
else
{
System.out.println("One or more invalid denominations. Try again.");
}
}
}
}
Create an instance of your class and invoke initialCash on that instance from main.
money = new Project1().initialCash();
What PermGenError said would definitely work, or you could make both the initalCash() method and the scanner reference variable static.
In your code, the line
Scanner scanner = new Scanner(System.in);
creates a new Scanner object each time you create an object of type Project1. Whereas if you had written it as
static Scanner scanner = new Scanner(System.in);
It would create a single Scanner instance for use by all classes that refer to this object. In your question you mentioned there has to be exactly one Scanner object, if so this is the way to go.
If you use
money = new Project1().initialCash();
you are creating a new Project1 object as well as a new Scanner object, if you were to reuse the Scanner object by calling another function you cannot as it is tied to that specific instance of Project1, so I'd recommend you make it static, the same with the initialCash function, it is tied to that object instance.
Make the Scanner and the initialMoney method static. This should fix your problem.
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{
int[] money = new int[4];
money = initialCash();
}
public static int[] initialCash()
{
int[] initialMoney = new int[4];
while(true)
{
System.out.print("Ones: ");
initialMoney[0] = scanner.nextInt();
System.out.print("Fives: ");
initialMoney[1] = scanner.nextInt();
System.out.print("Tens: ");
initialMoney[2] = scanner.nextInt();
System.out.print("Twenties: ");
initialMoney[3] = scanner.nextInt();
if((initialMoney[0]>=0)&&(initialMoney[1]>=0)&&(initialMoney[2]>=0)&&(initialMoney[3]>0))
{
return initialMoney;
}
else
{
System.out.println("One or more invalid denominations. Try again.");
}
}
}
Related
I have a trouble about usage of the scanner.
The getUserInput takes as an input the scanner instance and initialise the array of specified size which comes from the scanner. For example: if user puts 3 then the method will create an array of the size 3.
However, it keeps saying that scnr can't converted to int....
Any advice?
public static void main(String[] args)
{
Scanner scnr = new Scanner(System.in);
System.out.println("How many orders were placed Saturday?");
int [] userInput = getUserInput(scnr);
System.out.println("How many orders were placed Sunday?");
int [] userInput = getUserInput(scnr);
System.out.println("How many orders were placed Monday?");
int [] userInput = getUserInput(scnr)
return;
}
}
public static int[] getUserInput(Scanner scnr)
{
int[] userInput = new int[scnr];
return userInput;
}
You have to call a method on Scanner. And because you want an int do it like this:
int[] userInput = new int[scnr.nextInt()];
Here you'll find the API documentation: https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
nextInt() method of Java Scanner class is used to scan the next token of the input as an int
public static int[] getUserInput(Scanner scnr)
{
int[] userInput = new int[scnr.nextInt()];
return userInput;
}
Firstly there are 2 mistakes you have done here.
int [] userInput there are 2 duplicates of this userInput variable.
You are passing an instance of Scanner as a parameter in your getUserInput function.
getUserInput FIX
So in order to create we need to follow a syntax i.e
datatype [] vairable_name = new datatype[size];
Here size can be byte short int but what you did is
datatype [] vairable_name = new datatype[Scanner];
Which is just not the Syntax. You can fix it by taking input as int from the user.
A scanner as a method to do that .nextInt() which converts the input of the user to int if it's in numbers.
Solution is
int[] userInput = new int[scnr.nextInt()];
// This is like the syntax
datatype [] vairable_name = new datatype[Scanner];
Duplicate Variable
You should revise scopes in java, and then you will know why it's an error.
You cannot have the same variable name in the same scope or in the child scope
public static void main(String args[]){
int a = 0;
int a = 1; // <- error cuz a is already difined and is duplicate in the same scope.
}
Similarly
public static void main(String args[]){
int a = 0;
if(true){
int a = 1; // <- error cuz a is already difined and is duplicate in child scope.
}
}
The solution is to change the variable name.
//scnr is now globally available in the class so need to pass it as a parameter
Scanner scnr = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("How many orders were placed Saturday?");
int [] saturdayUserInput = getUserInput();
System.out.println("How many orders were placed Sunday?");
int [] sundayUserInput = getUserInput();
System.out.println("How many orders were placed Monday?");
int [] mondayUserInput = getUserInput()
return;
}
}
public static int[] getUserInput()
{
int[] userInput = new int[scnr.nextInt()];
return userInput;
}
scnr is not an int. It's an isntance of the Scanner class. If you want to read an int from it, you'll need to call:
scnr.nextInt();
It's also better not to pass this as a parameter, but to create the Scanner on class level, so you can use it in all the methods.
I wanted to know the proper way todo a function call of an "Object Array." I'm not sure, my first thought is the scope of the object variable is local to the to function causing the function call error. My second thought is I should have declared the object in main first.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Function Calls
returnObjectArray();
scanner();
userInput(studentInfos,input ); //ERROR HERE is on the function call of Object Array
}
public static Object[] returnObjectArray() {
StudentInfo[] studentInfos = new StudentInfo[2];
return studentInfos;
}
public static Object scanner() {
Scanner input = new Scanner(System.in);
return input;
}
public static Object[] userInput(StudentInfo [] studentInfos, Scanner input) {
int emplid;
double quiz1;
for (int i = 0; i < studentInfos.length; i++) {
System.out.println("Enter student emplid number");
studentInfos[i] = new StudentInfo();
emplid = input.nextInt();
studentInfos[i].setEmplid(emplid);
System.out.println("Enter Quiz one percentage");
quiz1 = input.nextDouble();
studentInfos[i].setQuizScoreOne(quiz1);
System.out.println("Enter Quiz two percentage");
quiz1 = input.nextDouble();
studentInfos[i].setQuizScoreTwo(quiz1);
System.out.println("Enter Quiz three percentage");
quiz1 = input.nextDouble();
studentInfos[i].setQuizScoreThree(quiz1);
}
return studentInfos ;
}
}
The scope of StudentInfo[] declared inside the method, returnObjectArray is local to this method. Also, this array will be garbage collected once the method, returnObjectArray returns. Similar is the case with the Scanner object declared inside the method, scanner.
First, replace the following methods as shown below:
public static StudentInfo[] returnObjectArray() {
StudentInfo[] studentInfos = new StudentInfo[2];
return studentInfos;
}
public static Scanner scanner() {
Scanner input = new Scanner(System.in);
return input;
}
Then, collect the returned values from these methods into variables of respective types and pass them to userInput as shown below:
StudentInfo[] studentInfos = returnObjectArray();
Scanner input = scanner();
userInput(studentInfos, input);
Reference to the studentInfo[] is not visible outside the method returnObjectArray(); it is a local reference. However, you can create a new reference in the calling (main) method and assign it the return value of the called method.
StudentInfo[] studentInfos = returnObjectArray();
I'm new to Java and having a little trouble getting the concept of Java. One of my class assignments is to create two class and have one for the output and one for the input. Otherwise known as an instance and driver class.
So if I have something like
Scanner userInput = new Scanner(System.in);
** Declare it **
System.out.println("How many do you have?");
int count = userInput.nextInt();
Then, I need to put arithmetic into a new method. Then that new method needs to be called inside the other class how would I do so?
When I try count = count + 5;
It just says I have a duplicate variable.
https://gyazo.com/f9b008d839ecfad6d9ef33334a47782a
https://gyazo.com/6a420e98e27fa8779fec4ccab158f9bc
import java.util.Scanner;
class Instance
{
Scanner userInput = new Scanner(System.in);
void show()
{
System.out.println("How many do you have?");
int count = userInput.nextInt();
count=count+5;
System.out.println(count);
}
}
class Driver
{
Instance instance = new Instance();
B()
{
instance.show();
}
}
class Result
{
public static void main(String... args)
{
Driver d =new Driver();
}
}
I'm helping someone learn Java at the moment. I'm a senior C# developer. I understand programming in general but I do not know the Java APIs.
Most advice on the web on how to read an int from the console is complicated. It involves BufferedReader and InputStreamReader and such. This is completely incomprehensible to a beginner.
I want to provide him with a function static int readIntFromConsole() that does this. What would the body of that function be?
Try the following:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter some integer:\t");
int myIntValue = scanner.nextInt();
In order to use through the lifespan of your test application, you can do the following:
public void scanInput() {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter some integer:\t");
int myIntValue = scanner.nextInt();
System.out.print("You entered:\t" + myInteValue);
}
}
Are you talking about reading user input from the console? You could use the Scanner class in that case.
Scanner stdin = new Scanner(System.in);
int input = stdin.nextInt();
If you want to grab different input, no need to initialize a new scanner. You can use a different method from the scanner in that case, depending on the value you want.
System.out.println("Enter a double: ");
double myDouble = stdin.nextDouble();
System.out.println("Enter a string of characters: ");
String myString = stdin.next();
System.out.println("Enter a whole line of characters: ");
String myEntireLine = stdin.nextLine();
etc.
See this example
import java.util.Scanner;
public class InputTest {
public static void main(String[] args) {
//Now using the readIntFromConsole()
int myNumber = readIntFromConsole();
System.out.println(myNumber);
}
public static int readIntFromConsole() {
System.out.print("Enter an integer value....");
Scanner s = new Scanner(System.in);
int number = s.nextInt();
return number;
}
}
//Edit: provided the required method
I am getting this error: "cannot make a static reference to the nonstatic field" everytime I try to execute a line of code with .nextInt() in it.
Here are the lines of code that could affect (that I can think of):
private Scanner input = new Scanner(System.in);
int priceLocation = input.nextInt();
This is most likely because you're trying to access input in a static method, which I'm assuming it to be the main() method. Something like this
private Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int priceLocation = input.nextInt(); // This is not allowed as input is not static
You need to either make your input as static or may be move it inside the static(main) method.
Solution1: Make the input as static.
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int priceLocation = input.nextInt();
Solution2: Move the input inside the main(note that you can't use input in any other methods, if its moved inside the main(), as it'll be local to it).
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int priceLocation = input.nextInt();
private Scanner input = new Scanner(System.in); // make this static
If you accessing this inside static method. you have to make input static.
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int priceLocation = input.nextInt();
// without static you will get that error.
}
This is because of the way you are defining input
private Scanner input = new Scanner(System.in); // notice private
int priceLocation = input.nextInt();
Private variables are defined in the class, outside methods like
class myclass{
private Scanner input = new Scanner(System.in);
void methodname(){
int priceLocation = input.nextInt();
}
}
Or if you want to define input inside the method
class myclass{
void methodname(){
Scanner input = new Scanner(System.in); // you can make this a final variable if you want
int priceLocation = input.nextInt();
}
}