I am having trouble on a program and I can't seem to fix the problem. I have a team roster program that gives the option of replacing a player's number and rating, but when that option is used the loop keeps going and it won't end and go back to the menu for the other options. If anyone could help point me in the right direction it would be appreciated.
import java.util.Scanner;
class PlayerRoster {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
int[] playerJerseyNumber = new int[5];
int[] playerRating = new int[5];
for (int i = 0; i < 5; i++) {
//Taking jersey number till it is in the range of 0-99
while (true) {
System.out.println("Enter player " + (i + 1)
+ "'s jersey number:");
playerJerseyNumber[i] = scanner.nextInt();
if (0 <= playerJerseyNumber[i] && playerJerseyNumber[i] <= 99) {
break;
} else {
System.out.println("Jersey number must be 0-99");
}
}
//Taking playerRating till it is in the range of 1-9
while (true) {
System.out.println("Enter player " + (i + 1) + "'s rating:");
playerRating[i] = scanner.nextInt();
if (1 <= playerRating[i] && playerRating[i] <= 9) {
break;
} else {
System.out.println("Player's ratings must be 1-9");
}
}
System.out.println("");
}
System.out.println("ROSTER");
//Displaying the rosters
for (int i = 0; i < 5; i++) {
System.out.println("Player " + (i + 1) + " -- Jersey number: "
+ playerJerseyNumber[i] + ", Rating: "
+ playerRating[i]);
}
System.out.println("");
//Printing the menu
do {
System.out.println("MENU " + "u - Update player rating");
System.out.println("a - Output players above a rating");
System.out.println("r - Replace player");
System.out.println("o - Output roster");
System.out.println("q - Quit");
System.out.println("");
System.out.println("Choose an option:");
char choice = scanner.next().charAt(0);
switch (choice) {
case 'u': {
System.out.println("Enter a jersey number:");
int playerJersey = scanner.nextInt();
System.out.println("Enter a new rating for player:");
int newRating = scanner.nextInt();
for (int i = 0; i < 5; i++) {
if (playerJerseyNumber[i] == playerJersey) {
playerRating[i] = newRating;
break;
}
}
}
break;
case 'a': {
System.out.println("Enter a rating:");
int aboveRating = scanner.nextInt();
System.out.println("ABOVE " + aboveRating);
for (int i = 0; i < 5; i++) {
if (playerRating[i] > aboveRating) {
System.out.println("Player " + (i + 1)
+ " -- Jersey number: "
+ playerJerseyNumber[i] + ", Rating: "
+ playerRating[i]);
}
}
}
break;
case 'r': {
boolean flag = true;
do {
System.out.println("Enter a jersey number:");
int newRating, playerNewJersey;
int playerJersey = scanner.nextInt();
for (int i = 0; i < 5; i++) {
if ((playerJerseyNumber[i] == playerJersey)) {
//Taking jersey number till it is in the range of 0-99
while (true) {
System.out.println("Enter a new jersey number:");
playerNewJersey = scanner.nextInt();
if (0 <= playerNewJersey && playerNewJersey <= 99) {
break;
} else {
System.out.println("Jersey number must be 0-99");
}
}
//Taking playerRating till it is in the range of 1-9
while (true) {
System.out.println("Enter a new rating for player:");
newRating = scanner.nextInt();
if (1 <= newRating && newRating <= 9) {
break;
} else {
System.out.println("Player's ratings must be 1-9");
}
}
playerJerseyNumber[i] = playerNewJersey;
playerJerseyNumber[i] = playerJersey;
playerRating[i] = newRating;
flag = false;
break;
}
}
if (!flag) {
System.out.println("Error: Invalid Jersey Number... Try Again...");
}
} while (flag);
}
break;
case 'o': {
System.out.println("ROSTER");
for (int i = 0; i < 5; i++) {
System.out.println("Player " + (i + 1)
+ " -- Jersey number: " + playerJerseyNumber[i]
+ ", Rating: " + playerRating[i]);
}
}
break;
case 'q':
break;
default:
break;
}
if (choice == 'q') break;
} while (true);
} catch (Exception e) {
}
return;
}
}
if (flag) {
System.out.println("Error: Invalid Jersey Number... Try Again...");
} }
Removing the ! solves the problem. Also, a few lines above it there is
playerJerseyNumber[i] = playerNewJersey;
playerJerseyNumber[i] = playerJersey;
I don't understand why you need to reassign it to playerJersey. This would cause the jersey number to not get updated.
Related
All menu options work besides menu option 1 when i select 1 it just repeats the menu instead of asking me to type the name and repeat it 20 time, if anyone can help me debug I would appreciate it.
Get the user’s first name and echo it back out 20 times.
Get the Store user’s age and double it and display the age and the doubled age.
Using the age from #2 output one of the following statements.Since you are 99 years old, you are a teenagerb. Since you are 99 years old, you are NOT a teenager
Get a single integer between 3 and 50 from the user. Create a triangle of X’s with the integer inputted rows. The triangle needs to be displayed on the screen and in a text document named triangle.txt.
The code :
//Menu.java
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("\n::MENU::");
System.out.println("1.Echo Name");
System.out.println("2.Double Your Age");
System.out.println("3.Check Teenager or not");
System.out.println("4.Display Triangle");
System.out.println("5.Exit");
System.out.print("Enter Choice:");
choice = sc.nextInt();
switch (choice) {
case 1: {
System.out.print("Enter your name");
String name = sc.nextLine();
for (int i = 1; i <= 20; i++) {
System.out.println(name);
}
break;
}
case 2: {
int age;
System.out.print("Enter age :");
age = sc.nextInt();
System.out.println("Your age :" + age);
System.out.println("Doubled age :" + (2 * age));
break;
}
case 3: {
int age;
System.out.print("Enter age :");
age = sc.nextInt();
if (age >= 13 && age <= 19) {
System.out.println("Since you are " + age + " years old.Your are a Teenager");
} else {
System.out.println("Since you are " + age + " years old.Your are not a Teenager");
}
break;
}
case 4: {
int rows;
do {
System.out.print("Enter a number (between 3 and 50):");
rows = sc.nextInt();
if (rows < 3 || rows > 50) {
System.out.println("** Invalid.Must be between 3 and 50 **");
}
} while (rows < 3 || rows > 50);
printTriangle(rows);
break;
}
case 5: {
break;
}
default: {
System.out.println("** Invalid Choice **");
break;
}
}
} while (choice != 5);
}
private static void printTriangle(int size) {
char ch = '*';
for (int a = 0; a < 2 * size - 1; a++) {
if (a % 2 == 0) {
for (int b = 0; b < (2 * size - 1) - a; b++) {
System.out.print(" ");
}
for (int c = 0; c <= a; c++) {
System.out.print(ch + " ");
}
System.out.println();
}
}
}
}
After taking input for choice you have to write sc.nextLine() like
choice = sc.nextInt();
sc.nextLine();
switch (choice) {
because nextInt() only reads in until it's found the int and then stops.
You have to do nextLine() because the input stream still has a newline character and possibly other non-int data on the line. Calling nextLine() reads in whatever data is left, including the enter the user pressed between entering an int and entering a String.
To read both strings and integer value, a solution is to use two Scanners:
//Menu.java
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner intScanner = new Scanner(System.in);
//added new separate scanner for string
Scanner stringScanner = new Scanner(System.in);
int choice;
do {
int age;
System.out.println("\n::MENU::");
System.out.println("1.Echo Name");
System.out.println("2.Double Your Age");
System.out.println("3.Check Teenager or not");
System.out.println("4.Display Triangle");
System.out.println("5.Exit");
System.out.print("Enter Choice: ");
choice = intScanner.nextInt();
switch (choice) {
case 1: {
System.out.print("Enter your name: ");
String name = stringScanner.nextLine();
for (int i = 1; i <= 20; i++) {
System.out.println(name);
}
break;
}
case 2: {
System.out.print("Enter age :");
age = intScanner.nextInt();
System.out.println("Your age :" + age);
System.out.println("Doubled age :" + (2 * age));
break;
}
case 3: {
System.out.print("Enter age :");
age = intScanner.nextInt();
if (age >= 13 && age <= 19) {
System.out.println("Since you are " + age + " years old.Your are a Teenager");
} else {
System.out.println("Since you are " + age + " years old.Your are not a Teenager");
}
break;
}
case 4: {
int rows;
do {
System.out.print("Enter a number (between 3 and 50):");
rows = intScanner.nextInt();
if (rows < 3 || rows > 50) {
System.out.println("** Invalid.Must be between 3 and 50 **");
}
} while (rows < 3 || rows > 50);
printTriangle(rows);
break;
}
case 5: {
System.out.println("You pressed Exit");
break;
}
default: {
System.out.println("** Invalid Choice **");
break;
}
}
} while (choice != 5);
}
private static void printTriangle(int size) {
char ch = '*';
for (int a = 0; a < 2 * size - 1; a++) {
if (a % 2 == 0) {
for (int b = 0; b < (2 * size - 1) - a; b++) {
System.out.print(" ");
}
for (int c = 0; c <= a; c++) {
System.out.print(ch + " ");
}
System.out.println();
}
}
}
}
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Level, Str, Dex, Con, Int, Wis, Cha, HP, Bonus, bonusCounter;
System.out.print("Enter Level : ");
Level = sc.nextInt();
if (Level <= 0) {
System.err.println("Invalid Input!!");
System.exit(0);
}
System.out.println("Enter Str :");
Str = sc.nextInt();
if (Str <= 0) {
System.err.println("Invalid Input!!");
System.exit(0);
}
System.out.println("Enter Dex :");
Dex = sc.nextInt();
if (Dex <= 0) {
System.err.println("Invalid Input!!");
System.exit(0);
}
System.out.println("Enter Con :");
Con = sc.nextInt();
if (Con <= 0) {
System.err.println("Invalid Input!!");
System.exit(0);
}
System.out.println("Enter Int :");
Int = sc.nextInt();
if (Int <= 0) {
System.err.println("Invalid Input!!");
System.exit(0);
}
System.out.println("Enter Wis :");
Wis = sc.nextInt();
if (Wis <= 0) {
System.err.println("Invalid Input!!");
System.exit(0);
}
System.out.println("Enter Cha :");
Cha = sc.nextInt();
if (Cha <= 0) {
System.err.println("Invalid Input!!");
System.exit(0);
}
System.out.println("\nLevel : " + Level);
if (Str == 10) {
Bonus = 0;
System.out.println("Str : " + Str + "[" + Bonus + "]");
}
else if (Str < 10) {
Bonus = 0;
bonusCounter = Str;
while (bonusCounter <= 10) {
if (bonusCounter % 2 == 1) {
Bonus=+1;
}
bonusCounter=+1;
}
System.out.println("Str : " + Str + "[-" + Bonus + "]");
}
else {
Bonus = 0;
bonusCounter = 10;
while (bonusCounter <= Str) {
if (bonusCounter % 2 == 0) {
Bonus=+1;
}
bonusCounter=+1;
}
System.out.println("Str : " + Str + "[+" + Bonus + "]");
}
The code should calculate a bonus value for the 6 variables. Each Bonus should be 0 at 10, cumulative +1 for each even number above 10 and -1 for each odd number below 10. This is just the first part of my code. The same method applies for the 6 variables. There is logical error in the while condition so the code doesn't produce the output. What can i do to fix it?
Replace
bonusCounter = +1;
with
bonusCounter += 1;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Hangman {
public static void main(String[] args) {
String playAgainMsg = "Would you like to play again?";
String pickCategoryMsg = "You've tried all the words in this category!\nWould you like to choose another category?";
int winCounter = 0, loseCounter = 0, score = 0;
String[] words;
int attempts = 0;
String wordToGuess;
boolean playCategory = true, playGame = true;
int totalCounter = 0, counter;
while (playCategory && playGame)
{
while (playCategory && playGame) {
words = getWords();
counter = 0;
while (playGame && counter < words.length) {
wordToGuess = words[counter++];
if (playHangman(wordToGuess)) {
winCounter++;
System.out.println("You win! You have won " + winCounter + " game(s)." + " You have lost " + loseCounter + " game(s).");
} else {
loseCounter++;
System.out.println("You lose! You have lost " + loseCounter + " game(s)." + " You have won " + winCounter + " game(s).");
}
if (counter < words.length) playGame = askYesNoQuestion(playAgainMsg);
}
if (playGame) playCategory = askYesNoQuestion(pickCategoryMsg);
}
}
}
public static boolean playHangman(String wordToGuess) {
String[] computerWord = new String[wordToGuess.length()];
String[] wordWithDashes = new String[wordToGuess.length()];
for (int i = 0; i < computerWord.length; i++) {
computerWord[i] = wordToGuess.substring(i, i+1);
wordWithDashes[i] = "_";
}
Scanner in = new Scanner(System.in);
int attempts = 0, maxAttempts = 7;
boolean won = false;
int points = 0;
while (attempts < maxAttempts && !won) {
String displayWord = "";
for (String s : wordWithDashes) displayWord += " " + s;
System.out.println("\nWord is:" + displayWord);
System.out.print("\nEnter a letter or guess the whole word: ");
String guess = in.nextLine().toLowerCase();
if (guess.length() > 1 && guess.equals(wordToGuess)) {
won = true;
} else if (wordToGuess.indexOf(guess) != -1) {
boolean dashes = false;
for (int i = 0; i < computerWord.length; i++) {
if (computerWord[i].equals(guess)) wordWithDashes[i] = guess;
else if (wordWithDashes[i].equals("_")) dashes = true;
}
won = !dashes; // If there are no dashes left, the whole word has been guessed
} else {
drawHangmanDiagram(attempts);
System.out.println("You've used " + ++attempts + " out of " + maxAttempts + " attempts.");
}
}
int score = 0;
score = scoreGame(attempts);
System.out.println("Your score is: " + score);
return won;
}
//should take in a failure int from the main method that increments after every failed attempt
public static void drawHangmanDiagram(int failure)
{
if (failure == 0)
System.out.println("\t+--+\n\t| |\n\t|\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 1)
System.out.println("\t+--+\n\t| |\n\t| #\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 2)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 3)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| / \\\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 4)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 5)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| /\n\t|\n\t|\n\t+--");
else if (failure == 6)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| / \\\n\t|\n\t|\n\t+--");
}
// Asks user a yes/no question, ensures valid input
public static boolean askYesNoQuestion(String message) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println(message + " (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
public static boolean askForCategory(int category) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("\nWould you like to play again? (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
// Asks the user to pick a category
public static String[] getWords() {
String[] programming = {"java", "pascal", "python", "javascript", "fortran", "cobol"};
String[] sports = {"gymnastics", "badminton", "athletics", "soccer", "curling", "snooker", "hurling", "gaelic", "football", "darts"};
String[] result = {""};
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("Pick a category:\n1. Programming\n2. Sports");
answer = in.nextLine().toLowerCase();
if (answer.matches("[1-2]")) validAnswer = true;
else System.out.println("Invalid input! Enter the number of the category you want.");
} while (!validAnswer);
int selection = Integer.parseInt(answer);
switch (selection) {
case 1: result = randomOrder(programming); break;
case 2: result = randomOrder(sports); break;
}
return result;
}
// Sorts a String array in random order
public static String[] randomOrder(String[] array) {
int[] order = uniqueRandoms(array.length);
String[] result = new String[array.length];
for (int i = 0; i < order.length; i++) {
result[i] = array[order[i]];
}
return result;
}
// Generates an array of n random numbers from 0 to n-1
public static int[] uniqueRandoms(int n) {
int[] array = new int[n];
int random, duplicateIndex;
for (int i = 0; i < n; ) {
random = (int) (Math.random() * n);
array[i] = random;
for (duplicateIndex = 0; array[duplicateIndex] != random; duplicateIndex++);
if (duplicateIndex == i) i++;
}
return array;
}
public static int scoreGame(int attempts)
{
int score = 0;
switch (attempts)
{
case 0: score = 70; break;
case 1: score = 60; break;
case 2: score = 50; break;
case 3: score = 40; break;
case 4: score = 30; break;
case 5: score = 20; break;
case 6: score = 10; break;
case 7: score = 0; break;
}
return score;
}
}
I have got it working so that it keeps count of the games won and lost, as well as assigning a score based on the amount of attempts/lives saved but I haven't been able to find a way to get it to keep a total score for all of the games played. Each game unfortunately has a seperate score. If anyone can advise me on a way of doing this, it would be greatly appreciated.
Create an int totalScore variable where winCounter, loseCounter and score are defined. Then increment it after each call to scoreGame()
score = scoreGame(attempts);
totalScore += score;
System.out.println("Your score is: " + score);
If you want to permanently save statistics between sessions then it's a whole nother story. You would need to write your scores to a file after each round and then start your program by reading this score file. It's hardly impossible, but requires a bit more code.
My variable names are pretty stupid near the bottom but that's not the point. Line 110 says that I'm making an else statement without the if and I'm nearly certain the if is there. Please help in any way you can.
Thank you
import java.util.*;
public class hw7
{
public static void main(String[] args)
{
int turnScores = 0;
int totalScores = 0;
int turnScores2 = 0;
int totalScores2 = 0;
int dice;
int dice2;
String input = "r";
char repeat;
boolean peppers;
peppers = true;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to the game of Pig!\n");
while(totalScores < 20 || totalScores2 < 20)
{
do
{
dice = randomNumbers.nextInt(6) + 1;
System.out.println("You rolled: " + dice);
if(dice == 1)
{
turnScores = 0;
System.out.print("Your lose your turn!");
System.out.println("Your Total is " + totalScores);
break;
}
else
{
turnScores += dice;
System.out.print("Your turn score is " + turnScores);
System.out.println(" and your total scores is " + totalScores);
System.out.println("If you hold, you will have " + turnScores
+ " points.");
System.out.println("Enter 'r' to roll again, 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'h')
{
break;
}
}
}
while(input.equalsIgnoreCase("r") || dice != 1);
totalScores += turnScores;
peppers = peppers(turnScores, turnScores2);
System.out.println("Your scores is " + totalScores);
turnScores = 0;
System.out.println();
System.out.println("It is the computer's turn.");
do
{
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("The computer rolled: " + dice2);
if(dice2 == 1)
{
turnScores2 = 0;
System.out.print("The computer lost its turn!");
System.out.println(" Computer total is " + totalScores2);
break;
}
else
{
turnScores2 += dice2;
if(turnScores2 >= 20 || (totalScores2 + turnScores2) >= 20 )
{
System.out.println("The computer holds");
break;
}
}
}
while(dice2 != 1 || turnScores2 < 20);
totalScores2 += turnScores2;
System.out.println("The computer's scores is " + totalScores2 + "\n");
turnScores2 = 0;
}
}
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20);
{
done = false;
System.out.println(" YOU WIN!!!");
return done;
}
else (ghost >= 20);
{
done = false;
System.out.println(" COMPUTER WINS");
return done;
}
/*else
{
return done;
}
*/
}
}
Try removing the semicolons in if(chili >= 20); and else (ghost >= 20);.
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20)
{
done = false;
System.out.println(" YOU WIN!!!");
}
else if (ghost >= 20)
{
System.out.println(" COMPUTER WINS");
}
return done;
}
replace
else (ghost >= 20);
with
else if (ghost >= 20)
and remove the semicolons after the if-statement.
The problem is when I create three accounts for example 1, 2 and 3. Then delete 2 and add a new one the result is 1, 3 and 2, everything ok. When I add another account the results is 1, 3, 2, 3. Adding yet another one gets me 1, 3, 2, 3, 4.
The values are stored in a text file from where the array reads and writes them to.
The problem is I get the same account number twice. Also just making it always increment by one isn't ok, because I need it to fill the gaps from the deleted accounts.
Can't figure out the problem and would really appreciate some help!
The code responsible:
private int choice;
public String name;
public int accountNr = 1;
public int cash;
public int funds;
private boolean run = true;
private int index = 0;
private int index1 = 0;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
ArrayList<Account> acc = new ArrayList<Account>();
ArrayList<TransferHistory> transferHistory = new ArrayList<TransferHistory>();
public int c;
public int amount;
private int c1;
private int size;
ReaderWriter io = new ReaderWriter();
private int account0;
private Account ac;
private int account1;
private int account3;
private int account2;
private int viewAnswer;
private int deleteAnswer;
private String s = "";
public void startMessage() {
System.out.println("***** Welcome to our bank system *****");
}
public void mainMenu() {
while (run == true) {
acc = io.readFromFile();
Scanner scan = new Scanner(System.in);
System.out.println("**** Main menu ****");
System.out.println("1. Create a new account");
System.out.println("2. Deposit/Withdraw from account");
System.out.println("3. Transfer money");
System.out.println("4. View the account properties");
System.out.println("5. View one account properties");
System.out.println("6. Delete account");
System.out.println("7. Show transfer history");
System.out.println("8. Show transfer history for one account");
System.out.println("9. Quit");
try {
choice = scan.nextInt();
} catch (InputMismatchException e) {
System.out.println("Please enter valid choice");
}
if (choice == 1) {
addAccount();
}
if (choice == 2) {
transfer();
}
if (choice == 3) {
transferWithin();
}
if (choice == 4) {
view();
}
if (choice == 5) {
viewOne();
}
if (choice == 6) {
delete();
}
if (choice == 7) {
showTransfers();
}
if (choice == 8) {
showOneTransfer();
}
if (choice == 9) {
quit();
}
}
}
public void addAccount() {
System.out.print("Enter your name: ");
name = scan.next();
for (int i = 0; i < acc.size(); i++) {
if(acc.get(i).getAcc() == accountNr) {
accountNr++;
}
}
System.out.println("Your account nr is: " + accountNr);
System.out.print("Enter your starting funds: ");
try {
cash = scan.nextInt();
if(cash < 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
index = acc.size();
acc.add(index, new Account(name, accountNr, cash)); //Add new account object to specified element in acc arraylist
index = acc.size();
io.writeToFile(acc);
} catch (InputMismatchException e) {
System.out.println("The scanner couldn´t read your input, use digits next time.");
System.out.println("The funds for this account has been set to zero, use transfers to adjust");
scan.reset();
}
}
public void transfer() {
System.out.print("Enter account number to withdraw/deposit to: ");
try {
account1 = Integer.parseInt(scan.nextLine());
if(account1 > acc.size() || account1 <= 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.println("Enter a number!");
scan.reset();
return;
}
System.out.print("Enter a positive number to deposit and negative to withdraw: ");
try {
funds = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
System.out.println("Enter a number!");
scan.reset();
return;
}
for (int i = 0; i < acc.size() + 1; i++) {
if (account1 == i) {
if (funds > 0) {
acc.get(account1 - 1).setCash(funds + acc.get(account1 - 1).getCash());
System.out.println("The amount is changed to " + acc.get(account1 - 1).getCash());
index1 = transferHistory.size();
transferHistory.add(index1, new TransferHistory(account1, funds, account1));
io.writeTransferedToFile(transferHistory);
index1 = transferHistory.size();
}
if (funds < 0 && funds + acc.get(account1 - 1).getCash() > 0) {
acc.get(account1 - 1).setCash(funds + acc.get(account1 - 1).getCash());
System.out.println("The amount is changed to " + acc.get(account1 - 1).getCash());
index1 = transferHistory.size();
transferHistory.add(index1, new TransferHistory(account1, funds, account1));
io.writeTransferedToFile(transferHistory);
index1 = transferHistory.size();
} else if (acc.get(account1 - 1).getCash() + funds < 0) {
System.out.println("This transaction is not allowed since the balance will be negative");
}
}
}
io.writeToFile(acc);
}
public void view() {
acc = io.readFromFile();
for (int i = 0; i < acc.size(); i++) {
System.out.println(s);
System.out.println("Account name: " + acc.get(i).tempName);
System.out.println("Account number: " + acc.get(i).tempAccNr);
System.out.println("Funds: " + acc.get(i).tempCash);
}
if (acc.isEmpty()) {
System.out.println("No accounts to show");
}
}
public void quit() {
System.exit(0);
}
private void transferWithin() {
System.out.print("Enter account you want to transfer from: ");
try {
account3 = Integer.parseInt(scan.nextLine());
if(account3 > acc.size() || account3 <= 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.print("Enter a account number: ");
scan.reset();
return;
}
System.out.print("Enter amount you want to transfer: ");
try {
amount = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
System.out.print("Enter a number: ");
scan.reset();
return;
}
System.out.print("Enter account you want to transfer to: ");
try {
account2 = Integer.parseInt(scan.nextLine());
if(account2 > acc.size() || account2 <= 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.print("Enter a account number:");
scan.reset();
return;
}
for (int i = 0; i < acc.size() + 1; i++) {
if (i == account3) {
c = acc.get(i - 1).getCash();
if (c - amount >= 0) {
acc.get(i - 1).setCash(c - amount);
System.out.println("Funds in account: " + acc.get(i - 1).getAcc() + " " + acc.get(i - 1).getCash());
index1 = transferHistory.size();
transferHistory.add(index1, new TransferHistory(account3, amount, account2));
io.writeTransferedToFile(transferHistory);
index1 = transferHistory.size();
} else if (c - amount < 0) {
System.out.println("Not enough funds in account");
mainMenu();
}
}
}
for (int j = 0; j < acc.size() + 1; j++) {
if (j == account2) {
c1 = acc.get(j - 1).getCash();
acc.get(j - 1).setCash(c1 + amount);
System.out.println("Funds in account " + acc.get(j - 1).getAcc() + " " + acc.get(j - 1).getCash());
}
}
io.writeToFile(acc);
}
private void viewOne() {
System.out.println("Enter account number you want to look at");
try {
viewAnswer = Integer.parseInt(scan.nextLine());
if(viewAnswer > acc.size() || viewAnswer <= 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.println("Enter a account number!");
scan.reset();
return;
}
for (int i = 0; i < acc.size() + 1; i++) {
if (i == viewAnswer) {
System.out.println("Account name: " + acc.get(i - 1).getName());
System.out.println("Account nr: " + acc.get(i - 1).getAcc());
System.out.println("Funds: " + acc.get(i - 1).getCash());
}
}
}
private void delete() {
System.out.print("Enter account you want to delete: ");
try {
deleteAnswer = Integer.parseInt(scan.nextLine());
if(deleteAnswer > acc.size() || deleteAnswer < 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.println("Enter a account number!");
scan.reset();
return;
}
for (int i = 0; i < acc.size(); i++) {
if (acc.get(i).getAcc() == deleteAnswer) {
acc.remove(i);
io.writeToFile(acc);
}
}
}
private void showTransfers() {
transferHistory = io.readTransferedFromFile();
System.out.println(s);
System.out.println("***Transactions***");
System.out.println(s);
for (int i = 0; i < transferHistory.size(); i++) {
int t = transferHistory.get(i).tempFromAccount;
int t1 = transferHistory.get(i).temptransfered;
int t2 = transferHistory.get(i).tempToAccount;
System.out.println("Transfer from: " + t);
System.out.println("Transfered amount: " + t1);
System.out.println("Transfered to: " + t2);
System.out.println(s);
}
}
private void showOneTransfer() {
transferHistory = io.readTransferedFromFile();
System.out.println(s);
System.out.println("***Transactions***");
System.out.println(s);
System.out.print("Enter account nr: ");
int z = scan.nextInt();
System.out.println("Transactions made my account nr "+z+":");
for (int i = 0; i < transferHistory.size(); i++) {
if(transferHistory.get(i).tempFromAccount == z){
int t = transferHistory.get(i).tempFromAccount;
int t1 = transferHistory.get(i).temptransfered;
int t2 = transferHistory.get(i).tempToAccount;
System.out.println("Transfer from: " + t);
System.out.println("Transfered amount: " + t1);
System.out.println("Transfered to: " + t2);
System.out.println(s);
}
}
}
}
Here I populate the array from the file:
public ArrayList<Account> readFromFile() {
FileReader reader = null;
ArrayList<Account> result = new ArrayList<Account>();
try {
reader = new FileReader(new File(text));
BufferedReader br = new BufferedReader(reader);
String row = br.readLine();
while (row != null) {
String[] splits = row.split(":");
if (splits.length == 3) {
int saveNR = Integer.valueOf(splits[1]);
int saveAmount = Integer.valueOf(splits[2]);
String saveName = splits[0];
result.add(new Account(saveName,saveNR,saveAmount));
} else {
System.out.println("Error in file format");
}
row = br.readLine();
}
} catch (Exception e) {
System.out.println("Error while reading from file");
} finally {
try {
reader.close();
} catch (IOException ex) {
System.out.println("Ignore");
}
return result;
}
}
private void delete() {
System.out.print("Enter account you want to delete: ");
try {
deleteAnswer = Integer.parseInt(scan.nextLine());
if(deleteAnswer > acc.size() || deleteAnswer < 0){
System.out.println("Incorrect input!");
System.out.println(s);
scan.reset();
return;
}
} catch (Exception e) {
System.out.println("Enter a account number!");
scan.reset();
return;
}
for (int i = 0; i < acc.size(); i++) {
if (acc.get(i).getAcc() == deleteAnswer) {
acc.remove(i);
io.writeToFile(acc);
}
}
}
If you want a counter, have it be a static variable on the class and increment it when you need a new value. Something like:
private static int counter = 0;
private static int nextCounter() {
return ++counter;
}
Or, for synchronization reasons, use
private static AtomicInteger counter = new AtomicInteger();
private static int nextCounter() {
return counter.incrementAndGet();
}
However, I suggest you stop thinking that you need to fill in all the gaps in the account numbers. Typically in database work, account numbers are never reused. You aren't formally using a database, but you should work the same way. Reuse buys you nothing, and there is always a chance your code may confuse a new user 17 with the an old user 17. Just imagine what would happen were the US Social Security Administration were to reuse social security numbers.
Here's the reason for your error, by the way. In the code:
for (int i = 0; i < acc.size(); i++) {
if(acc.get(i).getAcc() == accountNr) {
accountNr++;
}
}
Suppose accountNr starts as 1, there are 3 accounts, and they have account numbers 2, 1, 3. After each runthrough of the loop, accountNr changes to:
1 ⇢ 1⇢ 2 ⇢ 2.
2 is an existing accont number, but your code sets account number to 2 after the last time it would be checked.
Getting the first unused integer
You want a way to get the first unused integer in acc. Here goes:
private int firstUnusedId(List<Account> accounts) {
List<Integer> ids = new ArrayList<>();
// Foreach loop.
for(Account account: accounts) {
ids.add(account.getAcc());
}
Collections.sort(ids);
for (int index = 0; index < ids.size(); ++index) {
if (ids.get(index) != index + 1) {
return index + 1;
}
}
return ids.size() + 1;
}
If the ids are 2, 1, 5 then they sort to 1, 2, 5. Then the loop compares:
index = 0, index + 1 = 1, compare to 1, equal.
index = 1, index + 1 = 2, compare to 2, equal.
index = 2, index + 1 = 3, compare to 5, not equal, return 3.
If the ids were 3, 2, 1, they would sort to 1, 2, 3, and the only difference would be the last comparison:
index = 2, index + 1 = 3, compare to 3, equal.
return size + 1 = 4.
You must share more of you code but from what i have seen and predict that you are creating the new account from the last accountNr +1 so if your last account in the list is 2 then 3 will be created ...4 etc..so review your new account and set your accountNr = acc.size+1