I am trying to determine if the user entered value already exists in the current array, how to do that?
User entered value to check the variable is
accno and the array to compare to is accnums
This is what i am currently working on
public class Randomtopic {
static BigDecimal[] accbal = new BigDecimal[20];
static Integer[] accnums = new Integer[20];
public static void main(String[] args) {
displayMenu();
}
public static void displayMenu() {
int option, accno;
double accbal;
Scanner sc = new Scanner(System.in);
System.out.println(" Add an account");
System.out.println("Search an account with the given account number");
System.out.print("Enter Your Choice: ");
option = sc.nextInt();
switch (option) {
case 1:
System.out.println("You have choosen to add account");
addAccount();
break;
case 2:
System.out.println("You have choosen to search for an account");
System.out.print("Enter the Account Number: ");
accno = sc.nextInt();
System.out.println(search(accno, accnums));
break;
default:
System.out.println("Please choose an appropriate option as displayed");
}
displayMenu();
}
public static void addAccount() {
//String accno;
int i = 0;
int accno, input;
BigDecimal accbala;
DecimalFormat df = new DecimalFormat("0.00");
//BigDecimal[] accbal= new BigDecimal[20];
Scanner sc = new Scanner(System.in);
//String[] accnums = new String[20];
int j;
System.out.print("Enter the account number: ");
accno = sc.nextInt();
if (String.valueOf(accno).matches("[0-9]{7}")) {
System.out.print("Enter account balance: ");
accbala = sc.nextBigDecimal();
for (j = 0; j < accnums.length; j++) {
if (accnums[j] == null )
break;
else if(accnums[j].equals(accno))
{
System.out.println("Account already exists");
}
}
//System.out.print(j);
if (j == accnums.length) {
System.out.print("Account storage limit has reached.");
} else {
accnums[j] = accno;
accbala = accbala.setScale(2, RoundingMode.HALF_UP);
accbal[j] = accbala;
}
input = accnums[0];
System.out.println("The value: " + input + " witha a balance of " + accbal[0].toString());
} else {
System.out.println("Wrong NRIC");
}
displayMenu();
}
public static String search(int accnum, Integer[] numbers) {
// Integer[] numbers;
//int key;
//numbers = accnums;
// System.out.print("Enter the Account Number: ");
for (int index = 0; index < numbers.length; index++) {
if (numbers[index].equals(accnum)) {
return String.valueOf(index);
// System.out.println("The account number exists in this array index :"+index);//We found it!!!
}
break;
}
return "-1";
}
}
So my problem?
When i enter the accnum for the first time itself i am getting NullPointerException. Tks
When you instantiate or create an array, the values are by default set to null; whenever you iterate over an array of possibly null values, it is required you skip these. For example,
for(loop conditions)
if (numbers[index] != null && (numbers[index].equals(accnum))) {
return String.valueOf(index);
//your text goes here;
}
break;//I suggest you take this line out of your original code. Your for loop will end this once you have iterated through the entire array, or you will automatically break out if you find the value.
}
If you must use an array, then this is the best way to iterate through it. The parenthesis and the && in the if clause prevent you from performing the .equals check if the value of numbers[index] == null - in turn, preventing the null error from being thrown. your only alternative would be to set every value in the numbers[ ] to 0, or some other value, and than skip that value when you iterate. Such would be done with a static final int. However, this is not ideal coding.
Ideally, you should use an ArrayList - you can then not only make this more efficient, but also, much more readable.
Your accnums is filled with null values. Check if they are not null. I suppose your NullPointerException is thrown from search method.
If I understood your code correctly you have a number of accounts with associated balance identified by an account number. In this case I would use a Map instead of fiddling with arrays.
when you run your method search first time, yours array accnums is filled with null value so when you call line if ( numbers[index].equals(accnum)) you are trying call equal method on null object
what you can do is change your accnums from array to list, and then size will depends on number elements, so it wont have fixed size like your arrays
The problem in your code without adding anything in your accnum you are searching.So your accnum contains NULL values.if you change your accnum array into list/hashmap the exception would not arise.
Related
So I am completely new to java, and I want to create a code to accept string inputs from a user, and store it into an array. After this in the next statement, I will type a value into the terminal, and I want the code to compare my string input to one of the strings in the array and print available on the terminal when the string is available and vice versa. The first part of my code was right (hopefully) but I had a problem in comparing the strings. I feel it doesn't check the strings with my input in the code. Here is my code, Could anyone please help me with this? Thank you so much.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a[] = new String[20] //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() //entering a string to search
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) //I feel the problem is here
System.out.println(search + "course is available");
break;
else
System.out.println(search + "course is not available");
}
}
}
}
I expect the output to be
<string> course is available
when my string matches a string in the array and
<string> course is not available
when my entered string doesn't match a string in the array
But there is no output :(
I have modified your code and commented on line where it need to be explained. check it carefully.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
String a[] = new String[no_of_courses]; // do not assume when you have proper data.
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); // accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); // entering a string to search
boolean flag = false;
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) // I feel the problem is here
{
flag = true;//do not print here. just decide whether course is available or not
break;
}
}
//at the end of for loop check your flag and print accordingly.
if(flag) {
System.out.println(search + "course is available");
}else {
System.out.println(search + "course is not available");
}
}
}
}
class Course {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String a[] = new String[20] ; //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if(no_of_courses <= 0)
System.out.println("Invalid Range");
else
{
System.out.println("Enter course names:");
for(int i=0 ; i < no_of_courses ; i++)
{
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() ; //entering a string to search
boolean found = false;
for(int i = 0 ; i < no_of_courses ; i++)
{
if(a[i].equalsIgnoreCase(search)) //I feel the problem is here
{
**found = true;**
break;
}
}
if(found) {
System.out.println(search+ "course is available");
}else {
System.out.println(search+ "course is not available");
}
}
}
}
This is really a good effort and you almost got it. So just a couple of things
Since you are inputting the number of courses, just use that value to initialise your array (it's just a good practice to get into to try not initialise things before you actually need them).
If you are doing String comparisons and case sensitivity does not matter, rather use .equalsIgnoreCase(String)
To solve your problem, you just needed a boolean variable to indicate whether or not you had found a match. Initially this would be FALSE (no match found) and you would run through your array until a match is found. Once found this would be flagged TRUE and you'd breakout your loop (which you correctly did).
Only once out your loop, you'd print out whether you found a match.
Have a look:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0) {
System.out.println("Invalid Range");
} else {
String a[] = new String[no_of_courses];
System.out.println("Enter course names:");
for (int i = 0; i < a.length; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); //entering a string to search
boolean courseFound = Boolean.FALSE;
for(int i = 0; i < a.length; i++) {
if (a[i].equalsIgnoreCase(search)) {
courseFound = Boolean.TRUE;
break;
}
}
if(courseFound) {
System.out.println(search + "course is available");
} else {
System.out.println(search + " course is not available");
}
}
}
Oh, just for interest (and when you start working with some more advanced constructs), you could always just use stream, which was introduced in Java 8. It'll trim down 12 lines to 5...
if(Arrays.stream(a).anyMatch(i -> i.equalsIgnoreCase(search))) {
System.out.println(search + " course is available");
} else {
System.out.println(search + " course is not available");
}
I noticed a few things - Does your program run to the end? When i copy/pasted into my ide i noticed a few missing semi-colons, and like Yhlas said, your last if/else statement syntax is incorrect.
And this doesn't have anything to do with whether or not your program will give you the right answer, but your last loop will print over and over again because it will check each element in a, and each time it loops and finds a mismatch it will print something out
I need to write a code that "Display the complete set of unique values input after the user enters each new value." Such as:
The·complete·set·of·unique·values·entered·is:↵
Unique·Value·1:·is·100↵
Unique·Value·2:·is·10↵
Unique·Value·3:·is·20↵
I have attached my code below, and have the code completed, however, it seems to come across errors on my very last line to produce the last "this is the first time (user input) has been entered" & the unique value portion results of Unique Value # is (user input that's unique and stored in array). There seems to be an error in the very last System.out.println("Unique...) line.
Any help would be greatly appreciated.
import java.util.Scanner;
import java.util.ArrayList;
public class DisplayUniqueValueInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// creating an ArrayList from user input
ArrayList<Integer> userInputs = new ArrayList<Integer>(5);
// prompt user and store input
int count = 0;
while (true) {
int a = 0;
while(true) {
System.out.print("Enter an integer between 10 and 100:");
a = Integer.parseInt(sc.nextLine());
if (a < 10 || a > 100)
System.out.println("Invalid input\n");
else
break;
}
count++;
if (count == 5)
break;
boolean ifExists = false;
for(int i = 0; i<userInputs.size(); i++) {
if (userInputs.get(i) == a) {
ifExists = true;
break;
}
}
if (!ifExists){
System.out.printf("This is the first time %d has been entered\n", a);
userInputs.add(a);
}
} // end while statement
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < 5; i++) {
System.out.println("Unique Value" + userInputs[i] + "is:" + " ");
}
} // end main method
} // end of class
A little off-topic but if you must store unique elements, you normally go for a Set. That being said, in the portion of the code where you collect the user input, you are asking for 5 numbers but storing 4 e.g.:
int count = 0;
while (true) {
int a = 0;
while(true) {
System.out.print("Enter an integer between 10 and 100:");
a = Integer.parseInt(sc.nextLine());
if (a < 10 || a > 100)
System.out.println("Invalid input\n");
else
break;
}
// count++;
// if (count == 5) if you break here, the code below won't be reached
// break; thus you will never store the last user input
// Lists have a method contains that does exactly what you are trying to do
// Consider using ifExists = userInput.contains(a)
boolean ifExists = false;
for(int i = 0; i<userInputs.size(); i++) {
if (userInputs.get(i) == a) {
ifExists = true;
break;
}
}
if (!ifExists){
System.out.printf("This is the first time %d has been entered\n", a);
userInputs.add(a);
}
// consider breaking here after you have collected the last user input
// alternatively, use a do{ ... } while(); loop
count++;
if (count == 5)
break;
} // end while statement
You are not printing the iteration variable i e.g.:
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < userInputs.size(); i++) {
System.out.println("Unique Value " + (i + 1) + ": is " + userInputs.get(i));
}
Also as mentioned in another answer, in your for-loop the variable i must go up to < userInputs.size() since if you try to go up to 5, it will break if the user entered duplicate values.
For the last loop, you should do this instead, because your array is to store unique numbers, right? So if there is less than 5 unique number, your program will break, and why don't use Set instead?
// output unique values
System.out.println("\nThe complete set of unique values entered is:\n");
for(int i = 0; i < userInputs.size(); i++) {
System.out.println("Unique Value" + userInputs.get(i) + "is:" + " ");
}
Your error is because in the last for loop you try to access your list with userInputs[i] instead of userInputs.get(i)
If you want to accept and print only unique value, Perhaps use Set instead of ArrayList. Example:-
public static void main(String args[]){
Set<Integer> numbers = new HashSet<>();
for(String input : args){
Integer num = Integer.parseInt(input);
if(!(numbers.add(num))){
throw new IllegalArgumentException("Number already have");
}
System.out.println("Unique number =" + num);
}
}
A Set is a collection that contains no duplicate elements. Refer to its javadoc for details.
** Sample above just for brevity, you may retrofit your program with Set type.
public static void choice( String arrayString[], double arrayReal[])
{
int choice;
Scanner sc = new Scanner(System.in);
System.out.println("1.display mark");
System.out.println("2.exit");
choice = sc.nextInt();
while (choice !=2 && choice != 1)
{
System.out.println("invalid input enter again");
choice = sc.nextInt();
}
switch (choice)
{
case 1:
output(arrayString, arrayReal);
break;
case 2:
System.out.println("exiting");
break;
default:
System.out.println("invalid choice choose between 1 and 2");
choice = sc.nextInt();
}
}
public static void output(String arrayString[], double arrayReal[])
{
String name;
Scanner sc = new Scanner(System.in);
for (int i=0;i<arrayString.length;i++)
{
System.out.println(arrayString[i]);
}
System.out.println("enter stident name");
name = sc.nextLine();
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString.equals(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
}
for (int j=0;j<arrayString.length;j++)
{
if (arrayString[j].equals(name))
{
System.out.println("mark of " + arrayString[j] + "is " + arrayReal[j]);
}
}
im trying to validate the student name and if it doesnt equal to any of the names in the array return back to the menu. it does go back to the menu but the problem is after going back to the menu even if i type the correct student name if keps going back to the menu. i thought for loops were supposed to loop set amount of times and pass to the next code?? is that right? also is my approach correct? ive tried putting if else in the last for loop but that didnt end up as i wanted it to as well. any help is appreciated thanks!
EDIT-
thanks for spotting the mistake. fixed !arrayString.equals(name) to !arrayString[k].equals(name) but still the same problem
Your problem ist here:
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString.equals(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
}
You are comparing an Array String[] arrayString with a String name. They are never going to be treated as equal and therefor your choice method is allways called.
Also the whole loop is totally pointless as you never use your loop index k for anything.
You don't need a loop here at all. Instead you can simply convert the String array to a temporary list and check if it contains your input:
if(!Arrays.asList(arrayString).contains(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
Edit:
here a short main Method that can be used for testing:
public static void main(final String[] args) {
final String[] test = { "Mark", "Peter" };
final double[] test2 = { 1, 2 };
choice(test, test2);
}
Input/Output:
OUTPUT: 1.display mark
OUTPUT:2.exit
INPUT: 1
OUTPUT: Mark
OUTPUT: Peter
OUTPUT: enter stident name
INPUT: Mark
OUTPUT: mark of Markis 1.0
The logic at this part, after adding the index, is still wrong:
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString[k].equals(name))
{
System.out.println("invalid name");
...
}
}
this will print "invalid name" for every name in the list that is not the given name. Example: if the first name in the array does not match, you will get a message (and choice called), no matter if the second entry matches.
One way is to search the whole array until you find the name and then act on the result:
boolean found = false;
for (int k=0;k<arrayString.length;k++)
{
if(arrayString[k].equals(name))
{
found = true;
break; // stop searching
}
}
if (!found)
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
just another newbie here needing help with a coding dilemma. The program I'm trying to create is a small database that has to use three parallel arrays (userNumber, player, and highScore). The intention is that the user should enter the a user number at the prompt and the program will display the person's information. If the number entered doesn't exist then the program should show them the number they entered and make them re-enter a user number until a correct one is entered.
The problems I'm running into now is that the program doesn't accept any user number except the first user number in the array, whether or not it's a valid number in the array list. Also, the error message only displays the first "incorrect" number regardless of how many times a "wrong" number is entered.
In short, I guess the right questions would be:
1.) Exactly what should I change in order for the program to return the info for just the array entries that correspond to the entered userNumber?
2.) What do I change to make each error message display the "incorrect" number that was just entered?
Here's the code I have:
import java.util.Scanner;
public class HighScoreSearch
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] userNumber = new int[5];
String[] player = new String[5];
Double[] highScore = new Double[5];
userNumber[0]= 1;
userNumber[1]= 2;
userNumber[2]= 3;
userNumber[3]= 4;
userNumber[4]= 5;
player[0]= "Morpheus";
player[1]= "Neo";
player[2]= "Cereal Killer";
player[3]= "Crash Override";
player[4]= "Acid Burn";
highScore[0]= 853797.67;
highScore[1]= 999999.99;
highScore[2]= 15097.34;
highScore[3]= 864513.16;
highScore[4]= 543188.68;
System.out.print("Enter User# ");
int scan= input.nextInt();
int i=0;
while (scan!=userNumber[i])
{
System.out.printf("Error #%s Is Unknown User", scan);
System.out.print("Enter User# ");
scan=input.nextInt();
}
System.out.printf("%s, user# %s, has a high score of: %s", player[i], userNumber[i], highScore[i]);
}
}
You are not using the entered value - consider
while (scan < userNumber[0] || scan > userNumber[4])
{
System.out.printf("Error #%s Is Unknown User", scan);
System.out.print("Enter User# ");
scan=input.nextInt();
}
// now use the value
System.out.printf("%s, user# %s, has a high score of: %s",
player[scan-1], userNumber[scan-1], highScore[scan-1]);
Of course, you should really loop through the userNumber array to check if the number is there. In reality such a solution would require you to create single obejcts holding this information and then having a List or array of these objects
You should consider using a HashMap for your users instead of an array. Otherwise, you would have to loop through the entire array each time to find if the user exists.
Map<Integer, Integer> userMap = new HashMap<>();
// map user numbers to associative array indexes.
userMap.put(1, 0);
userMap.put(2, 1);
userMap.put(3, 2);
userMap.put(4, 3);
userMap.put(5, 4);
player[0]= "Morpheus";
player[1]= "Neo";
player[2]= "Cereal Killer";
player[3]= "Crash Override";
player[4]= "Acid Burn";
highScore[0]= 853797.67;
highScore[1]= 999999.99;
highScore[2]= 15097.34;
highScore[3]= 864513.16;
highScore[4]= 543188.68;
System.out.print("Enter User# ");
int scan= input.nextInt();
// loop until the user actually exists
while (!userMap.containsKey(scan))
{
System.out.printf("Error #%s Is Unknown User", scan);
System.out.println();
System.out.println("Enter User# ");
scan=input.nextInt();
}
// get the index for the user
int lookup = userMap.get(scan);
System.out.printf("%s, user# %s, has a high score of: %s", player[lookup], scan, highScore[lookup]);
Note
The other benefit with using this approach is that your user numbers don't have to be in order.
For example, you can have the following mapping and the code would still work:
userMap.put(1, 0);
userMap.put(2, 1);
userMap.put(9, 2); // user # 9 can map to index 2.
userMap.put(4, 3);
userMap.put(5, 4);
Per #ScaryWombat it would be ideal to create a Player class so you don't have to use associative arrays and make your program more OO.
Example:
class Player
{
private int id = 0;
private String name;
private Double score = 0.0;
public Player (int id, String name, double score)
{
this.id = id;
this.name = name;
this.score = score;
}
#Override
public String toString()
{
return String.format("%s, user# %s, has a high score of: %s", name, id, score);
}
}
Then, you can create a HashMap of Integer to Player
Map<Integer, Player> userMap = new HashMap<>();
userMap.put(1, new Player(1, "Morpheus", 853797.67));
userMap.put(2, new Player(2, "Neo", 999999.99));
userMap.put(3, new Player(3, "Cereal Killer", 15097.34));
userMap.put(4, new Player(4, "Crash Override", 864513.16));
userMap.put(5, new Player(5, "Acid Burn", 543188.68));
Now, you can look up the Player like this:
// get the player object for the user id
Player p = userMap.get(scan);
// print out the player like this since it has a toString()
System.out.println(p);
I'm proving another answer that uses arrays, since your requirement is to use parallel arrays. Please see all the comments in the code. I've added error checking so the program doesn't exit nor get into an invalid state.
The key here is that you have to loop through the entire array each time the user enters a potential user number.
import javax.swing.JOptionPane;
public class HighScoreSearch
{
// You need an indicator for an invalid user in the case where
// you don't use all array positions
private static final int INVALID_USER_NUM = -1;
public static void main(String[] args)
{
// consider renaming this int to something like userNumber (scan is not very meaningful)
int scan = 0;
int[] userNumber = new int[10];
String[] player = new String[10];
Double[] highScore = new Double[10];
userNumber[0]= 10;
userNumber[1]= 777;
userNumber[2]= 5;
userNumber[3]= 1234;
userNumber[4]= 357;
// set the rest to an invalid user #; otherwise these will have a value 0 by default
userNumber[5]= INVALID_USER_NUM;
userNumber[6]= INVALID_USER_NUM;
userNumber[7]= INVALID_USER_NUM;
userNumber[8]= INVALID_USER_NUM;
userNumber[9]= INVALID_USER_NUM;
player[0]= "Morpheus";
player[1]= "Neo";
player[2]= "Cereal Killer";
player[3]= "Crash Override";
player[4]= "Acid Burn";
highScore[0]= 853797.67;
highScore[1]= 999999.99;
highScore[2]= 15097.34;
highScore[3]= 864513.16;
highScore[4]= 543188.68;
// this represents the array index of the user across the arrays
int indexOfUser = 0;
// flag to indicate if we found a valid user
boolean userFound = false;
do
{
String replyBox = JOptionPane.showInputDialog("Enter User#");
// consider trimming this replyBox value
// If they enter "10 " (w/o quotes would you still want that to be valid)
replyBox = replyBox.trim();
scan = INVALID_USER_NUM; // default to an invalid user #
try
{
scan = Integer.parseInt(replyBox);
}
catch (java.lang.NumberFormatException nfe)
{
// they didn't enter a valid integer, but you don't want to exit the program
}
// don't bother searching if it's invalid
if (scan != INVALID_USER_NUM)
{
// loop through each user to see if you find the entered #
for (int i = 0; i < userNumber.length && !userFound; i++)
{
// we found this user
if (scan == userNumber[i])
{
indexOfUser = i;
userFound = true;
}
}
}
if (!userFound)
{
// you should use replyBox instead of scan here
//String messagefalse = String.format("Error %s is an Unknown User", scan);
String messagefalse = String.format("Error: '%s' is an Unknown User", replyBox);
JOptionPane.showMessageDialog(null, messagefalse);
}
} while (!userFound); // loop until we find a user
// we've found a user - use the indexOfUser to index the arrays
String messagetrue = String.format("%s, user# %s, has a high score of: %s", player[indexOfUser], userNumber[indexOfUser], highScore[indexOfUser]);
JOptionPane.showMessageDialog(null, messagetrue);
}
}
I want the user to enter integers into an array. I have this loop I wrote which has a try and catch in it, in case a user inserts a non integer. There's a boolean variable which keeps the loop going if is true. This way the user will be prompted and prompted again.
Except, when I run it, it gets stuck in a loop where it repeats "Please enter # " and "An Integer is required" without letting the user input a new number. I reset that number if an exception is caught. I don't understand.
import java.util.*;
public class herp
{
//The main accesses the methods and uses them.
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array"+" and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize+1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length)
{
// Not into will turn true and keep the loop going if the user puts in a
// non integer. But why is it not asking the user to put it a new checkint?
while(notint)
{
try
{
notint = false;
System.out.println("Please enter #"+ prompt);
checkint = scan.nextInt();
}
catch(Exception ex)
{
System.out.println("An integer is required." +
"\n Input an integer please");
notint = true;
checkint = 1;
//See, here it returns true and checkint is reset.
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
}
}
Once the scanner has thrown an InputMismatchException it cannot continue to be used. If your input is not reliable, instead of using scanner.nextInt() use scanner.next() to obtain a String then convert the string to an int.
Replace:
checkint = scan.nextInt();
With:
String s = scan.next();
checkint = Integer.parseInt(s);
I have corrected it like below. I don't rely on exception, but check if the next Scanner input is int (using hasNextInt()). If not int, just consume Scanner token and wait for the next user input.
Looks like it is working, apart from 0 being inserted as a first array element, because you started indexing prompt from 1.
public class Herp {
//The main accesses the methods and uses them.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array" + " and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize + 1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length) {
while (notint) {
notint = false;
System.out.println("Please enter #" + prompt);
// check if int waits for us in Scanner
if (scan.hasNextInt()) {
checkint = scan.nextInt();
} else {
// if not, consume Scanner token
scan.next();
System.out.println("An integer is required."
+ "\n Input an integer please");
notint = true;
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
for (int i : mainarray) {
System.out.print(i + " ");
}
}
}