I have a a program that is suppose to take information on the speed of the computer, how much ram the computer has, etc etc(Basically a computer inventory system). Nothing is really wrong with the program as far as I know. The only problem I have is that I do not want to use multiple scanner since I've read it's considered bad practice. The scenario is I have the main method, public static void main, acting as a menu system(The user simply inputs the choice that he wants). Then there are other methods that asks information like how fast is your computer, how much ram does your computer, or even if you would like to remove a computer from your inventory system. Each of these methods have a scanner object and I want to know how I can trim it down to one scanner that could interact with all the data.
Update: Here is a the complete program of the program.
package computerinventory;
import java.util.Scanner;
import java.util.ArrayList;
public class ComputerInventory
{
private static Scanner read = new Scanner(System.in);
public static void main(String[] args)
{
ComputerInventory process = new ComputerInventory();
ArrayList<Computer> computer = new ArrayList<>();
int option;
do
{
System.out.println("1.) Add computers to your inventory.");
System.out.println("2.) Display your Inventory.");
System.out.println("3.) Remove Computers from your inventory.");
System.out.println("4.) Quit the program. ");
option = read.nextInt();
switch(option)
{
case 1:
process.addComputers(computer);
System.out.println("");
break;
case 2:
process.displayInventory(computer);
System.out.println("");
break;
case 3:
process.removeComputer(computer);
break;
case 4:
System.out.println("\nThank you for using my program.");
return;
default:
System.out.println("\nThis choice doesn't exist in the menu.");
}
}
while(true);
}
public void addComputers(ArrayList<Computer> computer)
{
double computerSpeed;
int hardDrive;
double ram;
boolean functional;
double cost;
System.out.println("\nHow fast is this computer in Ghz?");
computerSpeed = read.nextDouble();
System.out.println("\nHow big is the HardDrive in GB?");
hardDrive = read.nextInt();
System.out.println("\nHow much ram does this computer has. ");
ram = read.nextDouble();
System.out.println("\nTrue or false, does this computer work?");
functional = read.nextBoolean();
System.out.println("\nHow much does this computer cost? ");
cost = read.nextDouble();
Computer com = new Computer(computerSpeed, hardDrive, ram, functional, cost);
computer.add(com);
}
public void displayInventory(ArrayList<Computer> computer)
{
for (Computer computer1 : computer)
{
System.out.println(computer1);
}
}
public double totalCost()
{
return 0;
}
public void removeComputer(ArrayList<Computer> computer)
{
}
}
package computerinventory;
public class Computer
{
private double computerSpeed;
private int hardDrive;
private double ram;
private boolean functional;
private double cost;
public Computer(double computerSpeed, int hardDrive, double ram, boolean functional, double cost)
{
this.computerSpeed = computerSpeed;
this.hardDrive = hardDrive;
this.ram = ram;
this.functional = functional;
this.cost = cost;
}
public Computer()
{
}
public void setComputerSpeed(double computerSpeed)
{
this.computerSpeed = computerSpeed;
}
public void setHardDrive(int hardDrive)
{
this.hardDrive = hardDrive;
}
public void setRam(double ram)
{
this.ram = ram;
}
public void setFunctional(boolean functional)
{
this.functional = functional;
}
public void setCost(double cost)
{
this.cost = cost;
}
#Override
public String toString()
{
return "\nSpeed is " + computerSpeed + " GHz.\n" + "hardDrive is " + hardDrive
+ " GigaBytes.\n" + "RAM is " + ram + "GigaBytes.\n" + "Status is " + functional
+ "\n" + "The cost of this computer " + cost;
}
}
You can use the Scanner method in the main class and possibly prompt for inputs in the main class.
public static void main(String[] args)
{
// Scanner object created here
// Ask for information here, variables a and b
// ArrayList that is suppose to contain all the information.
// menu here with four choices
}
public void doSomething(ArrayList<ClassName> obj, int a, int b)
{
// Add paramater variables to the existing array list
}
// More methods as you go down with a scanner object.
Here I use one scanner to gather all of the data, if you'd like, I can post an update at your request passing the scanner to the method also. This same practice works with pretty much any data type. You can expand on this to use ArrayLists, which would be pretty easy also.
try this code out:
public static void main (String [] args) {
Scanner input = new Scanner (System.in);
int data1;
int data2;
int data3;
System.out.println ("Enter data1: ");
data1 = input.nextInt(); //Can use .nextDouble/float/long/short/byte/line/char... ();
System.out.println ("Enter data2: ");
data2 = input.nextInt();
data3 = manipData (data1, data2);
System.out.println (data1 + " + " + data2 + " = " + data3);
input.close(); // Be sure to close your scanner
}
public static int manipData (int data1, int data2) {
return data1 += data2;
}
Declare the Scanner at level class as a static field. In this way, you have a single Scanner instance available to all the methods of this class and available for other classes as well.
public class X {
public static Scanner scanner;
public static void main(String[] args) {
scanner = new Scanner(System.in);
//...
foo();
//...
scanner.close();
}
public static void foo(...) {
System.out.println("Please enter the value of x:");
int x = scanner.nextInt();
System.out.println("The result of working with X: " + realMethod(x));
}
public static int realMethod(int x) {
int result = ...; //some operations done with an X parameter
return result;
}
}
Related
So, I wrote this code and its working fine but when i try to check total sale it shows zero(0).
in this part-
public void totalSales(){
getTotal();
System.out.println("Total sales is "+getTotal());
}.
I am struggling to save the previous values to get the total sales. And also how do I take multiple input from the menu? Any kind of help would be appreciated. If you see an area of improvement, do let me know. Thank You!
import `java.util.InputMismatchException`;
import java.util.Scanner;
import `java.util.ArrayList`;
public class Main {
static double a;
ArrayList<Product> cart = new ArrayList<Product> ();
Scanner scanner = new Scanner(System.in);
double vat = 0.5;
boolean done = false;
public Main() {
cart.add(new Product("Vegetable", 8.00));
cart.add(new Product("Deodrant", 56.00));
cart.add(new Product("Beverages", 35.00));
cart.add(new Product("Home Essentials", 10.00));
cart.add(new Product("Bakery", 20.50));
cart.add(new Product("Snacks", 15.00));
}
public void displayCart() {
for (int i = 0; i < cart.size(); i++) {
switch (cart.get(i).quantitySelected){
case 0:
System.out.println(i + ": " + cart.get(i).name + " Not Selected.");
break;
default:
System.out.println(i + ": " + cart.get(i).name + " Selected: " + cart.get(i).quantitySelected);
break;
}
}
}
public void addToCart(int product, int amount) {
cart.get(product).select(amount);
}
public void getSelection() {
int productSelected;
System.out.println("Enter the Product Value: \nOr \nEnter Done to End and See The Total. ");
try {
productSelected = scanner.nextInt();
} catch (InputMismatchException e) {
done = true;
return;
}
System.out.println("Enter Amount To Select: ");
int amount = scanner.nextInt();
cart.get(productSelected).select(amount);
}
public double getSubtotal() {
double cost = 0.00;
for (Product product : cart) {
cost += product.cost * product.quantitySelected;
}
return cost;
}
public double getTotal() {
return (getSubtotal() + getSubtotal()*vat);
}
public void totalSales(){
getTotal();
System.out.println("Total sales is "+getTotal());
}
public void finnishPurchase() {
System.out.println("---------------------");
System.out.println("Subtotal: " + getSubtotal());
System.out.println("Vat: " + vat);
System.out.println("Total: " + getTotal());
}
public static void main(String[] args) {
Main store = new Main();
while (!store.done) {
store.displayCart();
store.getSelection();
}
store.finnishPurchase();
System.out.println("Enter the password");
Scanner input=new Scanner(System.in);
String pw=input.next();
String actual="abc123";
boolean check=pw.equals(actual);
if(check==true)
{
System.out.println("Correct password.Here is the access");
Main c=new Main();
c.totalSales();
}
else
{
System.out.println("Incorrect password.Try again");
}
}
}
public class Product {
String name;
double cost;
int quantitySelected = 0;
public Product(String name, double cost) {
this.name = name;
this.cost = cost;
}
public void select(int quantity) {
quantitySelected = quantity;
}
}
I fixed your total issue.
You start a new main for no reason which resets the total to 0.
The fix was just to use the old main(Check the environment i tested in) to get the total.
I don't understand what you mean by getting mutiple inputs from the menu, however, it loops fine to select products one by one. I adapted the code to limit the number of products. All I did was add a limit variable to each object(you can use static to add a global limit). If you wanted to retrieve all users' totals you would have to store them then retrieve them and add them up.
The code I made.
Edit:
In order to take multiple item you just have to loop your nextInt() statements.
Code(Main.java):
System.out.println("Enter the Products and amounts(eg. 1(product) 20(amount)) Value: \nOr \nEnter Done to End and See The Total. ");
while(true){
try {
productSelected = scanner.nextInt();
int amount = scanner.nextInt();
if((amount+cart.get(productSelected).quantitySelected) <= cart.get(productSelected).limit)
cart.get(productSelected).select(amount);
else
System.out.println("Limit reached for item:"+cart.get(productSelected).name);
} catch (InputMismatchException e) {
done = true;
return;
}
}
The menu won't redisplay the user menu and will wait for the user to put done(or the wrong input). The user is able to put products line by line or all in one line(eg. 1 10 2 5 done) and get their total(check the code I tested on).
I am trying to write a java program which have two classes. The second class will have the main method and for checking the balance of the account and. The first class will have three methods one for opening an bank account, one for deposit and one for withdrawal. All input needs to be given by user. I am new to java and stuck after at one point any help would be appreciated.
import java.util.Scanner;
class Balance {
static int account()
{ Scanner minimumAmount = new Scanner(System.in);
int openingAmount = minimumAmount.nextInt();
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account:" + openingAmount);
if (openingAmount > 1000)
{
System.out.println("Your Bank account has opened successfully");
int ac = minimumAmount.nextInt();
System.out.println("Enter your account number" + ac);
}
}
static int withdrawal() {
Scanner withdrawalAmount = new Scanner(System.in);
int w = withdrawalAmount.nextInt();
System.out.println("Withdrawal Amount is :" + w);
int b = openingAmount - w;
if (b < 100) {
System.out.println("Unable to process your request");
}
}
void deposit() {
Scanner depositAmount = new Scanner(System.in);
int d = depositAmount.nextInt();
System.out.println("Deposited amount is :" + d);
int b = openingAmount + d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
}
}
i) Is there a way where an user input variable declared under one method can be used in another method to declare another variable?
ii) ow to return a value from a method so that the value received works in different method while declaring a variable?
Is there a way where an user input variable declared under one method
can be used in another method to declare another variable?
You can declare your attribute in your class and use constructor to initialize it for example :
class A{
private String name;
public A(String name){
this.name = name
}
public int account(){
//can use and change the name
}
public int withdrawal(){
//can use and change the name
}
public int deposit(){
//can use and change the name
}
}
Main class
public class B{
public static void main(String[] args) {
A s = new A("Hello");
//------------^^---pass your attribute in the constructor
s.account();
s.withdrawal();
s.deposit();
}
}
How to return a value from a method so that the value received works
in different method while declaring a variable?
You can use the result of each method in another method for example :
s.withdrawal(s.account());
//--------------^^-------account return a result that can be used by withdrawal
I don't know what you really want to do, but I can explain some things.
Methods account() & withdrawal() don't have to be static.
You can use instance attribute like I do to store values.
Balance & AccountBalance should be in different files.
Take a look about private & public on attribut & methods (& getter/setter)
Scanner is a little bit tricky so you should declare it once, and reuse it.
If you want to use returned value from function, change void by int (in this case) and use "return var" (var is what you want to return). So when you can call the function like this -> int value = s.account();
Try this code, it works.
Cheers !
import java.util.Scanner;
class Balance {
private Scanner scanner;
public int userAccount;
public int userAccountNumber;
public Balance() {
scanner = new Scanner(System.in);
}
public void account() {
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account : ");
int openingAmount = scanner.nextInt();
if (openingAmount > 1000) {
System.out.println("Your Bank account has opened successfully");
userAccount = openingAmount;
System.out.println("Enter your account number : ");
userAccountNumber = scanner.nextInt();
} else {
System.out.println("Not enought money");
this.account(); //Ask again for opening an account
}
}
public void withdrawal() {
System.out.println("Withdrawal Amount is : ");
int w = scanner.nextInt();
int b = userAccount - w;
if (b < 100) {
System.out.println("Unable to process your request");
} else {
userAccount = b;
}
}
public void deposit() {
System.out.println("Deposited amount is : ");
int d = scanner.nextInt();
userAccount += d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
System.out.println("Final amount is : "+s.userAccount);
}
}
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);
}
}
I am currently learning about methods and using methods. It sometimes confuses my mind when deciding what to put inside the parameters. I have some code where I created three methods and all correspond. What I must do for this program is to display some services and prices and ask the user if he/she would like it. If they say yes, the prices add up until the end of the array. The part I am having trouble with is how to take in the price from main in my third method. I know that I should use a void method because I am not returning anything, just printing out the prices to the user.
Heres my piece of code for this program:
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("What automobile make do you own?");
Scanner keyboard = new Scanner(System.in);
String name = keyboard.nextLine();
make(name);
double price = carMaintenance(name);
finalPrice(price);
}
// First Method
public static void make(String name) {
System.out.println("Hello! We will be happy to service your " + name
+ " automobile today!");
}
// Second Method
public static double carMaintenance(String name) {
String[] services = { "Oil Change", "Tire Rotation", "Air Filter",
"Check Fluids" };
double[] prices = { 39.99, 49.99, 19.99, 10.99 };
double Total = 0;
for (int i = 0; i < services.length; i++) {
System.out.println("Do you want a " + services[i] + " for your "
+ name + " " + prices[i] + "? (y/n)");
String answer;
answer = keyboard.nextLine();
if (answer.equals("y"))
{
Total = Total + prices[i];
}
// Third method
public static void finalPrice ( ? )
Specifically this the part I am having trouble with:
// Third method
public static void finalPrice (double price )
The problem is finalPrice is an invalid type for the variabl which is pretty confusing about.
You have to change finalPrice() to accept a double parameter:
public static void finalPrice(double price) { ... }
And pass the value returned by carMaintenance() to finalPrice():
double price = carMaintenance(name);
finalPrice(price);
Note I am assuming you just forgot to paste the rest of the carMaintenance() method. In the end, of course, it should have the return Total statement.
Your second method is lacking a return statement. You can return the total to main and then send it to your third method, as such:
public static void main(String[] args) {
System.out.println("What automobile make do you own?");
Scanner keyboard = new Scanner(System.in);
String name = keyboard.nextLine();
make(name);
double finalPrice = carMaintenance(name);
printFinalPrice(finalPrice);
}
//first method code here
public static double carMaintenance(String name) {
//second method code here, plus:
return total;
}
// Third method
public static void printFinalPrice(double finalprice) {
System.out.println("Your final price is " + finalprice);
}
Pass double from carMaintance to finalPrice
double finalPriceDbl = carMaintenance(name);
finalprice(finalPriceDbl);
and accept double as parameter in finalPrice
public static void finalPrice ( double finalPrice );
also you should return value from carMaintenance with return statemenet
return Total;
I'm working on a roulette game and I'm having an error with my makeDecision method in my Roulette class. The reason is because I am having trouble with the updatePot method in my Player class and am not sure what to do in it. I am using 4 classes, here is my code for each:
public class Assign3 {
public static void main(String[] args) {
Roulette roulette = new Roulette();
roulette.run();
}
}
and
public class Roulette {
private String decision;
Player player = new Player();
Wheel wheel = new Wheel();
private void makeDecision(){
String bet = player.getBet();
try {
int value = Integer.parseInt(bet);
if (value == wheel.getValue()){
decision = " you win 40 times your bet";
player.updatePot(40);
} else {
decision = "you lose the game";
player.updatePot(0);
}
} catch (NumberFormatException e){
if (bet.equals("odd")){
if (wheel.getValue() %2 == 0){
decision = "you lose the game";
player.updatePot(0);
} else {
decision = "you win double your bet";
player.updatePot(2);
}
} else if (bet.equals("equals")){
if (wheel.getValue() %2 == 0){
decision = "you win double your bet";
player.updatePot(2);
}
}
}
}
private void displayDecision(){
}
public void run(){
System.out.println("Welcome to Cache Creek style Roulette..bet an amount and type\n"
+ " if you select the correct colour, you win double your bet\n"
+ " if you select the correct odd/even, you win double your bet\n"
+ " if you select the right number, you win 40 times your bet\n"
+ " otherwise you lose your bet\n"
+ " If you lose all your money, the game is over");
do {
player.setBetAmount();
player.setBet();
wheel.spin();
wheel.display();
makeDecision();
displayDecision();
} while (true);
}
}
and
package Assignment3;
import java.util.Scanner;
public class Player {
private int pot = 0;
private int amount = 0;
Scanner input = new Scanner(System.in);
public void setBetAmount() {
System.out.print("\nHow much do you want to bet? ");
amount = input.nextInt();
int pot =100;
if (amount > pot || amount < 1){
System.out.print("Invalid bet amount..How much do you want to bet? ");
amount = input.nextInt();
}
}
public void setBet() {
System.out.print("What is your bet? (odd/even/red/black/exact number)");
}
public String getBet() {
return null;
}
public void updatePot(int i) {
}
}
and
package Assignment3;
import java.util.Random;
public class Wheel {
private int value;
private String colour;
Random random;
public Wheel(){
value = 0;
colour = null;
random = new Random();
}
public int getValue(){
return value;
}
public void setValue(int value){
this.value = value;
}
public String getColour(){
return colour;
}
public void spin(){
value = random.nextInt(39)+1;
colour = (random.nextInt(1)==0)?"red":"black";
}
public void display(){
System.out.print(value+" "+colour);
}
}
the input for your program has to be a String because your Player can input both text or a specific number. You then have to check this String for the occurence of either (odd/even/red/black) or a valid number. If neither is true then the input is invalid.
When looking at your code you need to think about how you want your updatePot method to work.
Should it set the pot to the given value (that's what the method name would suggest to me)
Should it add the given value to the pot or
Should it multiply the current pot value by the given value
When you have decided how it should work you have to update your Roulette.makeDecision() method.
Good luck with your assignment!
Markus
Just change the datatype of bet from String to int and then add your updatePot methode. You will also need to adjust your NumberFormatException.