I have written code for a program but I have not used methods in my code, and I was wondering how I would implement methods in the code?
I know the basic structure should have the Input, Processing, and Output.
It's all here:
import java.io.*;
public class Question {
public static void main(String[] args) throws IOException {
String name = null;
float mark, total, average, totalAverage = 0;
int totalNumberOfPeople = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("Average Calc.\n");
do {
total = 0;
System.out.print("Name: ");
try {
name = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
if(!name.equalsIgnoreCase("end")) {
totalNumberOfPeople++;
System.out.println("Enter marks for " + name + ".");
for(int i=1; i <= 5; i++) {
System.out.print("Enter mark #" + i + " of 5: ");
try {
mark = Float.parseFloat(br.readLine());
}
catch(NumberFormatException nfe) {
mark = 0;
}
catch (IOException e) {
mark = 0;
}
total = total + mark;
}
average = (float)total / 5;
System.out.println("\nThe average of the 5 marks entered is " + average);
totalAverage = totalAverage + average;
}
}
while(!name.equalsIgnoreCase("end"));
System.out.println("Total number of people = " + totalNumberOfPeople);
System.out.println("Final average = " + totalAverage / totalNumberOfPeople );
}
}
You may try to separate in methods like this :
import java.io.*;
public class Question {
public static void main(String[] args) throws IOException {
String name = null;
float mark, total, average, totalAverage = 0;
int totalNumberOfPeople = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println ("This program will calculate the average of five marks for each person.\n");
do {
total = 0;
name = readName(name, br);
if(!name.equalsIgnoreCase("end")) {
totalNumberOfPeople++;
total = getMarksForStudent(name, total, br);
totalAverage = calculateAverage(total, totalAverage);
}
}
while(!name.equalsIgnoreCase("end"));
printOutput(totalAverage, totalNumberOfPeople);
}
private static float getMarksForStudent(String name, float total, BufferedReader br) {
float mark;
System.out.println("\nPlease enter 5 marks for " + name + ".");
for(int i=1; i <= 5; i++) {
System.out.print("Enter mark #" + i + " of 5: ");
mark = getMark(br);
total = total + mark;
}
return total;
}
private static float calculateAverage(float total, float totalAverage) {
float average;
average = (float)total / 5;
System.out.println("\nThe average of the 5 marks entered is " + average);
totalAverage = totalAverage + average;
System.out.println("============================================================");
return totalAverage;
}
private static void printOutput(float totalAverage, int totalNumberOfPeople) {
System.out.println("============================================================");
System.out.println("Total number of people = " + totalNumberOfPeople);
System.out.println("The overall average for all the people entered = " + totalAverage / totalNumberOfPeople );
}
private static float getMark(BufferedReader br) {
float mark;
try {
mark = Float.parseFloat(br.readLine());
}
catch(NumberFormatException nfe) {
mark = 0;
}
catch (IOException e) {
mark = 0;
}
return mark;
}
private static String readName(String name, BufferedReader br) {
System.out.print("Please enter student name <or enter 'end' to exit> : ");
try {
name = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return name;
}
}
Related
I was working on a Uni project for the end of the semester. The program is a simple bank system. My issue is that when the program first launches it creates a "Log" folder. Then when an account object is created using a Constructor a new txt file is created in the folder with the name of the account holder. Up until here I have managed to do it.
The issue is that when closing the program via the option menu but before closing the program, all the details from all the created objects (which are stored in a array) are written in their respective files following the order they are stored in the object array but on the first run the files are created but nothing is written in them.
Then on the 2nd run if I close the program again the details are written correctly. Can I have some suggestions please I could not find anything regarding this online?
import java.util.Scanner;
import java.io.*;
public class FileManagement {
static String pathnameFile = "src\\Log";
static File directory = new File(pathnameFile);
static String[] allFiles = directory.list();
public static void createFolder() {
File logFile = new File(pathnameFile);
if (!logFile.exists()) {
logFile.mkdir();
}
}
public static void writeFiles() throws IOException {
FileWriter writer;
for (int i = 0; i < allFiles.length; i++) {
writer = new FileWriter(pathnameFile + "\\" + allFiles[i]);
writer.write("accountName= " + eBanking.accounts[i].getAccountName() + "\n");
writer.write("PIN= " + eBanking.accounts[i].getPIN() + "\n");
writer.write("balance= " + Integer.toString(eBanking.accounts[i].getBalance()) + "\n");
writer.write("Object ID stored in RAM= " + eBanking.accounts[i].toString() + "\n");
writer.close();
}
}
//original method
/*public static void readFiles() {
Scanner reader;
for (int i = 0; i < allFiles.length; i++) {
reader = new Scanner(pathnameFile + allFiles[i]);
}
}*/
//My solution
public static void readFiles() throws IOException{
if(directory.exists() == false || allFiles == null) {
return;
}
Scanner reader;
File currentFile;
String[] data = new String[4];
for(int i = 0; i < allFiles.length; i++) {
currentFile = new File(pathnameFile + "\\" +allFiles[i]);
reader = new Scanner(currentFile);
int count = 0;
while(reader.hasNextLine()) {
if(!reader.hasNext()) {
break;
}
reader.next();
data[count] = reader.next();
count++;
}
reader.close();
String accountName = data[0];
String PIN = data[1];
int balance = Integer.parseInt(data[2]);
eBanking.accounts[i] = new eBanking(accountName, PIN, balance);
}
}
}
import java.util.Scanner;
import java.io.*;
public class App {
public static eBanking currentAccount;
public static void mainMenu() throws Exception{
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("""
--------------------------------------------------------
1. Log in
2. Register
0. Exit.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
System.out.println("Please enter your account name and PIN below.");
System.out.print("Account name: ");
String accountName = input.next();
System.out.print("PIN: ");
String PIN = input.next();
System.out.println();
for (int i = 0; i < eBanking.accounts.length; i++) {
if (accountName.equals(eBanking.accounts[i].getAccountName()) && PIN.equals(eBanking.accounts[i].getPIN())) {
eBanking.accounts[i].welcome();
currentAccount = eBanking.accounts[i];
break;
}
}
menu();
}
case 2 -> {
System.out.println("Please enter the account name, PIN and inital balance of your new account.");
System.out.print("Account name:");
String accountNameRegister = input.next();
System.out.print("PIN: ");
String registerPIN = input.next();
System.out.print("Initial balance: ");
int initialBalance = input.nextInt();
currentAccount = new eBanking(accountNameRegister, registerPIN, initialBalance);
menu();
}
default -> {
FileManagement.writeFiles();
System.exit(0);
}
}
}
}
public static void menu() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("""
--------------------------------------------------------
1. Show your balance.
2. Withdraw money.
3. Deposit money.
4. Change your PIN.
5. Transfer money to another person.
0. Back.
--------------------------------------------------------
""");
int menuOption = input.nextInt();
switch (menuOption) {
case 1 -> {
currentAccount.showBalance();
}
case 2 -> {
System.out.println("Please enter the amount you want to withdraw: ");
int withdrawAmount = input.nextInt();
currentAccount.withdraw(withdrawAmount);
}
case 3 -> {
System.out.println("Please enter the amount you want to deposit: ");
int depositAmount = input.nextInt();
currentAccount.deposit(depositAmount);
}
case 4 -> {
currentAccount.changePIN();
}
case 5 -> {
System.out.println("Please enter the amount you want to send: ");
int amount = input.nextInt();
System.out.println("Please enter the account number you want to send the money to: ");
String transferAccount = input.next();// Me nextLine(); duhet ta shkruaj 2 here qe ta marri, duke perdor next(); problemi evitohet (E kam hasur edhe tek c++ kete problem)
System.out.println("The amount of money is completed");
currentAccount.transfer(amount, transferAccount);
}
case 0 -> {
return;
}
default -> {
System.out.println("Please enter a number from the menu list!");
}
}
}
}
public static void main(String[] args) throws Exception {
FileManagement.createFolder();
FileManagement.readFiles();
mainMenu();
}
}
import java.util.Scanner;
import java.io.*;
public class eBanking extends BankAccount {
// Variable declaration
Scanner input = new Scanner(System.in);
private String accountName;
private String accountID;
public static eBanking[] accounts = new eBanking[100];
// Methods
public String getAccountName() {
return accountName;
}
public void welcome() {
System.out.println("---------------------------------------------------------------------------------------");
System.out.println("Hello " + accountName + ". Welcome to eBanking! Your account number is: " + this.accountID);
}
public void transfer(int x, String str) {
boolean foundID = false;
withdraw(x);
if (initialBalance == 0) {
System.out.println("Transaction failed!");
} else if (initialBalance < x) {
for(int i = 0; i < numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += initialBalance;
System.out.println("Transaction completed!");
foundID = true;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += initialBalance;
return;
}
} else {
for(int i = 0; i <= numberOfAccount; i++) {
if (str.equals(accounts[i].accountID)) {
accounts[i].balance += x;
System.out.println("Transaction completed!");
foundID=true;
return;
}
}
if (foundID = false) {
System.out.println("Account not found. Transaction failed. Deposit reimbursed");
this.balance += x;
return;
}
}
}
// Constructors
public eBanking(String name){
int firstDigit = (int)(Math.random() * 10);
int secondDigit = (int)(Math.random() * 10);
int thirdDigit = (int)(Math.random() * 10);
int forthDigit = (int)(Math.random() * 10);
accountID = this.toString();
PIN = Integer.toString(firstDigit) + secondDigit + thirdDigit + forthDigit; //Nuk e kuptova perse nese i jap Integer.toString te pares i merr te gjitha
balance = 0; //dhe nuk duhet ta perseris per the gjitha
accountName = name;
accounts[numberOfAccount] = this;
numberOfAccount++;
System.out.println("---------------------------------------------------------------------------------------");
System.out.println(accountName + ": Your balance is " + balance + ", your PIN is: " + PIN + " and your account number is: " + accountID);
}
public eBanking(String name, String pin, int x){
if (checkPIN(pin) == false) {
System.out.println("Incorrect PIN format!");
return;
}
accountID = this.toString();
accountName = name;
balance = x;
PIN = pin;
accounts[numberOfAccount] = this;
numberOfAccount++;
welcome();
}
}
import java.util.Scanner;
public abstract class BankAccount {
// Variable declaration
protected String PIN;
protected int balance;
public static int numberOfAccount = 0;
protected static int initialBalance; // E kam perdorur per te bere menune me dinamike sidomos per metoden transfer();
//Methods
//Balance
public int getBalance() {
return balance;
}
public void showBalance() {
System.out.println("The total balance of the account is " + balance);
}
public void withdraw(int x) {
initialBalance = balance;
if (balance == 0) {
System.out.println("The deduction has failed due to lack of balance!");
return;
}
if (balance < x) {
balance = 0;
System.out.println("The deduction of " + initialBalance + " from your balance is completed!");
} else {
balance -= x;
System.out.println("The deduction of " + x + " from your balance is completed!");
}
}
public void deposit(int x) {
balance += x;
System.out.println("You have made a deposit of " + x + " and your current balance is " + balance);
}
//PIN
public String getPIN() {
return PIN;
}
public void changePIN() {
Scanner input = new Scanner(System.in);
System.out.print("Please enter your previous PIN: ");
String tryPIN = input.nextLine();
if (tryPIN.equals(PIN)) {
System.out.print("Please enter your new PIN: ");
String newPIN = input.nextLine();
if (checkPIN(newPIN) == false) {
System.out.println("The PIN is not in the correct format!");
} else {
System.out.println("The PIN has been changed");
PIN = newPIN;
}
} else {
System.out.println("The PIN does not match!");
}
}
protected static boolean checkPIN(String str) {
boolean isValid;
if(str.length() != 4) {
isValid = false;
} else {
try {
int x = Integer.parseInt(str);
isValid = true;
} catch (NumberFormatException e) {
isValid = false;
}
}
return isValid;
}
//Kjo metode duhet per testim
public void getDetails() {
System.out.println(balance + " and PIN " + PIN);
}
}
I have updated the post showing how I fixed it and providing all my classes. Please do not mind the messy code as I am first trying it out with a switch and then will ditch that when the time comes and use GUI as soon as I learn how to use it. Also I know that the classes can be organized better but BankAccount and eBanking are 2 salvaged classes I used on a different exercise.
I think I have found a solution. I just remembered that when using FileWriter if a file does not exist it creates one automatically. So i have cancelled the method which creates a file whenever a new object is created and now whenever the program is closed the files are created if needed or overwritten if they already exist.
I have provided all the current code on my program and the fix I implemented on FileManagment class
import java.util.Scanner;
public class InputCalculator {
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
boolean first = true;
int sum = 0;
int count = 0;
int avg = 0;
while(true){
int number = scanner.nextInt();
boolean isAnInt = scanner.hasNextInt();
if(isAnInt){
sum += number;
count++;
avg = Math.round((sum)/count);
}else{
System.out.println("SUM = " + sum + " AVG = " + avg);
break;
}
scanner.nextLine();
}
scanner.close();
}
}
When input is "1, 2, 3, 4, 5, a", I think it's not reading the input 5, resulting sum = 10 and avg = 2! Why it's happening?
By the way it's just a method not whole code!
When scanner.nextInt() provides you '5', the next line 'scanner.hasNextInt() is false. Just change line order
import java.util.Scanner;
public class InputCalculator {
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
boolean first = true;
int sum = 0;
int count = 0;
int avg = 0;
while(true){
boolean isAnInt = scanner.hasNextInt();
if(isAnInt){
int number = scanner.nextInt();
sum += number;
count++;
avg = Math.round((sum)/count);
}else{
System.out.println("SUM = " + sum + " AVG = " + avg);
break;
}
scanner.nextLine();
}
scanner.close();
}
}
you can also clean the code like
import java.util.Scanner;
public class InputCalculator {
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
int sum = 0;
int count = 0;
while( scanner.hasNextInt() ){
int number = scanner.nextInt();
sum += number;
count++;
}
scanner.close();
double avg = Math.round((sum)/count);
System.out.println("SUM = " + sum + " AVG = " + avg);
}
}
I have a this small code:
Scanner vloz = new Scanner(System.in);
int cisla = 0;
int i = 0;
while(i < 10){
try {
System.out.println("Vloz cislo " + i + ":");
int cislo = Integer.parseInt(vloz.nextLine());
++i;
cisla = cisla + cislo;
}
catch(InputMismatchException exception){
System.out.println("Nevlozil si cislo!");
}
}
float priemer = cisla / i;
System.out.println("Priemer cisel je " + priemer + ".");
}
}
but always when I run it and type other charakters then int, program crash and did not run through "catch".
The goal of the program is when the other then int is typed show error message, do not add to int i and give another option to the user to add the intenger.
You need to be catching a NumberFormatException rather than an InputMismatchException like so:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner vloz = new Scanner(System.in);
int cisla = 0;
int i = 0;
while(i < 10){
try {
System.out.print("Vloz cislo " + i + ":");
int cislo = Integer.parseInt(vloz.nextLine());
i++;
cisla = cisla + cislo;
} catch(NumberFormatException exception) {
System.out.println("Nevlozil si cislo!");
}
}
float priemer = cisla / i;
System.out.println("Priemer cisel je " + priemer + ".");
}
}
Try it here!
You catch the wrong exception. The method parseInt(String s) throws a NumberFormatException not a InputMismatchException. Change your catch clause to catch(NumberFormatException exception).
import java.util.*;
public class demo{
public static void main (String []args ){
Scanner vloz = new Scanner(System.in);
int cisla = 0;
int i = 0;
while(i < 10){
try {
System.out.println("Vloz cislo " + i + ":");
int cislo = Integer.parseInt(vloz.nextLine());
++i;
cisla = cisla + cislo;
}
catch(InputMismatchException exception){
System.out.println("Nevlozil si cislo!");
}
}
float priemer = cisla / i;
System.out.println("Priemer cisel je " + priemer + ".");
}
}
I'm not sure why it crashed but this code works. I think you may have forgotten to import.java.*;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Here is my error message
Exception in thread "main" java.lang.IllegalArgumentException
at TestGrades.setRaceTime(TestGrade.java:49)
at GradeDriver.getGradeData(GradeDriver.java:40)
at Grade Driver.main(GradeDriver.java:26)
Java-Class:
import java.util.*;
import java.io.*;
public class GradeDriver{
public static void main(String[] args){
double[] averageInfo = new double[3];
Scanner console = new Scanner(System.in);
String[] fileName = new String[2];
for(int i = 0; i < args.length; i++){
fileName[i] = args[i];
}
Scanner input = getInputFile(console, fileName);
PrintStream output = getOutputFile(console, fileName);
TestGrades[] grades = getGradeData(input);
showGradeInfo(output, grades);
getAverageInfo(averageInfo, grades);
showAverageInfo(output, averageInfo, grades[0]);
}
public static TestGrades[] getGradeData(Scanner input) {
int numberOfGrades = input.nextInt();
TestGrades[] grades = new TestGrades[numberOfGrades];
for(int driver = 0; driver < numberOfGrades && input.hasNext(); driver++) {
grades[driver] = new TestGrades(input.next(), input.next());
for (int grade = 1; grade <= 4; grade++) {
grades[driver].setRaceTime(grade , input.nextDouble());
}
}
return grades;
}
public static void showGradeInfo (PrintStream output, TestGrades[] grades) {
for (int i = 0; i < grades.length; i++) {
output.print(( i + 1 ) + ". " + grades[i] + "\n");
}
}
public static void getAverageInfo (double[] info, TestGrades[] grades) {
double low = 20.0;
double high = 0.0;
double average = 0.0;
double totalAverage = 0.0;
for (int i = 0; i < grades.length; i++) {
average = grades[i].getGradeAverage();
if (average > high) {
high = average;
}
if (average < low) {
low = average;
}
totalAverage = totalAverage + average;
}
info[0] = low;
info[1] = high;
info[2] = totalAverage/grades[0].getCounter();
}
public static void showAverageInfo(PrintStream o, double[] info, TestGrades d) {
String[] s = {"Total number of students: "};
o.printf("\n%d. %s %d\n", 1, s[0], d.getCounter());
for (int i = 1; i <info.length; i++) {
o.printf("%d. %s %.2f/n", i + i, s[i], info[i - 1]);
}
}
public static Scanner getInputFile(Scanner console, String[] inFileName) {
boolean fileFound = false;
Scanner s = null;
if (inFileName[0] == null) {
System.out.print("Please enter the input file name: ");
inFileName[0] = console.nextLine();
}
do {
try {
s = new Scanner(new File(inFileName[0]));
fileFound = true;
}
catch (FileNotFoundException e) {
System.out.println("Cannot read file: " + e) ;
System.out.println("Enter the correct input file name: ");
inFileName[0] = console.nextLine();
}
}
while (!fileFound);
return s;
}
public static PrintStream getOutputFile (Scanner console, String[] outFileName) {
boolean fileFound = false;
PrintStream pS = null;
if (outFileName[1] == null) {
System.out.print("Please enter output file name: ");
outFileName[1] = console.nextLine();
}
do {
try {
pS = new PrintStream (new File (outFileName[1]));
fileFound = true;
}
catch (FileNotFoundException e2) {
System.out.println("Cannot read file: " + e2);
System.out.println("Enter a correct output file name: ");
outFileName[1] = console.nextLine();
}
}
while(!fileFound);
return pS;
}
}
import java.io.*;
import java.util.*;
public class TestGrades {
private static int gradeCount = 0;
private String firstName;
private String lastName;
private double[] raceTime = new double[4];
public TestGrades(String fName, String lName) {
firstName = fName;
lastName = lName;
gradeCount++;
}
private String getFirstName() {
return firstName;
}
private String getLastName() {
return lastName;
}
public double getGradeAverage() {
double highest = 0.0;
double sum = 0.0;
for (int i = 0; i < raceTime.length; i++) {
sum += raceTime[i];
if (raceTime[i] > highest) {
highest = raceTime[i];
}
}
sum = sum - highest;
sum = sum / 3;
return sum;
}
public void setRaceTime(int grade, double time) {
if (grade < 1 || grade > 4 || time < 0.0 || time > 15.0) {
throw new IllegalArgumentException();
}
raceTime[grade - 1 ] = time;
}
public int getCounter() {
return gradeCount;
}
public String toString() {
return (firstName + " " + lastName);
}
}
Any help would really be appreciated!
It looks like you threw the IllegalArgumentException yourself.
if (grade < 1 || grade > 4 || time < 0.0 || time > 15.0) {
throw new IllegalArgumentException();
}
But you didn't supply a message as an argument to the constructor. You should supply a message that will make more sense when displayed, for example:
throw new IllegalArgumentException("grade (" + grade + ") or time (" + time +
") outside of legal range.");
You are probably entering a time value outside of your range.
You are throwing the exception yourself...
if (grade < 1 || grade > 4 || time < 0.0 || time > 15.0) {
throw new IllegalArgumentException();
}
I'm having diffuculties with sorting the input i want it to sort by lowest time first. I'm new to java so i dont know so much I've done a guees a number game but I cant manage to sort the highscore by lowest time here is what i've done so far.
import java.io.*;
import java.util.*;
public class teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeest {
private static void start() throws IOException {
int number = (int) (Math.random() * 1001);
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
String scorefile = "p-lista_java";
int försök = 0;
int gissning = 0;
String namn;
String line = null;
String y;
String n;
String val ;
String quit = "quit";
System.out.println("Hello and welcome to this guessing game" +
"\nStart guessing it's a number between 1 and 1000:");
long startTime = System.currentTimeMillis();
while (true){
System.out.print("\nEnter your guess: ");
gissning = input.nextInt();
försök++;
if (gissning == number ){
long endTime = System.currentTimeMillis();
long gameTime = endTime - startTime;
System.out.println("Yes, the number is " + number +
"\nYou got it after " + försök + " guesses " + " times in " + (int)(gameTime/1000) + " seconds.");
System.out.print("Please enter your name: ");
namn = reader.readLine();
try {
BufferedWriter outfile
= new BufferedWriter(new FileWriter(scorefile, true));
outfile.write(namn + " " + försök +"\t" + (int)(gameTime/1000) + "\n");
outfile.close();
} catch (IOException exception) {
}
break;
}
if( gissning < 1 || gissning > 1000 ){
System.out.println("Stupid guess! I wont count that..." );
--försök;
}
else if (gissning > number)
System.out.println(" Your guess is too high");
else
System.out.println("Your guess is too low");
}
try {
BufferedReader infile
= new BufferedReader(new FileReader(scorefile));
while ((line = infile.readLine()) != null) {
System.out.println(line);
}
infile.close();
} catch (IOException exception) {
}
System.out.println("Do you want to continue (Y/N)?");
val=reader.readLine();
if ((val.equals("y"))||(val.equals("Y"))){
teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeest.start();
}
else
System.out.print("Thanks for playing");
System.exit(0);
}
}
Create a value object that holds all your scoring, time and other details. Create a Comparator that compares the components between two of these holders. The sorting can be achieved by creating a Set of Holder with a Comparator.
If you wish to sort by other properties in a different order simply update the Comparator as appropriate.
Holder {
long time;
int score;
String name;
}
Comparator<Holder> {
int compare( Holder holder, Holder other ){
int result = holder.time - other.time;
if( 0 == result ){
result = holder.score - other.score;
}
return result;
}
}