NoSuchElementException Java - java

This is a simple program that I wrote to do calculations on integers from a txt file. After a few hours of trying to debug, I was hoping a fresh set of eyes could spot a few of my problems. EDIT: data.txt contains integers 1-5. One integer per line.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class Calculator {
public static int[] NUMBERS; //global value for the array
public static void main(String[] args) throws FileNotFoundException {
File file = new File("data.txt");
Scanner sc = new Scanner(file);
List x = new ArrayList();
while (sc.hasNextInt()) {
x.add(sc.nextInt());
}
NUMBERS = new int[x.size()];
Iterator<Integer> iterator = x.iterator();
for (int i = 0; i < NUMBERS.length; i++) {
NUMBERS[i] = iterator.next().intValue();
}
sc.close();
Scanner sc2 = new Scanner(file);
System.out.println("Welcome to Calculation Program!\n");
startMenus(sc2);
}
private static void startMenus(Scanner sca) throws FileNotFoundException {
while (true) {
System.out.println("(Enter option # and press ENTER)\n");
System.out.println("1. Display the average of the list");
System.out.println("2. Display the number of occurences of a given element in the list");
System.out.println("3. Display the prime numbers in a list");
System.out.println("4. Display the information above in table form");
System.out.println("5. Save the information onto a file in table form");
System.out.println("6. Exit");
int option = sca.nextInt();
sca.nextLine();
switch (option) {
case 1:
infoMenu1(sca);
break;
case 2:
infoMenu2(sca);
break;
case 3:
infoMenu3(sca);
break;
case 4:
infoMenu4(sca);
break;
case 5:
infoMenu5(sca);
break;
case 6:
System.exit(0);
default:
System.out.println("Unrecognized Option!\n");
}
}
}
private static void infoMenu1(Scanner sc2) {
System.out.println("The average of the numbers in the file is: " + avg(NUMBERS));
}
public static double avg(int[] numbers) {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum = (sum + numbers[i]);
}
return (sum / numbers.length);
}
public static int occr(int[] numbers, int x) {
int count = 0;
for (int n : numbers) {
if (n == x) {
count = count + 1;
}
}
return count;
}
public static boolean prime(int x) {
boolean answer = true;
if (x == 0 || x == 1) {
return false;
}
for (int i = 2; i <= x / 2; i = i + 1) {
if (i != x) {
if (x % i == 0) {
answer = false;
}
}
}
return answer;
}
public static int[] primes(int[] numbers) {
int primesCount = 0;
for (int i : numbers) {
if (prime(i)) {
primesCount = (primesCount + 1);
}
}
if (primesCount == 0) {
return null;
}
int[] result = new int[primesCount];
int index = 0;
for (int i : numbers) {
if (prime(i)) {
result[index] = i;
index = index + 1;
}
}
return result;
}
private static void infoMenu2(Scanner sc) {
sc = new Scanner(System.in);
System.out.println("Which integer would you like to check for number of occurences?");
int choice = sc.nextInt();
System.out.println("The number of occurence(s) of " + choice + " are/is " + occr(NUMBERS, choice));
}
private static void infoMenu3(Scanner sc2) {
int[] myPrimes = primes(NUMBERS);
System.out.println("The prime number(s) in the file are/is: ");
for (int j = 0; j < myPrimes.length; ++j) {
System.out.println(myPrimes[j] + " ");
}
}
private static void infoMenu4(Scanner kb) throws FileNotFoundException {
File file = new File("data.txt");
Scanner sc = new Scanner(file);
int counter = 0;
while (sc.hasNextInt()) {
counter = counter++;
}
int lenth = counter;
int[] column1 = new int[lenth];
while (sc.hasNextInt()) {
column1 = new int[sc.nextInt()];
}
int[] column2 = new int[occr(NUMBERS, sc.nextInt())];
boolean column3 = prime(sc.nextInt());
System.out.printf("Average: " + "%20.2f", column1);
System.out.println();
System.out.printf("Occurences: " + "%14d", column2);
System.out.println();
System.out.printf("Primes:" + "%19s : %s", column3);
System.out.println();
}
private static void infoMenu5(Scanner kb) throws FileNotFoundException {
File file = new File("data.txt");
Scanner sc = new Scanner(file);
PrintWriter pw = new PrintWriter(new File("results.txt"));
int counter = 0;
while (sc.hasNextInt()) {
counter = counter++;
}
int lenth = counter;
int[] column1 = new int[lenth];
while (sc.hasNextInt()) {
column1 = new int[sc.nextInt()];
}
int[] column2 = new int[occr(NUMBERS, sc.nextInt())];
boolean column3 = prime(sc.nextInt());
pw.printf("Number: " + "%-10d", column1);
pw.println();
pw.printf("Occurences: " + "%12d", column2);
pw.println();
pw.printf("Primes:" + "%24s : %s", column3);
pw.println();
pw.close();
}
}

You are using wrong Scanner in your code (line 49). I suppose you are trying to get user input. However, you are using Scanner to get input from data.txt.
Updated according to the comments. Actually, you don't need Scanner from data.txt in startMenus. What you need is user input. So change sc2 to Scanner from System.in.
Original line 31:
// Scanner sc2 = new Scanner(file);
Scanner sc2 = new Scanner(System.in);

Related

Finding the mode of an array from user input java

So I'm making a program that gets an array from user-inputed values but I'm having trouble writing the code for finding the mode of the array. I tried writing my own code and then tried using a version of someone else's code but that didn't work out because I didn't fully understand it to be honest.
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int length;
Statistics stats = new Statistics();
System.out.println("Welcome to our statistics program!");
System.out.print("Enter the amount of numbers you want to store: ");
length=Integer.parseInt(keyboard.next());
int[] nums = new int[length];
for(int i=0; i<length; i++) {
System.out.println("Enter a number: ");
nums[i]=keyboard.nextInt();
}
System.out.println("Array elements are: ");
for (int i=0; i<length; i++) {
System.out.println(nums[i]);
}
public int Mode (int[] nums) {
double maxValue = -1.0d;
int maxCount = 0;
for(int i = 0; i < data.length; i++) {
double currentValue = data[i];
int currentCount = 1;
for(int j = i + 1; j < data.length; ++j) {
if(Math.abs(data[j] - currentValue) < epsilon) {
++currentCount;
}
}
}
if (currentCount > maxCount) {
maxCount = currentCount;
maxValue = currentValue;
} else if (currentCount == maxCount) {
maxValue = Double.NaN;
}
}
System.out.println("The minimum number is " + stats.Mode(nums));
You could consider using a HashMap to maintain the frequencies of the values in the array in your loop:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static int getIntegerInput(String prompt, Scanner scanner) {
System.out.print(prompt);
int validInteger = -1;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
validInteger = scanner.nextInt();
break;
} else {
System.out.println("Error: Invalid input, try again...");
System.out.print(prompt);
scanner.next();
}
}
return validInteger;
}
public static int getPositiveIntegerInput(String prompt, Scanner scanner) {
int num = getIntegerInput(prompt, scanner);
while (num <= 0) {
System.out.println("Error: Integer must be positive.");
num = getIntegerInput(prompt, scanner);
}
return num;
}
public static int getMode(int[] nums) {
if (nums.length == 0) {
throw new IllegalArgumentException("nums cannot be empty");
}
Map<Integer, Integer> valueFrequencies = new HashMap<>();
valueFrequencies.put(nums[0], 1);
int maxFreq = 1;
int candidateMode = nums[0];
for (int i = 1; i < nums.length; i++) {
int value = nums[i];
valueFrequencies.merge(value, 1, Integer::sum);
int candidateFreq = valueFrequencies.get(value);
if (candidateFreq > maxFreq) {
candidateMode = value;
maxFreq = candidateFreq;
}
}
return candidateMode;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numsLength = getPositiveIntegerInput("Enter how many numbers you want to store: ", scanner);
int[] nums = new int[numsLength];
for (int i = 0; i < numsLength; i++) {
nums[i] = getIntegerInput(String.format("Enter number %d: ", i + 1), scanner);
}
int mode = getMode(nums);
System.out.printf("Mode: %d%n", mode);
}
}
Example Usage:
Enter how many numbers you want to store: 0
Error: Integer must be positive.
Enter how many numbers you want to store: 6
Enter number 1: 3
Enter number 2: 2
Enter number 3: 5
Enter number 4: 5
Enter number 5: 3
Enter number 6: 3
Mode: 3

Java: How to use binary search with an array

For this java program, I'm trying to use a binary search for the array I have created in the Class Numbers, however, when I enter the 4th choice, the program just ends. The method binSearch is in Class Numbers. I can enter the required the size of the array, generate random numbers, search for specific numbers, and display them. However, when I want to use a binary search, the program ends as previously said. What is the reason why the program ends and what needs to be done to fix that certain method?
public class Numbers {
int[] array;
private int sizeOfArray;
public Numbers() {
sizeOfArray = 0;
array= new int [sizeOfArray];
}
public Numbers(int sizeOfArray) {
this.sizeOfArray = sizeOfArray;
array= new int [sizeOfArray];
}
public void generateNumbers() {
Random randomNumber = new Random();
int theNumber = 0;
for (int i = 0; i < sizeOfArray; i++) {
theNumber = randomNumber.nextInt(50);
array[i] = theNumber;
}
}
public int count(int num) {
int theNumbers = 0;
for (int i = 0; i < sizeOfArray; i++) {
if (array[i] == num) {
theNumbers++;
}
}
return theNumbers;
} // end count method
public String toString() {
String myArray = "";
for (int i = 0; i < sizeOfArray; i++) {
myArray += array[i] + " ";
}
return myArray;
}
public int binSearch(int[] array, int key) {
int low = 0;
int high = sizeOfArray - 1;
//int middle = (low + high + 1) /2;
int location = -1;
while (high >= low) {
int middle1 = (low + high) / 2;
if (array[middle1] == key ) {
//return true;
}
if (array[middle1] < key) {
low = middle1 + 1;
}
if (array[middle1] > key) {
high = middle1 - 1;
}
}
//return false;
return location;
}
}
and here is the main menu:
boolean isDone = false;
String input = null;
Numbers theNumber = new Numbers();
Scanner scanner = new Scanner (System.in);
try {
while (isDone == false) {
/*Menu options */
System.out.println("Enter 1 to create array size");
System.out.println("Enter 2 to generate random numbers");
System.out.println("Enter 3 to search and display number of occurrences");
System.out.println("Enter 4 to binary search to find whether specific number exists");
System.out.println("Enter 5 to display the array");
System.out.println("Enter 6 to quit the program");
input = scanner.nextLine();
switch (input) {
case "1":
int intNumber1 = 0;
System.out.println("Enter required size:");
intNumber1 = Integer.valueOf(scanner.nextLine());
theNumber = new Numbers(intNumber1);
System.out.println("Array has been generated.");
break;
case "2":
//theNumber = new Numbers();
theNumber.generateNumbers();
System.out.println("Numbers have been generated and stored.");
break;
case "3":
int intNumber2 = 0;
System.out.println("Enter number to search for: ");
intNumber2 = Integer.valueOf(scanner.nextLine());
System.out.println("Number of occurences of " + intNumber2 + " in the array is " + theNumber.count(intNumber2) + ".");
break;
case "4":
int key = 0;
theNumber.binSearch(null, key);
System.out.println("Array is sorted: ");
break;
case "5":
int theNumbers = 0;
if (theNumbers == 0)
{
System.out.println("No array has not been generated yet.");
}
else
{
System.out.println("The numbers are: ");
}
System.out.println(theNumber.toString());
break;
case "6":
isDone = true;
System.out.println("Bye... See you again");
scanner.close();
break;
default:
System.out.println("These are invalid choices...please reenter.");
break;
}
}
}
catch (Exception exception)
{
System.out.println("This is an invalid choice...please reenter.");
scanner.nextLine();
return;
}

How to scramble a word that is picked randomly from a text file

I am attempting to write a program that picks a random word from a text file, scrambles it, and allows the user to unscramble it by swapping 2 index locations at a time.
I have the program to the point where it grabs a random word from the text file and prints it out with the index numbers above it.
I am having trouble figuring out how to:
Get the word scrambled before it prints out on screen, and
How to get the user to be able to loop through swapping 2 indexes at a time until the word is unscrambled.
Is there a method I can write that will perform these actions?
Here is my code so far.
import java.io.*;
import java.util.*;
public class Midterm { // class header
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int scrambled;
int counter = 0;
int index1;
int index2;
String[] words = readArray("words.txt");
/*
* Picks a random word from the array built from words.txt file. Prints
* index with word beneath it.
*/
int randWord = (int) (Math.random() * 11);
for (int j = 0; j < words[randWord].length(); j = j + 1) {
System.out.print(j);
}
System.out.print("\n");
char[] charArray = words[randWord].toCharArray();
for (char c : charArray) {
System.out.print(c);
}
/*
* Prompt the user for input to play game or quit.
*/
System.out.println("\n");
System.out.println("Enter 1 to swap a par of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
if (input.hasNextInt()) {
option = input.nextInt();
counter++;
}
else {
option = 3;
}
System.out.println("");
if (option == 1) {
System.out.println("Enter the two index locations to swap separated by a space. ");
index1 = 0;
index2 = 0;
if (input.hasNextInt()) {
index1 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
if (input.hasNextInt()) {
index2 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
}
}
// end main
public static String[] readArray(String file) {
// Step 1:
// Count how many lines are in the file
// Step 2:
// Create the array and copy the elements into it
// Step 1:
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
}
return null;
}
}
I made some pretty major modifications to your code, including adding a scrambler method. The program is almost perfect, its just that your file "words.txt" can not hold words with repeat letters. For example, yellow, green, and purple won't unscramble correctly, but white, gray, blue, orange, or red will work fine. Other than that, the program works well. It chooses a random word, then when it is solved, chooses a different word, changing the last word to null, so it does not get picked again. Here's the program:
import java.io.*;
import java.util.*;
public class Experiments { // class header
private static String[] words = readArray("/Users/UserName/Desktop/words.txt"); //change to your location of the file
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int counter = 0;
String scrambledWord;
int index1;
int index2;
Random rand = new Random();
int randWord = rand.nextInt(words.length);
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.print("\n");
scrambledWord = scrambler(words[randWord]);
System.out.println(scrambledWord);
System.out.println("\n");
System.out.println("Enter 1 to swap a pair of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
option = input.nextInt();
if (option == 1) {
while (!scrambledWord.equals(words[randWord])) {
index1 = 0;
index2 = 0;
boolean validOption = false;
System.out.println("Enter the two index locations to swap separated by a space.");
while (!validOption) {
if (input.hasNextInt()) {
index1 = input.nextInt();
index2 = input.nextInt();
validOption = true;
}
else {
System.out.println("Please enter only numbers.");
validOption = false;
break;
}
}
String letter1 = scrambledWord.substring(index1, index1+1);
String letter2 = scrambledWord.substring(index2, index2+1);
System.out.println("replacing " + letter1 + " with " + letter2 + "...");
if (index1 < index2) {
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
} else {
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
}
System.out.println();
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.println("\n"+scrambledWord);
System.out.println();
counter++;
if (scrambledWord.equals(words[randWord])){
System.out.println("You did it! The word was " + words[randWord]);
System.out.println("You got it with " + counter + " replacements!");
words[randWord] = null;
if (words.length == 0){
System.out.println("I'm all out of words. You win!");
System.exit(0);
} else {
main(args);
}
}
}
} else if (option == 2) {
System.out.println(words[randWord]);
System.exit(0);
} else {
System.exit(0);
}
input.close();
}
//scrambles the word given to it
private static String scrambler(String word) {
String scrambled = "";
Random rand = new Random();
int length;
int index;
String letter;
String firststring;
String secondstring;
while (word.length()>0) {
length = word.length();
index = rand.nextInt(length);
letter = word.substring(index, index+1);
firststring = word.substring(0, index);
secondstring = word.substring(index+1);
word = firststring + secondstring;
scrambled += letter;
}
return scrambled;
}
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
And here's the list of words in the file words.txt(I pretty much wrote down whatever popped into my head that did not have repeat letters):
orange
red
brown
black
white
blue
tiger
horse
bugs
stack
overflow
pathfinder
extra
zealous
wisdom
under
above
death
life
second
first
frost
forest
These are obviously not the only words that can go in, you can add as many as you want, as long as they do not have 2 occurrences of the same letter.
You are reading the file incorrectly. Do
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNext()) {
ctr = ctr + 1;
s1.next();
}
//..rest of code

Sorting an Array of Names from A-Z (or Z-A)

This program is a small contact manager. I am having a problem calling the sortContacts method. It gives me a nullpointerexception every time I call the method. I am trying to have the method sort the contacts from A-Z but for some reason the arrays appear to be empty? The text file they are loaded from in loadContacts has entries in it, and prints perfectly fine (with the index number) when displayContacts is called.
I have tried using ArrayLists to no avail. It just seems like comparing strings inside arrays will just never work?
Exception in thread "main" java.lang.NullPointerException
at Contacts.sortContacts(Contacts.java:179)
at Contacts.menu(Contacts.java:47)
at Contacts.main(Contacts.java:25)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Contacts {
//global variables
public static int counter = 0;
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static int x;
static String[] name = new String[101];
static String[] number = new String[101];
public static void main(String[] args) throws IOException {//main method, sends user to the menu method
menu();
}
//The menu method displays the option menu and compares user input to a menu option
public static void menu() throws IOException{
int choice = -1;
while (choice != 7){
System.out.println("Main Menu");
System.out.println("1. View all Contacts\n2. Add Entry\n3. Modify Entry\n4. Delete Entry\n5. Save\n6. Load\n7. Sort Conacts\n8. Exit");
choice = Integer.valueOf(in.readLine()).intValue();
switch(choice){
case 1: displayContacts();
break;
case 2: addContact();
break;
case 3: modifyContact();
break;
case 4: deleteContact();
break;
case 5: saveContact();
break;
case 6: loadContact();
break;
case 7: sortContacts(name);
break;
default:System.exit(0);//terminates the program (quit)
}
}
}
private static void displayContacts() throws IOException {
System.out.println(counter);
for(int i = 0; i < counter; i++){
if(name != null) {//this loops prevents the program from printing out empty contact slots
System.out.println("Contact " + i + ": " + name[i] + " | " + number[i]);
}
else{
System.out.print("");
}
}
}
public static void addContact() throws IOException {
//check the counter variable
int print;
BufferedReader scan = new BufferedReader(new FileReader("contacts.txt"));
print = Integer.valueOf(scan.readLine()).intValue();
print = counter;
if (counter < 101){
//prompt the user for information
System.out.println("Enter the Contact's name:");
name[counter] = in.readLine();
System.out.println("Enter the Contact's number");
number[counter] = in.readLine();
//increment the counter
counter++;
} else {
System.out.println("Sorry the array is full!");
}
scan.close();
}
public static void modifyContact() throws IOException{
boolean found = false;
int flag = 0;
String modCon;
System.out.println("Enter the name of the contact you wish to modify:");
modCon = in.readLine();
for (int i = 0; i < counter; i++){
if (modCon.compareTo(name[i]) == 0){
flag = i;
found = true;
}
}
if (found == false){
System.out.println("Item not found");
}
else{
System.out.println("Contact found!");
System.out.println("Enter new name: ");
name[flag] = in.readLine();
System.out.println("Enter new number: ");
number[flag] = in.readLine();
}
}
private static void deleteContact() throws IOException {
boolean found = false;
int flag = -1;
String delCon;
System.out.println("Enter the name of the contact you wish to delete:");
delCon = in.readLine();
for(int i = 0; i < counter; i++){
if(delCon.compareTo(name[i]) == 0) {
flag = i;
found = true;
}
}
if(found == false){
System.out.println("Item not found");
}
else{
if (flag == counter - 1){
name[flag] = "";
number[flag] = "";
counter--;
} else{
for (int i = flag; i < counter; i++){
name[i] = name[i + 1];
number[i] = number[i + 1];
}
}
}
counter = flag + 1;
}
public static void saveContact() throws IOException{
//Create File output
PrintWriter output;
output = new PrintWriter(new FileWriter("contacts.txt"));
//Output a header to the file, in this case it is the number of criminals
output.println(counter);
//loop through our array outputting to a file
for(int i = 0; i < counter; i++){
System.out.println("Writing Contact to file");
output.println(name[i]);
output.println(number[i]);
}
output.close();
}
public static void loadContact() throws IOException {
int print;
BufferedReader in = new BufferedReader(new FileReader("contacts.txt"));
print = Integer.valueOf(in.readLine()).intValue();
counter = print; // tells the counter where to continue from (if loading a file)
System.out.println("Loading " + print + " Contacts");
for (int i = 0; i < print; i++){
//read in the data
name[i] = in.readLine();
number[i] = in.readLine();
}
in.close();
}
public static void sortContacts(String[] a) throws IOException{
//counters i and j
int i = 0;
int j = 0;
//"smallest" flag"
int smallest = 0;
//temporary holder for swapping
String temp;
//Selection Sort
for (i = 0; i < 100; i++){
smallest = i;
for (j = i; j < 10; j++){
//compare the current smallest with the current array element
if (name[j].compareTo(name[smallest]) < 0){
smallest = j;
}
//swap the smallest
temp = name[i];
name[i] = name[smallest];
name[smallest] = temp;
}
}
}
}
Read this to understand what your exception means: What is a NullPointerException, and how do I fix it?
In your case, if I pick case 7 in your menu, name is not initialized before you call sortContacts so every index is equal to null by default because it is a string array. So in sortContacts when you try something like name[j].compareTo(name[smallest] you get your null pointer exception because name[j] is equal to null.
To fix this you need to make sure that you populate your array with values from the file before you give the option to call sortContacts.

Java skipping a number in the sequence

This is very interesting, i notice. Before i can explain further its best i show the code and you will understand what i mean.
This is the code:
public class Qn3 {
static BigDecimal[] accbal = new BigDecimal[19];
private static Integer[] accnums = new Integer[19];
public static void main(String[] args) {
addaccount();
}
public static void addAccount() {
int i = 0, accno, input, j, check;
BigDecimal accbala;
DecimalFormat df = new DecimalFormat("0.00");
Scanner sc = new Scanner(System.in);
Scanner in = new Scanner(System.in);
accnums[1] = new Integer(1);
while (accnums.length >= count(accnums)) {
System.out.print("Enter the account number: ");
while (sc.hasNext("[0-9]{7}")) {
accno = sc.nextInt();
System.out.print("Enter account balance: ");
accbala = in.nextBigDecimal();
for (j = 0; j < accnums.length; j++) {
if (accnums[j] == null)
break;
else if (accnums[j].equals(accno)) {
break;
}
}
if (j == accnums.length) {
System.out.print("No more than 20 accounts can be added.");
} else if (accnums[j] != null) {
if ((accnums[j].equals(accno)))
System.out.println("Account already exists");
break;
} else {
accnums[j] = accno;
accbala = accbala.setScale(2, RoundingMode.HALF_UP);
accbal[j] = accbala;
check = j;
System.out.println("Current number of accounts in the system: "
+ (check + 1)
+ "\nNumber of accounts still can be added: "
+ (20 - (check + 1)));
}
}
while (!sc.hasNext("[0-9]{7}")) {
System.out.println("Wrong NRIC");
break;
}
while (accnums.length <= count(accnums)) {
System.out.println("20 accounts have already been created");
break;
}
break;
}
}
private static int count(Integer[] array) {
int count = 0;
// accnums = new Integer[] {1,2};
for (int index = 0; index < array.length; index++) {
if (array[index] != null) {
count++;
}
}
// System.out.println("You have used " + count + " slots");
return count;
}
}
So now that you have seen the code the problem that is hard to notice is this, take note of the line in the addaccount() method where
System.out.println("Current number of accounts in the system: "+(check+1)+"\nNumber of accounts still can be added: "+(20 - (check+1)));
this line the first check+1 will give me 1 then the next one gives me 3! and then the next time i run the method it gives me 4 and then again 5 and so on so forth, what is happening to 2?
You have that println in an else block, and when j == 1 you're hitting the else if case. Try removing this line
accnums[1] = new Integer (1);

Categories