Adding to a User Input Variable - java

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

Related

I am trying to use scanner outside the main method, and it keeps repeating after 3 inputs

So I am trying to use scanner outside main method and keeps on repeating on enter, and idk if the new Obj is causing it cause I observed that the number of obj I created is the same as the amount of times I repeated input process and enter. Then after those tries it will then show the output inside the main method.
This is my code:
package galitkami;
import java.util.Scanner;
public class test {
Scanner myObj = new Scanner(System.in);
{System.out.print("Enter Carat Value: ");}
int c = myObj.nextInt();
double g = 0.20;
double cg = c*g;
double gm = cg*1000;
double mg = gm*0.00220462/1000;
public static void main(String[] args) {
test a = new test();
test b = new test();
test c = new test();
System.out.println("Carats in Grams: "+a.cg);
System.out.println("Grams in Milligrams: "+b.gm);
System.out.println("Milligrams in Pounds: "+c.mg);
}
}
I am expecting that after I input value on "Enter Carat Value:" it will automatically show the output inside the main method.
Update, I have found a solution for this and this is what it looks like:
import java.util.Scanner;
public class test {
static Scanner myObj = new Scanner(System.in);
{System.out.print("Enter Carat Value: ");}
final int c = myObj.nextInt();
double g = 0.20;
double cg = c*g;
double gm = cg*1000;
double mg = gm*0.00220462/1000;
public static void main(String[] args) {
test a = new test();
System.out.println("Carats in Grams: "+a.cg);
System.out.println("Grams in Milligrams: "+a.gm);
System.out.println("Milligrams in Pounds: "+a.mg);
}
}
My friend told me that I have simply need to create one object and call it out for all.
I don't know your level of expertise in programming and Java. However there are a few things that I believe are strongly recommended to follow. Don't use a Scanner outside a method. Never print outside a method. Initiate all class attributes that aren't immutable inside a class constructor call.
In your current code you have three calls to new test(); where each call will initiate all class attributes and hence the line int c = myObj.nextInt(); will be executed three times.
Instead create a constructor method in your Test class. Initiate all your attributes here and execute all System.out prints here or in the main method.
public class Test {
//Declare attributes only
int c;
double g, cg, gm, mg;
//Class constructor method
public Test(Scanner myObj) {
System.out.print("Enter Carat Value: ");
//Give declared attributes their values
c = myObj.nextInt();
g = 0.20;
cg = c*g;
gm = cg*1000;
mg = gm*0.00220462/1000;
System.out.println("Carats in Grams: "+ cg);
System.out.println("Grams in Milligrams: "+ gm);
System.out.println("Milligrams in Pounds: "+ mg);
}
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
//Calling new Test() executes the constructor method above
new Test(myObj);
myObj.close();
}
}

Scanner as parameter and convert to int? (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.

Calling an Object array

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

while there is input from user

I'm new to java. In my program, I have the user enter the integers that are being added to an array list. I need to set up a while loop that will be something like this:
arrayList = new ArrayList<int>;
int i = scanner.nextInt();
while(there is input from user)
{
arrayList.add(i);
}
I expect the user to enter 5 values. What do I put as the condition statement of the while loop. In other words, how do I say "while there is input?" Thanks
Try something along the lines of
while(scanner.hasNextInt())
{
arrayList.add(i);
}
import java.util.Scanner;
import java.util.ArrayList;
public class A {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList arrayList = new ArrayList<Integer>();
int input;
for (int i = 0; i < 5; i++)
{
input = scan.nextInt();
arrayList.add(input);
}
}
}
I tried below code and tested its working fine. let me know if u want another requirements.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> arr = new ArrayList<Integer>();
System.out.print("enter 5 numbers");
int counter=1;
while(scan.hasNextInt()){
int i=scan.nextInt();
arr.add(i);
counter++;
if(counter==5){
scan.close();
break;
}
}
}
}
I believe, you're currently accepted answer has a very fatal (it never updates i). What you need is something more like this -
// arrayList = new ArrayList<int>; // And arrayList isn't a great name. But I have
// no idea what they actually are. So
// just use a short name.
List<Integer> al = new ArrayList<Inteeger>(); // <-- Use the interface type?
// And, you have to use the wrapper type.
// int i = scanner.nextInt();
while (scanner.hasNextInt())
{
al.add(scanner.nextInt()); // You don't need `i`.
}

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