Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm writing a Java program that creates a menu and lets the user pick an option. The while loop in my getValidChoice method is not functioning as it should. It is an infinite loop, please help! New to Java! Ask questions for clarity!
import java.io.*;
import java.util.*;
import java.lang.*;
public class Main
{
public static String createMenu(String[] listOfChoices, String menuTitle) {
String bigStr = menuTitle + "\n\n";
int count = 1;
for (int i = 0; i < listOfChoices.length; i++) {
String littleStr = count + ". " + listOfChoices[i] + "\n";
count = count + 1;
bigStr = bigStr + littleStr;
}
return bigStr;
}
public static int getValidChoice(int numChoices, String menu) {
System.out.println(menu);
boolean error = true;
Scanner choice = new Scanner(System.in);
System.out.print("Enter your choice: ");
String number = choice.next();
char[] inputArray = new char[number.length()];
for (int i = 0; i < number.length(); i++) {
inputArray[i] = number.charAt(i);
if (Character.isDigit(inputArray[i])) {
error = false;
}
}
while (error == true || (Float.valueOf(number) > numChoices && Float.valueOf(number) < 1)) {
System.out.println("Invalid choice -- please try again\n");
System.out.println(menu);
choice = new Scanner(System.in);
System.out.print("Enter your choice: ");
number = choice.next();
inputArray = new char[number.length()];
for (int i = 0; i < number.length(); i++) {
inputArray[i] = number.charAt(i);
if (Character.isDigit(inputArray[i])) {
error = false;
}
}
}
return Integer.valueOf(number);
}
public static void main(String[] args) {
String[] employeeList = new String[50];
String[] chList = {"Add New Employee", "Delete Employee", "Change Employee Name", "Print Employee Roster", "Quit"};
String menuStr = createMenu(chList, "Main Menu");
int ch = getValidChoice(chList.length, menuStr);
System.out.println(ch);
}
}
Replace
for (int i = 0; i > number.length(); i++)
with
for (int i = 0; i < number.length(); i++)
Since your for loop counter (i.e. i) is increasing by 1 with each iteration, it will eventually become equal to number.length() and the loop will terminate if we put the condition as i < number.length(). In your code, the check fails for the first time itself.
Note that you need to make this change at two places, outside the while loop and also inside the while loop. Given below is the corrected code:
import java.util.Scanner;
public class Main {
public static String createMenu(String[] listOfChoices, String menuTitle) {
String bigStr = menuTitle + "\n\n";
int count = 1;
for (int i = 0; i < listOfChoices.length; i++) {
String littleStr = count + ". " + listOfChoices[i] + "\n";
count = count + 1;
bigStr = bigStr + littleStr;
}
return bigStr;
}
public static int getValidChoice(int numChoices, String menu) {
System.out.println(menu);
boolean error = true;
Scanner choice = new Scanner(System.in);
System.out.print("Enter your choice: ");
String number = choice.next();
char[] inputArray = new char[number.length()];
for (int i = 0; i < number.length(); i++) {
inputArray[i] = number.charAt(i);
if (Character.isDigit(inputArray[i])) {
error = false;
}
}
while (error == true || Float.valueOf(number) > numChoices || Float.valueOf(number) < 1) {
System.out.println("Invalid choice -- please try again\n");
System.out.println(menu);
choice = new Scanner(System.in);
System.out.print("Enter your choice: ");
number = choice.next();
inputArray = new char[number.length()];
for (int i = 0; i < number.length(); i++) {
inputArray[i] = number.charAt(i);
if (Character.isDigit(inputArray[i])) {
error = false;
}
}
}
return Integer.valueOf(number);
}
public static void main(String[] args) {
String[] chList = { "Add New Employee", "Delete Employee", "Change Employee Name", "Print Employee Roster",
"Quit" };
String menuStr = createMenu(chList, "Main Menu");
int ch = getValidChoice(chList.length, menuStr);
System.out.println(ch);
}
}
A sample run:
Main Menu
1. Add New Employee
2. Delete Employee
3. Change Employee Name
4. Print Employee Roster
5. Quit
Enter your choice: a
Invalid choice -- please try again
Main Menu
1. Add New Employee
2. Delete Employee
3. Change Employee Name
4. Print Employee Roster
5. Quit
Enter your choice: 6
Invalid choice -- please try again
Main Menu
1. Add New Employee
2. Delete Employee
3. Change Employee Name
4. Print Employee Roster
5. Quit
Enter your choice: -1
Invalid choice -- please try again
Main Menu
1. Add New Employee
2. Delete Employee
3. Change Employee Name
4. Print Employee Roster
5. Quit
Enter your choice: 3
3
This change in getValidChoice() will fix the problem. Start with boolean error = false; instead of boolean error = true;.
Starting of the changed method:
public static int getValidChoice(int numChoices, String menu) {
System.out.println(menu);
boolean error = false; //THIS IS THE CHANGE
Scanner choice = new Scanner(System.in);
Edit: Added the changed method
The places where changes have been made are commented with "CHANGE".
public static int getValidChoice(int numChoices, String menu) {
System.out.println(menu);
boolean error = false;
Scanner choice = new Scanner(System.in);
System.out.print("Enter your choice: ");
String number = choice.next();
char[] inputArray = new char[number.length()];
for (int i = 0; i < number.length(); i++) { //CHANGE: '<' and not '>'
inputArray[i] = number.charAt(i);
if ( !Character.isDigit(inputArray[i])){ //CHANGE: Notice '!'
error = true; //CHANGE: Error: The character is not a digit.
}
}
while (error == true || Float.valueOf(number) > numChoices || Float.valueOf(number) < 1) {
error = false; //CHANGE: Reset error back to false.
System.out.println("Invalid choice -- please try again\n");
System.out.println(menu);
choice = new Scanner(System.in);
System.out.print("Enter your choice: ");
number = choice.next();
inputArray = new char[number.length()];
for (int i = 0; i > number.length(); i++) {
inputArray[i] = number.charAt(i);
if (Character.isDigit(inputArray[i])) {
error = false;
}
}
}
return Integer.valueOf(number);
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 12 months ago.
I am working on a Java program that determines Evens, Odds, and Negative numbers from 12 inputted integers.
It then separates them into different arrays. The course I am following suggests building an exception handler and I utilized the Try-Catch Method for the Exception error I may receive.
It then creates an Out of Bounds error for counting these numbers when I enter a String.
I've commented on the area in which I have trouble reprompting the user. So far, I've tried prompting at the error with twelveInt [i] = in.nextInt(); and just in.next();.
Why is the program affected outside of the loop?
Here is the program:
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int [] twelveInt = new int [12];
int countEven = 0;
int countOdd = 0;
int countNeg = 0;
boolean ehandle = true;
for (int i = 0; i < twelveInt.length; i++) {
while(ehandle){
try{
System.out.println("Enter the #" + (i + 1) + " integer.");
twelveInt [i] = in.nextInt();
ehandle = false;
}
catch(Exception e){
System.out.println("Please enter integers only");
// Unsure of what to add here to handle the errors and allow me to reprompt. in.next();
//does not work nor does twelveInt [i] = in.nextInt();
}
if (twelveInt[i] % 2 == 0){
countEven++;
}
if (twelveInt[i] % 2 != 0){
countOdd++;
}
if (twelveInt[i] < 0){
countNeg++;
}
}
}
int [] evens = new int [countEven];
int [] odds = new int [countOdd];
int [] negatives = new int [countNeg];
countEven = 0;
countOdd = 0;
countNeg = 0;
for (int i : twelveInt) {
if (i % 2 == 0){
evens[countEven++] = i;
}
if (i % 2 != 0){
odds[countOdd++] = i;
}
if (i < 0){
negatives[countNeg++] = i;
}
}
System.out.println("Here are the Even numbers you entered");
System.out.println(Arrays.toString(evens));
System.out.println("Here are the Odd numbers you entered");
System.out.println(Arrays.toString(odds));
System.out.println("Here are the Negative numbers you entered");
System.out.println(Arrays.toString(negatives));
The problem in your code is that after you run your loop and enter your first number, you then define ehandle = false.
This means that you never enter the rest of your loop since you exit the while loop. Therefore, you never increment the values of countEven, countOdd, or countNeg.
This results in an error because when you try running this line: int [] evens = new int [countEven]; , countEven is still 0, so you get an error when you try to iterate it.
To avoid this error, you can modify your try catch error as so:
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int [] twelveInt = new int [12];
int countEven = 0;
int countOdd = 0;
int countNeg = 0;
for (int i = 0; i < twelveInt.length; i++) {
System.out.println("Enter the #" + (i + 1) + " integer.");
boolean error = true;
while (error) {
try {
twelveInt [i] = in.nextInt();
if (twelveInt[i] % 2 == 0){
countEven++;
}
if (twelveInt[i] % 2 != 0){
countOdd++;
}
if (twelveInt[i] < 0){
countNeg++;
}
error = false;
}
catch (Exception e) {
System.out.println("Please enter integers only");
in.next();
}
}
}
int [] evens = new int [countEven];
int [] odds = new int [countOdd];
int [] negatives = new int [countNeg];
countEven = 0;
countOdd = 0;
countNeg = 0;
for (int i : twelveInt) {
if (i % 2 == 0){
evens[countEven++] = i;
}
if (i % 2 != 0){
odds[countOdd++] = i;
}
if (i < 0){
negatives[countNeg++] = i;
}
}
System.out.println("Here are the Even numbers you entered");
System.out.println(Arrays.toString(evens));
System.out.println("Here are the Odd numbers you entered");
System.out.println(Arrays.toString(odds));
System.out.println("Here are the Negative numbers you entered");
System.out.println(Arrays.toString(negatives));
}
}
We first try taking in the user input, and if we get an exception error, we will use the catch so our code does not terminate. NOTE: we must do in.next() otherwise we will get an infinite loop (since integers leave a trailing newline, resulting in infinite exceptions).
I hope this helped! Please let me know if you need any further clarifications or details :)
If you want to reiterate your while(ehandle) loop when you get an exception, you can put continue in your catch block. But you should set ehandle back to true at the top of your for-loop.
for (int i = 0; i < twelveInt.length; i++) {
ehandle = true;
while (ehandle) {
try {
System.out.println("Enter the #" + (i + 1) + " integer.");
twelveInt[i] = in.nextInt();
ehandle = false;
} catch(Exception e) {
System.out.println("Please enter integers only");
continue;
}
...
I'm handling exceptions for an exercise and runs fine until I enter an invalid number (to try) after running the program for the first time, this is after the first run when asking to re-run with different values if I happen to enter invalid values it won't throw the exception and I don't know why? It's something I don't know or is it my code? Thanks
//program ReverseNumbers.java
//This program reverses the digits of each number in an array.
import java.util.Scanner;
public class ReverseNumbers{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
boolean continueInput = true; //controls loop for input
String another = "y";
while(another.equalsIgnoreCase("Y")){ //loop to re-run program
do{
System.out.print("\nEnter 5 positive integers: "); //prompt the user to enter 5 integers
//try block
try{
for(int i = 0; i < numbers.length ; i++) //initialize the array
numbers[i] = input.nextInt();
checkInput(numbers); //handler method
continueInput = false;
}
//catch block
catch(IllegalArgumentException ex){
System.out.print("\nInvalid input: ");
//input.nextLine();
}
}while(continueInput);
//outputs
System.out.print("\nEntered numbers:\t\t");
for(int e: numbers)
System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
reverse(numbers);
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
//Exception method
public static void checkInput(int[] array) throws IllegalArgumentException {
for(int i = 0; i < array.length; i++){
if(array[i]<0)
throw new IllegalArgumentException();
}
}
//method reverse.
public static void reverse(int[] array) {
//reverse order of element within the array
int i, k, t;
int n = array.length;
for (i = 0; i < n / 2; i++) {
t = array[i];
array[i] = array[n - i - 1];
array[n - i - 1] = t;
}
reverse(array, array.length-1);
}
//helper method
public static void reverse(int[] array, int n){ //reverse the order of the number for each element in the array
// n, number of elements in the array
if(n>=0){
int Element = array[n]; //element n in array
int NewElement = -1;
int Digit = -1;
String s = "";
if(Element<10)
s = Element + "";
while(Element >= 10){ //loop up to element is reduced to one digit number
Digit = Element%10;
s = s + "" + Digit; //save the digits
NewElement = Element/10;
if(NewElement < 10) //when NewElement has 1 digit left
s = s + "" + NewElement;
Element = NewElement;
}
System.out.print(s + " "); //print digit
reverse(array, n-1); //recursive call
}
}
}
This can be fixed simply by inserting continueInput = true in your outer while loop. Without that, continueInput will always be false after the first time you enter a valid input, and your do-while loop will always exit after one iteration.
However, I wouldn't suggest throwing exceptions yourself, and you should probably handle Scanner's InputMismatchException. Also, your reverse method is unnecessarily complicated. Here's the code I got:
import java.util.Scanner;
public class ReverseNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5]; //create array numbers size 5
String another = "y";
while (another.equalsIgnoreCase("Y")) { //loop to re-run program
boolean continueInput = true; //controls loop for input
outer: do {
System.out.print("\nEnter " + numbers.length + " positive integers: ");
try {
for (int i = 0; i < numbers.length; i++) {
int num = input.nextInt();
if (num < 0) {
System.out.print("Invalid input, found a negative integer " + num)
continue outer;
} else {
numbers[i] = num;
}
}
continueInput = false;
}
//handle bad inputs that aren't digits
catch (InputMismatchException ex) {
System.out.print("\nInvalid input, please enter integers");
}
} while (continueInput); //outputs
System.out.print("\nEntered numbers:\t\t");
for (int e: numbers) System.out.print(e + " ");
System.out.print("\nReversed numbers:\t\t");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + (i == 0 ? "\n" : " "));
}
//output re-run program
System.out.println();
System.out.print("\nRe-run program with different values, Y/N? ");
another = input.next();
}
}
}
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
I am trying to make some code that should keep track of a win/loss ratio. I have a for loop that checks if a name is present in a separate variable, this works but when I try to do it again it stalls.
System.out.println("\nEnter Name 1");
scan.nextLine();
String name1 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name1.equals(players[i].name)) {
players[i].win++;
break;
}
}
System.out.println("\nEnter Name 2");
scan.nextLine();
String name2 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name2.equals(players[i].name)) {
players[i].loss++;
break;
}
}
After the code it should go back to a while loop, but it just stalls instead. If I comment out the name 2 part, the code works, but I need both parts.
Edit 1:
Heres the whole code
public class Counter {
#SuppressWarnings("resource")
public static void main(String[] args) {
int intTemp;
String stringTemp;
int keepGoing = 1;
int numPlayers = 0;
Player[] players = new Player[999];
Scanner scan = new Scanner(System.in);
System.out.println("Melee Score Tracker");
while (keepGoing == 1) {
System.out.println("\nPrint Scores\t1\nNew Match\t2\nNew Player\t3\nExit\t\t4");
intTemp = scan.nextInt();
// Print Scores
if (intTemp == 1) {
intTemp = 0;
System.out.print("\n");
for (int i = 0; i < numPlayers; i++) {
players[i].print();
}
}
// New Match
if (intTemp == 2) {
intTemp = 0;
System.out.println("\nEnter Name 1");
scan.nextLine();
String name1 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name1.equals(players[i].name)) {
players[i].win++;
break;
}
}
System.out.println("\nEnter Name 2");
scan.nextLine();
String name2 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name2.equals(players[i].name)) {
players[i].loss++;
break;
}
}
}
// New Player
if (intTemp == 3) {
intTemp = 0;
System.out.println("\nWhat's the player's name?");
scan.nextLine();
stringTemp = scan.nextLine();
players[numPlayers] = new Player();
players[numPlayers].name = stringTemp;
numPlayers++;
System.out.println(numPlayers);
}
// Exit
if (intTemp == 4) {
System.exit(0);
}
}
}
}
It stalls because of this;
scan.nextLine();
scan.nextLine();
String name2 = scan.nextLine();
It is waiting for input 3 times. You only want input once so replace it with;
String name2 = scan.nextLine();
In the future things like this can easily be debugged by checking if the code actually enters the for loop by printing out a little message in the loop.
String name2 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
System.out.println("We have entered the loop.");
if (name2.equals(players[i].name)) {
players[i].loss++;
break;
}
}
If you see output in the console then you know the problem is not with the loop itself, but is before it.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So I'm trying to count the number of integer occurrences in this program. The code still doesn't work, but am I on the right track?
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int userInput = 0;
ArrayList<Integer> myList = new ArrayList<Integer>();
int[] newArray = new int[myList.size()];
int index1 = -1;
int current;
for (int num = 0; num <= userInput ; num++)
{
System.out.println("Please enter a random number between 0 and 50, enter a negative number to end input: ");
num--;
if(userInput >= 0 || userInput <= 50)
{
userInput++;
userInput = scan.nextInt();
index1++;
myList.add(userInput);
}
if (userInput < 0 || userInput > 50)
{
myList.remove(index1);
index1--;
break;
}
}
for (int num2 = 0; num2 < myList.size(); num2++)
{
current = myList.get(num2);
if(current == myList.get(num2))
{
newArray[current-myList.get(num2)]++;
}
}
for (int number=0; number < newArray.length; number++)
{
System.out.println(number + "1");
System.out.println(" : " + newArray[number]);
}
}
}
edit:
just wanted to add that I can run the program, but when I input an integer that is out of bounds (not between 0 and 50), I get an error
I just finished writing this, thanks for the downvotes while I was modifying my code and specifically stated I was modifying the code. Hashmaps will do the trick for you here.
public static void main(String args[]) {
HashMap<Integer, Integer> numbers = new HashMap<Integer, Integer>();
Scanner scan = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("Number: ");
int current = scan.nextInt();
if (current > 0 && current < 51) {
if (numbers.containsKey(current)) {
numbers.put(current, numbers.get(current)+1);
}else{
numbers.put(current, 1);
}
} else {
if(numbers.isEmpty()){
System.out.println("Nothing inputted");
loop = false;
}else{
for(Entry<Integer,Integer> e : numbers.entrySet()){
System.out.println(e.getKey() + " was entered " + e.getValue() + " times");
}
loop = false;
}
}
}
}
You do not need any additional collection like myList.
You can declare array
int[] occurrences = new int[51];
which can store occurence of elements from range [0,50]. When You read n as nextInt from scanner You should increment element of this array at readed n-th position if n is in range or stop reading new values otherwise.
This if statemest is always true:
current = myList.get(num2);
if(current == myList.get(num2))
Code example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] occurrrences = new int[51];
while (true){
int value = scanner.nextInt();
if(value>=0 && value<occurrrences.length){
occurrrences[value]++;
}else{
scanner.close();
break;
}
}
for (int i = 0; i < occurrrences.length; i++) {
if(occurrrences[i]>0){
System.out.println(i + " occured " + occurrrences[i] + " times.");
}
}
}