Scanner as parameter and convert to int? (JAVA) - java

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.

Related

working with variable number of arguments using scanner input class

While working with scanner input can we use var.. args with sc.nextInt()??
for example..(below code)
import java.util.Scanner;
class Sample
{
public static void run(int... args){
System.out.println(args[1]);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("please enter values: ");
int values = sc.nextInt();
run(values);
}
}
the output was ArrayIndexOutOfBoundsException:1 can any one explain about this...
values is just one variable, so args's length is 1, which means the only valid index is 0 (arrays are zero-based entities)
Your array size is 1 and trying to access 2nd value so use below code. I have change from args[1] to args[0].
ArrayIndexOutOfBoundsException arise when we try to access index value which is not present in array, not only for integers array but for all types of arrays.
import java.util.Scanner;
class Sample
{
public static void run(int... args){
System.out.println(args[0]);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("please enter values: ");
int values = sc.nextInt();
run(values);
}
}
use args[0] instead args[1] because your value store on

Adding to a User Input Variable

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();
}
}

How to create a static array that has a length defined by user input?

I have a program where a number of grades are entered by the user and stored into array which is then used by the program to calculate various values.
I'm using multiple methods so I want to define a static array that all the methods can refer to and will hold the grades. However I want its length to be equal to the number of grades entered.
public class GradeStatistics {
static int numGrades, sum = 0;
static int[] grades = new int[numGrades];
public static void main(String args[]){
readGrades();
calcSum();
the readGrades() method finds out how many grades there will be and assigns it to numGrades
public static void readGrades(){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of grades: ");
numGrades = input.nextInt();
Is there a way I can get the user to enter the number of grades before defining the static array?
You can define the static array, but not initialize it:
static int[] grades;
Then you can call the readGrades() method and initialize the grades array inside it:
public static void readGrades(){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of grades: ");
numGrades = input.nextInt();
grades = new int[numGrades];
}
You're not forced to initialize a field when declaring it. The initialization can come after, and the variable can be reinitialized any number of times. So you just need
static int[] grades; // declaration. The field is implicitely initialized to null.
public static void readGrades(){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of grades: ");
int numGrades = input.nextInt();
grades = new int[numGrades]; // initialization
Note that I made numGrades a local variable rather than a static field. There is no reason to make it a static field. The number of grades is available using grades.length.
When declaring the grades array you don't have to assign it.
static int[] grades;
And then just assign it when you're reading in the nr of grades.
public static void readGrades(){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of grades: ");
numGrades = input.nextInt();
grades = new int[numGrades];
I would implement the readGrades method like this
public static int[] readGrades(){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of grades: ");
numGrades = input.nextInt();
int[] grades = new int[numGrades];
// read the grades
return grades;
}
since it is more intuitive and encapsulated if a method that is named readGrades also returns something.
you may init the array int your static method : readGrades
like this:
public class GradeStatistics {
static int numGrades, sum = 0;
static int[] grades = null;
public static void main(String args[]){
readGrades();
calcSum();
}
public static void readGrades(){
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of grades: ");
numGrades = input.nextInt();
grades = new int[numGrades];
}
}
Declare you grades like this
static int[] grades = null;
And initialize the grades like below.
public static void readGrades(){
numGrades = input.nextInt();
grades =new int[numGrades];
}

Getting error while using .nextInt()

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();
}
}

Beginner Java static scope error

(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.");
}
}
}

Categories