I got two classes, this one and other called DailyExpenses that's full of getters and setters + constructors etc..
My problem is that I want to get the sum value of all daily expenses user inputs inside the while loop and print the sum after the program is closed, and I don't know how to do it.
Here is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class DailyExpensesMain {
public static void main(String[] args) {
ArrayList<DailyExpenses> expenses = new ArrayList<DailyExpenses>();
Scanner sc = new Scanner(System.in);
boolean isRunning = true;
System.out.println("Enter the date for which you want to record the expenses : ");
String date = sc.nextLine();
while(isRunning) {
System.out.println("Enter category: (quit to exit)");
String category = sc.nextLine();
if(category.equalsIgnoreCase("quit")) {
break;
}
System.out.println("Enter price: ");
double price = sc.nextDouble();
sc.nextLine();
System.out.println("Enter details: ");
String detail = sc.nextLine();
DailyExpenses newExpense = new DailyExpenses(date, category, price, detail);
expenses.add(newExpense);
}
sc.close();
for(DailyExpenses u: newExpense) {
System.out.println("Date: " + u.getDate() + " Category: " + u.getExpenseCategory() + " Price: " + u.getExpensePrice() +
" Detail: " + u.getExpenseDetail());
}
}
}
I still clueless on the situation
Related
I want to ask the user through a scanner class but I want this scanner to be in a method named readInput() and the output on a different method named writeOutput() using gett-setter
this is my code below:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LaboratoryExercise2 gro = new LaboratoryExercise2();
String[] SecondQuestion;
System.out.println("Select the item your purchasing.");
String Product1 = sc.nextLine();
System.out.println("Enter the Quantity and price separated by SPACE.");
SecondQuestion = sc.nextLine().split(" ");
int Quantity1 = Integer.parseInt(SecondQuestion[0]);
double Price1 = Double.parseDouble(SecondQuestion[1]);
double Amount1 = 0;
Amount1 = Quantity1 * Price1;
int Quantity = 0 + Quantity1;
double Amount = 0 + Amount1;
double Price = 0 + Price1;
I want the output of this to show on a different method
gro.setGrocery(Price, Quantity, Amount);
System.out.println("You've selected " + gro.getitemQuantity() + " " + Product1 + " " + "at " + " " +
gro.getitemPrice() + " each");
System.out.println("Amount due is " + gro.getamountDue());
This is my whole code:
import java.util.Scanner;
public class LaboratoryExercise2 {
private double itemPrice;
private int itemQuantity;
private double amountDue;
public void setGrocery(double newitemPrice, int newitemQuantity, double newamountDue) {
itemPrice = newitemPrice;
itemQuantity = newitemQuantity;
amountDue = newamountDue;
}
public double getitemPrice() {
return itemPrice;
}
public int getitemQuantity() {
return itemQuantity;
}
public double getamountDue() {
return amountDue;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LaboratoryExercise2 gro = new LaboratoryExercise2();
String[] SecondQuestion;
System.out.println("Select the item your purchasing.");
String Product1 = sc.nextLine();
System.out.println("Enter the Quantity and price separated by SPACE.");
SecondQuestion = sc.nextLine().split(" ");
int Quantity1 = Integer.parseInt(SecondQuestion[0]);
double Price1 = Double.parseDouble(SecondQuestion[1]);
double Amount1 = 0;
Amount1 = Quantity1 * Price1;
int Quantity = 0 + Quantity1;
double Amount = 0 + Amount1;
double Price = 0 + Price1;
gro.setGrocery(Price, Quantity, Amount);
System.out.println("You've selected " + gro.getitemQuantity() + " " + Product1 + " " + "at " + " " +
gro.getitemPrice() + " each");
System.out.println("Amount due is " + gro.getamountDue());
}
}
Piling all your code into main is a bad idea. Java is object oriented, and main, being static, isn't.
The solution for sharing data between methods is usually to make a field.
class Main {
public static void main(String[] args) throws Exception {
new Main().go();
}
private Scanner scanner;
void go() throws Exception {
scanner = new Scanner(System.in);
scanner.useDelimiter("\\R");
int quantity = askInt("Enter the quantity: ");
}
private int askInt(String prompt) {
while (true) {
System.out.print(prompt);
if (scanner.hasNextInt()) return scanner.nextInt();
scanner.next(); // eat the non-int token
System.out.println("ERROR: Please enter an integer number.");
}
}
}
That's what virtually all command line java apps should look like: a one-liner main method, no use of static anywhere except main, a scanner field, set with the proper delimiter (\\R, which means .nextX() always reads one line worth of input; use .next() to read an entire line. Don't call .nextLine(), ever. nextLine() and all the other next methods interact in nasty ways that make scanner useless or at least unwieldy and bugprone for command line 'prompting', which why you do it this way.
In my code I am to input multiple students and have a method check to see if any of the students are repeated (by checking ID number) but I cant seem to be able to set multiple students with my current code and save them. From my current code is there any way to be able to set multiple students or will I have to change my code completely
import java.util.Scanner;
public class Registrar
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String string1 = " ";
while(string1 != "1")
{
System.out.println("Please input full name name of student: ");
string1 = input.next(); // user input of name
if (string1 != "0"){
break;
}
System.out.println("Please input Student ID (if done enter 0): ");
String string2 = input.next(); // user input of ID
System.out.println("Please input Students Credits: ");
int inputCredits = input.nextInt(); // User input of Credits
System.out.println("Please input Student's Total Grade Points Earned: ");
double getPoints = input.nextDouble();
double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA
Student first = new Student(string1, string2, inputCredits, GPA);
System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints() );
}
}
}
This is my Student Class
public class Student {
private String name;
private String idnum;
private int credits;
private double gradePoints;
public Student(String n, String id, int c, double gp){
name = n;
idnum = id;
credits = c;
gradePoints = gp;
}
public String getName(){
return name;
}
public String getId(){
return idnum;
}
public int getCredits(){
return credits;
}
public double getGradePoints(){
return gradePoints;
}
}
Try this code. better implementation with collection.
Scanner input = new Scanner(System.in);
String string1 = " ";
System.out.println("Number of students to be entered");
int s = input.nextInt();
List<Student> studentList = new ArrayList<Student>();
for(int i = 0; i<s; i++) {
System.out.println("Please input full name of student: ");
string1 = input.next(); // user input of name
System.out.println("Please input Student ID (if done enter 0): ");
String string2 = input.next(); // user input of ID
System.out.println("Please input Students Credits: ");
int inputCredits = input.nextInt(); // User input of Credits
System.out.println("Please input Student's Total Grade Points Earned: ");
double getPoints = input.nextDouble();
double GPA = getPoints/inputCredits; //User input of Grade Points Earned and Divide by Credits to get GPA
Student student = new Student(string1, string2, inputCredits, GPA);
System.out.println( "Name: " + first.getName() + "\nUser ID: " + first.getId() + "\nCredits: " + first.getCredits() + "\nGrade Point Average: " + first.getGradePoints() );
studentList.add(student);
}
You can take a user input(How many student you want to save and run a loope to take details of input. The rough code will be like this:
System.out.println("Enter how many student you want to enter");
int s = input.nextInt();
for(int i = 0; i<s; i++) {
//Code for take details of user
}
//Then you can print the details of student in similar way.
This is for personal knowledge of how this works, is not for school
Program requirements - Enter 2 Names. Have the program find the assigned values with the names and print the average between the two people.
I an not sure how to get the Scanner to take the input and go to the class to make it start processing. For example, in the main method if I sysout print a, it should display the string inside the method getName.
import java.util.Scanner;
public class RainFallApp {
public static void main(String[] args) {
rainfall a = new rainfall();
rainfall b = new rainfall();
System.out.println(a);
// System.out.print("Please enter month one: ");
// Scanner = new Scanner(System.in);
// rain1 = aRain;
// System.out.print("Please enter month two: ");
// Scanner = new Scanner(System.in);
//
// int average = (rain1 + rain2) / 2;
// System.out.println("The average rainfall for " + var +
"and " + var2 +"is: " + average);
}
}
class rainfall {
String rainamt;
String Rain_Amount;
Scanner input = new Scanner(System.in);
String rainMonth = input.nextLine();
String rainAmount(String rainMonth) {
Rain_Amount = getName(rainMonth);
return Rain_Amount;
}
private String getName(String rainMonth) {
if (rainMonth.equals("Jan")) {
rainamt = "3.3";
}
else if (rainMonth.equals("Feb")) {
rainamt = "2.2";
}
else {
System.out.println("Not a valid month name");
}
return rainamt;
}
}
You only need to say Scanner scanner = new Scanner(System.in); once. Then you can use the scanner's nextLine() method to input data. It returns a string, so be sure to store the result in a variable.
I completed my program
import java.util.Scanner;
public class RainFallApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the first month: ");
String aMonth = input.nextLine();
System.out.print("Please enter the second month: ");
String bMonth = input.nextLine();
rainfall aRainfall = new rainfall();
String aName = aRainfall.rainAmount(aMonth);
Double aAmount = Double.parseDouble(aName);
rainfall bRainfall = new rainfall();
String bName = bRainfall.rainAmount(bMonth);
Double bAmount = Double.parseDouble(bName);
double Avg = (aAmount + bAmount) / 2;
System.out.println("\nIn the month of " + aMonth + " it had "
+ aAmount + " inches of rain.");
System.out.println("In the month of " + bMonth + " it had "
+ bAmount + " inches of rain.");
System.out.println("The average rainfall between the two months is: " + Avg);
}
}
class rainfall {
private String Rain_Amount;
String rainAmount(String rainMonth) {
Rain_Amount = getAmount(rainMonth);
return Rain_Amount;
}
private String getAmount(String rainMonth) {
if (rainMonth.equals("Jan")) {
Rain_Amount = "3.3";
}
else if (rainMonth.equals("Feb")) {
Rain_Amount = "2.3";
}
else {
System.out.println("Not a valid month name");
}
return Rain_Amount;
}
}
So I'm doing a TUI and this was my first iteration.
package bulb.classes;
import java.util.Scanner;
import java.util.ArrayList;
public class RoomTUI {
private ArrayList<Room> rooms;
Scanner scan = new Scanner (System.in);
private int userNumber;
private String userAnswer;
public void run() {
rooms = new ArrayList<Room>();
introduction();
userNumber = 0;
options();
while(userNumber < 5) {
if(userNumber == 1) {
newRoom();
}
if(userNumber == 2) {
addBulbToRoom();
}
if(userNumber == 3) {
clickAllBulbsInRoom();
}
if(userNumber == 4) {
printDescriptionOfBulbs();
}
}
System.out.println("Goodbye");
}
public int getUserInt(String aString) {
System.out.println(aString);
userAnswer = scan.nextLine();
userNumber = Integer.parseInt(userAnswer);
return userNumber;
}
public void displayRooms() {
System.out.println("Possible rooms to choose from.");
String tempString = "";
int roomIndex = 0;
for (int i = 0; i < rooms.size(); i++) {
tempString = tempString + "Room " + roomIndex++ + ": " + rooms.get(i).getDescription() + "\n";
}
System.out.println(tempString);
}
public void introduction() {
System.out.println("Welcome! With this program you can make rooms and design and place the light bulbs for each room you create.");
}
public void options() {
System.out.println("1 : Create a new Room");
System.out.println("2 : Add a bulb to an existing room");
System.out.println("3 : Click all of the bulbs in a particular room");
System.out.println("4 : Display a description of all bulbs in a particular room");
System.out.println("5 : Quit");
getUserInt("What would you like to do?");
}
public void newRoom() {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
rooms.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
public void addBulbToRoom() {
displayRooms();
System.out.println("Which room do you want the bulb in?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println("Please enter the blub's color.");
String color = scan.nextLine();
System.out.println("Please enter the blub's increment amount.");
String incrementS = scan.nextLine();
int incrementI = Integer.parseInt(incrementS);
ThreeWayBulb aBulb = new ThreeWayBulb(color, incrementI);
rooms.get(choiceNumber).addBulb(aBulb);
System.out.println("A " + color + " bulb with and increment of " + incrementI + " was added.");
options();
}
public void clickAllBulbsInRoom() {
displayRooms();
System.out.println("Which room do you want the bulbs clicked?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
rooms.get(choiceNumber).clickAllBulbs();
System.out.println("The bulbs in " + rooms.get(choiceNumber).getDescription() + " have been clicked.");
options();
}
public void printDescriptionOfBulbs() {
displayRooms();
System.out.println("Please enter a room number.");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println(rooms.get(choiceNumber).getDescription() + " with " + rooms.get(choiceNumber).returnSize() + " bulbs: " + "\n" + rooms.get(choiceNumber).toString());
options();
}
}
My instructor wants me to do this without instance variables He said if a method needs the ArrayList that I should make it a parameter and have no instance variables in my TUI. I can't for the life of me figure out how to do that. Also, making it static work fly either. Thanks for any help you can give.
He wants you to declare the ArrayList from a central location (such as the main thread) and then pass it as an argument to the functions that use it. This way if you were to take methods and put them in different classes then it wouldn't break because they're not dependent on this class.
For example if we take your newRoom class:
public void newRoom(List<Room> roomList) {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
roomList.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
EDIT: The easiest way to achieve this is to probably move the declaration of rooms to within your run method. Now for each location in the code that reports "unknown variable rooms" you can modify the function to take an ArrayList as a parameter.
Well, eliminating userNumber and userAnswer as members is trivial; their usage is very localized.
For the list, just pass it around after creating it in your main loop.
The scanner is used multiple places; it could also be passed around, I suppose.
Please help with my assignment. Here is the question:
Create a separate test driver class
called TestEmployeePayroll that will
test the EmployeePayroll class by
performing the following:
Prompt the user to enter the
employees’ ID number, First name, Last
name, Pay Category and Hours worked
(one at a time).
The user entry for employees ID
number must be exactly 5 digits long.
The user entry for Category must only
be accepted if it is in the range 1
to 4.
The user entry for Hours worked
must only be accepted if it is the
range 1 to 80.
This is what I did till now:
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args){
EmployeePayRoll obj1 = new EmployeePayRoll();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Employee ID number: "+ " ");
String EmployeeID = input.nextLine();
//How to check the range here if int is 5 digits long or not ?
System.out.println("Enter the first Name: "+ " ");
String FirstName = input.nextLine();
System.out.println("Enter Last Name: "+ " ");
String LastName = input.nextLine();
System.out.println("Enter the Pay Category: "+ " ");
double PayCategory = input.nextDouble();
System.out.println("Enter the number of hours worked: "+ " ");
double HoursWorked = input.nextDouble();
}
}
You will probably want to use Integer.parseInt().
You can count the length of a String and then convert it to number, Oli Charlesworth told you how to convert it, or you can measure the number. It depends on what you want. Is 012345 a valid ID? It's a 6 char String but it is less than the biggest 5 digits number.
I think you almost got it...
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args){
// ... get the values, as you are doing already
// validate input
int employeeIdAsInteger = validateAndConvertEmployeeId(EmployeeId);
int payCategoryAsInteger = validateAndConvertPayCategory(PayCategory);
// ... and so on
}
private int validateAndConvertEmployeeId(String employeeId) {
// The user entry for employees ID number must be exactly 5 digits long.
if (employeeId == null || employeeId.trim().length() != 5) {
throw new IllegalArgumentException("employee id must be exactly 5 digits long");
}
// will throw an exception if not a number...
return Integer.parseInt(employeeId);
}
// ...
}
Depending on your objectives & constraints, you could look into the Pattern class and use a regular expression.
You can check for conditions like this.
import java.util.Scanner;
public class TestEmployeePayRoll {
public static void main(String[] args) {
TestEmployeePayRoll obj1 = new TestEmployeePayRoll();
Scanner input = new Scanner(System.in);
System.out.println("Enter the Employee ID number: " + " ");
String EmployeeID = input.nextLine();
if (EmployeeID.trim().length() != 5) {
System.out.println("--- Enter valid Employee ID number ---");
}
System.out.println("Enter the first Name: " + " ");
String FirstName = input.nextLine();
System.out.println("Enter Last Name: " + " ");
String LastName = input.nextLine();
System.out.println("Enter the Pay Category: " + " ");
double PayCategory = input.nextDouble();
Double pay = new Double(PayCategory);
if (pay.isNaN()) {
System.out.println("***** Enter a valid Pay Category *****");
}
if (!(PayCategory >= 0 && PayCategory <= 5)) {
System.out.println(" --- PayCategory must be between 0 and 5");
}
System.out.println("Enter the number of hours worked: " + " ");
double HoursWorked = input.nextDouble();
Double hours = new Double(HoursWorked);
if (hours.isNaN()) {
System.out.println("--- Enter a valid hours value ----");
} else {
if (!(HoursWorked >= 1 && HoursWorked <= 80)) {
System.out.println("--- Enter value between 1 and 80 ---");
}
}
}
}