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
Query by loan ID
// Method that allows the user to query by loan ID
public static void QuerybyloanID(List<Loan> data) {
try (Scanner entry = new Scanner(System.in)) {
System.out.print("Please, enter the loan ID: ");
String userentry = entry.next();
// For loop is used to locate the loan ID within the list of loans
for (int i = 0; i < data.size(); i++) {
String loanID = data.get(i).getLoanID();
if (loanID.equals(userentry)) {
boolean pass = true;
String loanPassword = data.get(i).getPasscode();
// Three possible character from the loan password
int one;
int two;
int three;
int [] randomCharacters = randomUniqueGenerator(3, loanPassword.length());
one = randomCharacters[0];
two = randomCharacters[1];
three = randomCharacters[2];
// Check to see if the random numbers are the same or different. -> Implement a Hash Map.
char entry_one = loanPassword.charAt(one);
char entry_two = loanPassword.charAt(two);
char entry_three = loanPassword.charAt(three);
String entry_one_modify = Character.toString(entry_one);
String entry_two_modify = Character.toString(entry_two);
String entry_three_modify = Character.toString(entry_three);
String [] entriesmain = {entry_one_modify, entry_two_modify, entry_three_modify};
try (Scanner entrytwo = new Scanner(System.in)) {
for (int k = 0; k < 3; k ++) {
System.out.print("Enter character " + randomCharacters[k] + " of the loan pass code: ");
String userentrytwo = entrytwo.next();
entrytwo.nextLine();
if (userentrytwo.equals(entriesmain[k])) {
continue;
} else {
pass = false;
continue;
}
}
}
// Check to see if pass is true or false then take the appropriate action
if (pass) {
System.out.println("Customer Name: " + data.get(i).getFirstName() + " " + data.get(i).getLastName());
System.out.println("Branch Code: " + data.get(i).getBrachCode());
System.out.println("Gender: " + data.get(i).getGender());
System.out.println("Date of Birth: " + data.get(i).getDOB());
System.out.println("Loan Amount: " + data.get(i).getLoanAmount());
System.out.println("Customer Phone Number: " + data.get(i).getPhoneNumber());
MainMenu.options();
} else {
System.out.println("Wrong Passcode !");
MainMenu.options();
}
}
Trying to make it so if the user types "end", in the second input which is "Enter the first name of student", the loop automatically assigns each object in the array the attributes of "null" for id and name, and 0 for age and id, as well as breaking the outerloop. However, I get the error java.lang.NullPointerException.
Any help would be appreciated.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter number of students");
int numberof = myObj.nextInt();
System.out.println("Number of students is " + numberof);
Student Studentz[] = new Student[numberof];
outerloop:
for (int i = 0; i < numberof; ++i) {
Studentz[i] = new Student();
System.out.println("Enter first name of student " + (i + 1));
Scanner myObj1 = new Scanner(System.in);
String firstname = myObj1.nextLine();
System.out.println("Firstname is: " + firstname);
if (firstname.equals("end")) {
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null");
Studentz[g].Setlast("null");
Studentz[g].Setage(0);
Studentz[g].Setid(0);
}
break outerloop;
} else {
Studentz[i].Setfirst(firstname);
System.out.println("Enter last name of student " + (i + 1));
Scanner myObj2 = new Scanner(System.in);
String lastname = myObj2.nextLine();
System.out.println("Last name is: " + lastname);
Studentz[i].Setlast(lastname);;
System.out.println("Enter age of student " + (i + 1));
Scanner myObj3 = new Scanner(System.in);
int nazca = myObj3.nextInt();
System.out.println("Age is: " + nazca);
Studentz[i].Setage(nazca);
System.out.println("Enter ID of student " + (i + 1));
Scanner myObj4 = new Scanner(System.in);
int nazca1 = myObj4.nextInt();
System.out.println("ID is: " + nazca1);
Studentz[i].Setid(nazca1);
}
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
}
}
}
public class Student {
private String first;
private String last;
private int age;
private int id;
public int getid() {
return
this.id;
}
public void Studentss(String f, String l, int a, int i) {
first = f;
last = l;
age = a;
id = i;
}
public void Setfirst(String z) {
this.first = z;
}
public void Setlast(String za) {
this.last = za;
}
public void Setage(int zb) {
this.age = zb;
}
public void Setid(int zc) {
this.id = zc;
}
public String Snake() {
String snek = "Name is " + this.first + " " + this.last + " , Age is " + this.age + " ,ID is " + this.id;
return snek;
}
}
you fail here because you try to print students data before you initialized all elements of Studentz array:
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
also your code fails here by the same reason:
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null"); // NPE - no Student created yet in the array
Some Possibly Helpful Tips:
Follow Java naming rules for your variables and method names, Studentz should be studentz, even for your Arrays. I know...your tired of reading that but as you progress, you'll see how beneficial it really is.
If you can, don't use multiple Scanner objects, there is no need for that in your use-case. Declare one Scanner object and stick with it. You're probably doing this because you are using the nextLine() method after the nextInt() method and you're finding that it skips the first name prompt and provides a Null String (""). This happens because the nextInt() method does not consume the newline character when the Enter key is hit. To solve this problem you would either, place the code line myObj.nextLine(); directly under the int numberof = myObj.nextInt(); code line:
int numberof = myObj.nextInt();
myObj.nextLine(); // Consume ENTER key hit
or don't use the nextInt() method at all. Instead just stick with the nextLine() method and not worry about consumption:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
It's always a good idea to validate any input from the User (as shown above), even if they're in a for loop. Give the User an opportunity to make a correct entry, after all, typo's do happen.
Get rid of the outerLoop: label. As a matter of fact, try avoid ever using them if you can....and you can. It would only be on a relatively rare occasion where you might ever need one.
Give your variables meaningful names, at least to some extent. This can benefit you later on down the road when you want to read your old code in the future.
In your Student class you made yourself a this real nice method named Studentss(). Well, I think it should be a constructor instead and save yourself a lot of code entry for calls to Setter methods. After all, that's mostly what the constructor is for. Your Student class constructor can look like this:
public Student(String firstName, String lastName, int age, int id) {
this.first = firstName;
this.last = lastName;
this.age = age;
this.id = id;
}
And be used like this. You will notice that upon each iteration of the outer for loop, all the prompt answers are placed within variables then at the end of all those prompts the constructor is used instantiate a student object, for example:
studentz[i] = new Student(firstname, lastname, age, id);
Doing it this way mean that there is no need to make calls to Setter methods. There is nothing wrong with making setter calls, it's just easier using the constructor. This is demonstrated below:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
for (int i = 0; i < numberof; ++i) {
String firstname = "null";
String lastname = "null";
int age = 0;
int id = 0;
boolean exitOuterForLoop = false;
// Student First Name Prompt:
// (with option to End and default remaining to null's and 0's)
while (firstname.equals("null")) {
System.out.println("Enter first name of student " + (i + 1) + " (End to stop):");
firstname = myObj.nextLine();
if (firstname.equalsIgnoreCase("end")) {
firstname = "null";
//Make all remaining Student instances null and 0
for (int g = i; g < numberof; ++g) {
studentz[g] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
exitOuterForLoop = true;
break; // Exit this 'while' loop
}
// Validate first name (no numbers or crazy characters)
if (!firstname.matches("(?i)[a-z']+")) {
System.err.println("Invalid First Name! (" + firstname + ") Try Again...");
firstname = "null";
}
}
if (exitOuterForLoop) {
break; // Exit this outer 'for' loop.
}
System.out.println("Firstname is: " + firstname);
// Student Last Name Prompt
while (lastname.equals("null")) {
System.out.println("Enter last name of student " + (i + 1));
lastname = myObj.nextLine();
// Validate last name (no numbers or crazy characters)
if (!lastname.matches("(?i)[a-z']+")) {
System.err.println("Invalid Last Name! (" + lastname + ") Try Again...");
lastname = "null";
}
}
System.out.println("Last name is: " + lastname);
// Student Age Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter age of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid Age Supplied! (" + val + ") Try Again...");
val = "";
}
}
age = Integer.parseInt(val);
System.out.println("Student age is: " + age);
// Student ID Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter ID of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid ID Supplied! (" + val + ") Try Again...");
val = "";
}
}
id = Integer.parseInt(val);
System.out.println("Student ID is: " + id);
studentz[i] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
// Display the instances of Student contained within the 'studentz[]' array.
for (int c = 0; c < numberof; ++c) {
System.out.println(studentz[c].toString());
}
The snake() method is actually just another toString() method and there is nothing wrong with that however you might want to consider using StringBuilder class to create the returned string rather than doing concatenations, for example:
public String snake() {
return new StringBuilder("Name is ").append(this.first).append(" ").append(this.last)
.append(" , Age is ").append(this.age).append(" , ID is ")
.append(this.id).toString();
}
Not overly important here but it can save you memory if you do a lot concatenating with many large strings.
So my code currently has the user specify the name of the file that they want to load within the code itself but how would I make it so that when the program is run then the user will enter the location of the file that they want to load?
import java.io.*;
import java.util.*;
public class reader {
static int validresults = 0;
static int invalidresults = 0;
//used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
//checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
//also checks to make sure that there are no results that are just whitespace
public static boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
//checks to make sure that the data is an integer
public static void main(String[] args) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader("fbscores.txt"))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
//splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
validresults = validresults + 1;
System.out.println(hteam + " " + "[" + hscore + "]" + " " + ateam + " " + "[" + ascore + "]");
//output the data from the file in the format requested
}
else{
invalidresults = invalidresults + 1;
}
}
System.out.println("Total number of goals scored was " + totgoals);
//displays the the total number of goals
System.out.println("Valid number of games is " + validresults);
System.out.println("Invalid number of games is " + invalidresults);
System.out.println("EOF");
}
}
One approach would be to use a main loop asking for a file name and quitting program execution when no input is given.
Therefore I'd refactor most code of your main method into another function e.g. processFile(String fileName).
Then your main only deals with user input
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
while(true){ //keep running till we break
System.out.println("Enter filename or return blank line to quit");
String fileName = sc.nextLine();
if(fileName != null && !fileName.isEmpty()){
processFile(fileName)
}else{
break; //no user input => exit
}
}
System.out.println("bye");
}
private static processFile(String fileName){
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(fileName))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
… //rest of your original code
}
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;
}
}