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();
Related
I'm struggling with passing a variable value that a user has entered into my program into a method. I think the technical word is parameters.
The problem I'm having is that after the user enters a number in the getnum() method I want the number to be passed down to the two methods calculation and `calculation_two. However, I can't seem to be able to achieve it.
Just to explain the program, the user enters a number in the getnum() method, then they go to the option method and after they select what option, in the calculations methods the number that was written in the getnum() method needs to be passed down the the calculations methods. Therefore, I will then be able to perform calculations with it that way. I need the program to be set up like this as well for my own personal reasons.
Can anyone assist please?
Thanks
public static void main (String[]args){
getnum();
}
public static void getnum() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = input.nextInt();
option();
}
public static void option() {
Scanner input2 = new Scanner(System.in);
System.out.println("would you like to see option 1 or 2");
int num2 = input2.nextInt();
if(num2==1) {calculation();}
else if(num2==2) {calculation_two();}
else {System.exit(0);}
}
public static void calculation() {
}
public static void calculation_two() {
}
Please see call by reference and call by value to further clarify how primitives or objects are passed from one method to another.
Here are the steps to pass the parameter from one method to another:
You pass the int you got from the scanner as an argument in the option method call:
public static void getnum() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = input.nextInt();
option(num); // You pass the int as an argument
}
Now, since you are now calling a method with arguments you need to change the signature of the option method to take a parameter. You pass the int value(theNumber variable) from the option method's parameter to the calculation method call.
Arguments and parameters are terms which are used interchangeably but you can check the difference here.
public static void option(int theNumber) { // option now takes a int parameter
Scanner input2 = new Scanner(System.in);
System.out.println("would you like to see option 1 or 2");
int num2 = input2.nextInt();
if(num2==1) {
calculation(theNumber); // method now takes an argument
}
else if(num2==2) {
calculation_two(theNumber); // method now takes an argument
}
else {System.exit(0);}
}
You pass the parameter again to the calculation(s) method and change the signature to:
public static void calculation(int theNumber) { // method with parameter
}
public static void calculation_two(int theNumber) {
}
Declare your methods to use parameters and return values. Easiest way to do it:
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = input.nextInt();
System.out.println("would you like to see option 1 or 2");
int option = input.nextInt();
int result = 0;
if (option == 1) {
result = calculation(num);
} else if (option == 2) {
result = calculation_two(num)
} else {
System.out.println("Invalid option, exiting...");
System.exit(0);
}
System.out.println("Result = " + result);
}
private static int calculation(int num) {
// implement this
return 0;
}
private static int calculation_two(int num) {
// implement that
return 0;
}
To answer with secure coding practices
package in.faridabad.mandheer;
public class Main{
public static void main (String[]args){
Main m = new Main();
// Assuming calculation is "sum"
System.out.println("sum is + "+ m.option());
}
private int getnum() {
Scanner input = new Scanner(System.in);
return input.nextInt();
}
int option() {
System.out.println("would you like to see option 1 or 2");
int num2 = getnum();
if(num2==1) {return calculation();}
else if(num2==2) {return calculation_two();}
else {System.exit(0);}
}
private int calculation() {
System.out.println("Enter a number: ");
int num1 = getnum();
return num1;
}
private int calculation_two() {
System.out.println("Enter a number: ");
int num1 = getnum();
System.out.println("Enter 2nd number: ");
int num2 = getnum();
return num1+num2;
}
}
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();
}
}
Last objective of my assignment asks to create a method matches(). It receives another GenericMemoryCell as a parameter, and returns true if both of its stored values can be found in the stored values of the current GenericMemoryCell. Order of stored values is not important.
Creating the method was not difficult, but I am lost on how to call it from main() because I cannot wrap my head around the concept of passing another instance of GenericMemoryCell. Where am I getting another pair of storedValueA and storedValueB in the first place? Is matches() "running" a virtual instance of the entire program within itself?
import java.util.*;
public class GenericMemoryCell<T>{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter valueA: ");
String readerA = input.next();
System.out.print("Enter valueB: ");
String readerB = input.next();
GenericMemoryCell<String> values = new GenericMemoryCell<>(readerA, readerB);
System.out.println("storedValueA: " + values.readA());
System.out.println("storedValueB: " + values.readB());
values.writeA(readerA);
values.writeB(readerB);
}
public GenericMemoryCell(T storedValueA, T storedValueB)
{ this.storedValueA = storedValueA; this.storedValueB = storedValueB; writeA(storedValueA); writeB(storedValueB); }
public T readA()
{ return storedValueA; }
public T readB()
{ return storedValueB; }
public void writeA(T x)
{ storedValueA = x; }
public void writeB(T y)
{ storedValueB = y; }
public boolean matches(GenericMemoryCell<T> that){
return (this.storedValueA.equals(that.storedValueA) && this.storedValueB.equals(that.storedValueB)); }
private T storedValueA, storedValueB;
}
I think you need something like this
public class GenericMemoryCell {
public static void main(String[] args) {
GenericMemoryCell g1 = new GenericMemoryCell();
//set g1 values here
GenericMemoryCell g2 = new GenericMemoryCell();
//set g2 values here
System.out.println(g1.matches(g2));
}
public boolean matches(GenericMemoryCell g) {
//implement the logic here
return ...;
}
}
Hopefully, it might work for you. However, if you want system to ask for inputs repeatedly, you need to some kind of loop.
public class GenericMemoryCell {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first input: ");
int firstInput = scanner.nextInt();
System.out.println("Please enter second input");
int secondInput = scanner.nextInt();
list.add(firstInput);
list.add(secondInput);
Scanner scannerObj = new Scanner(System.in);
System.out.println("Please enter first input: ");
int firstArg = scannerObj.nextInt();
System.out.println("Please enter second input: ");
int secondArg = scannerObj.nextInt();
boolean isMatches = isInputMatches(firstArg, secondArg, list);
if (isMatches) {
System.out.println("These inputs were already stored before. Please try again with different inputs");
} else {
System.out.println("The inputs are successfully stored. Thank you.");
}
scanner.close();
scannerObj.close();
}
private static boolean isInputMatches(int firstArg, int secondArg, List<Integer> list) {
return list.contains(firstArg) && list.contains(secondArg);
}
}
Java noob here. My instructor told me specifically to "instantiate the scanner INSIDE the constructor". The problem is, i am not seeing a constructor in our ScannerLab class. Nor am i seeing any inheritance. I have a field named scan which is of type java.util.Scanner that i need to use. How do i instantiate the scanner inside the constructor?
code:
public class ScannerLab {
private java.util.Scanner scan;
public void echoStrings() {
String word;
// create a new storage array
String[] myList = new String[5];
// set for loop
for(int i = 0; i < 5; i ++) {
// prompt for the value
System.out.print("Enter word " + i + ": ");
// get the input value
word = scan.next();
// echo the input value
System.out.println("You entered " + word);
// store the input value into the array
myList[i] = word;
}
String line = "";
// loop through the array and concatenate the values
// put a space between the words
System.out.println("The words you entered are: " + line);
System.out.println("list is" + myList);
}
public void echoIntsAndTotal() {
int inputValue;
// declare an array to hold the 5 values
for(int i = 0; i < 5; i ++) {
// prompt for the value
System.out.print("Enter integer value " + i + ": ");
// get the input value
inputValue = 23;
// echo the input value
System.out.println("You entered " + inputValue);
// store the input value into the array
}
int total = 0;
// loop through the array and add the values
System.out.println("The total of your values is " + total);
}
public static void main(String[] args) {
ScannerLab lab;
lab = new ScannerLab();
lab.echoStrings();
// lab.echoIntsAndTotal();
}
}
i have tried:
setting the scan field as a reference variable to:
private java.util.Scanner scan = new java.util.Scanner(System.in);
then in my application method i used:
public static void main(String[] args) {
ScannerLab lab;
lab = new ScannerLab(scan);
didnt work. The only way it would compile and run is if i switch my field to:
private static java.util.Scanner scan = new java.util.Scanner(System.in);
but he wont allow us to use static fields, and that is still not being instantiated inside the constructor.
where is the constructor, and how do i instantiate a new scanner in it?
Thank you
If there is no constructor in your class yet, you have an implicit default constructor available (see this question too). You can choose to override it at any point:
public class ScannerLab {
public ScannerLab() {
scan = new java.util.Scanner(System.in);
}
...
}
From https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html:
The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass.
How about writing a constructor then?
// Constructor
public ScannerLab() {
scan = new java.util.Scanner(System.in);
}
Other than that, this line
System.out.println("list is" + myList);
doesn't work. It will give you the class name and hashcode, since that is the default implementation.
Try something like this:
System.out.println("\nThe words you entered are:");
System.out.println(Arrays.toString(myList));
which will give you an output like:
The words you entered are:
[apple, banana, carrot, dududu, elephant]
(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.");
}
}
}