I'm making a database where you can enter in animals and the supplements that they need. I have to use a multidimensional array. The problem I'm running into is that when a user goes into entering data into the multidimensional array, I get an out of bounds error. I'm confused because I used the same methodology for the user to input the type of animal and the number of supplements needed, but when it gets to actually entering the supplement, I introduced and array hold to keep the supplements for each animal organized. For a more visual reference, my logic wanted to be like this:
Names
Animal Type 1 Supplement 1
The Animal types go down the first column while the supplements fill in a horizontal fashion on each animal. I'll post my code but specifically I've run into issues with the array out of bounds. I suspect it has to do with how I initialized the multi array, but I'm unsure at this point. Any help would be greatly appreciated!
//Nicholas Stafford
//February 1, 2016
//This program will allow user input of up to any number of animals and dietary information and then allow the user to display that information when searching the database
import java.util.Scanner;
import java.util.Arrays;
public class inventory {
public static void main(String[] args)
{
//Initial variables
int choiceent;
int numAnimals = 0;
int numDiet = 0;
int ArrayHold = 0;
boolean isNum;
boolean isNum2;
boolean quit = false;
//Scanners needed for input
Scanner choice = new Scanner(System.in);
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
Scanner input3 = new Scanner(System.in);
Scanner input4 = new Scanner(System.in);
//Initial value needed to enter animals into database
System.out.println("Enter the number of animals you wish to enter:");
do
{
if(input1.hasNextInt()) {
numAnimals = input1.nextInt();
isNum = true;
}
else {
System.out.println("Please enter an integer value!");
isNum = false;
input1.next();
}
}
while(!(isNum));
System.out.println("You are entering " +numAnimals+ " animals.");
//Multidimensional array
String [][] ZooBase = new String [100][100];
//Array for data types
int numDietA[] = new int [numAnimals];
do{
System.out.println("1. Enter the names of each animal");
System.out.println("2. Enter the dietary information");
System.out.println("3. Search the array for information");
System.out.println("4. Close the program");
choiceent = choice.nextInt();
switch(choiceent)
{
case 1:
//Data validation for name
for(int i = 0; i < numAnimals; i++)
{
System.out.println("Enter the type of animal for animal " +i+ "");
while(!input2.hasNext("[a-zA-Z]+"))
{
System.out.println("Enter a type of animal!");
ZooBase[i+1][0] = input2.nextLine();
}
ZooBase[i+1][0] = input2.nextLine();
}
//Display Names
System.out.println("Names");
for(int j = 0; j < numAnimals; j++){
System.out.println(ZooBase[j+1][0]);
}
break;
case 2:
for(int j = 0; j < numAnimals; j++)
{
System.out.println("How many supplements does the " +ZooBase[j+1][0]+ " need?");
do
{
if(input3.hasNextInt()) {
numDietA[j] = input3.nextInt();
isNum2 = true;
}
else {
System.out.println("Please enter an integer value!");
isNum2 = false;
input3.next();
}
}while(!(isNum2));
}
for(int k = 0; k < numAnimals; k++)
{
ArrayHold = k+1;
for(int m = 0; m < numDietA[m]; m++ )
{
System.out.println("Enter item " +m+ " for the " +ZooBase[m+1][0]+ "");
while(!input4.hasNext("[a-zA-Z]+"))
{
System.out.println("Enter a supplement (No integers)!");
ZooBase[ArrayHold][m+2] = input4.nextLine();
}
ZooBase[ArrayHold][m+2] = input4.nextLine();
}
}
break;
case 3:
break;
case 4:
quit = true;
break;
default:
System.out.println("Invalid option!");
break;
}
}while(choiceent != 4);
}
}
Once an array is initialized, its size can't be changed. To make sure this does not happen, use ArrayList<>, which does not have fixed bounds. You can find the syntax + all details here: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Hope that helps!
ps. you can also initialize just 1 scanner input and use it throughout
Related
My homework question is to Create a procedure called NoDuplicates which will prompt the user to enter 7 unique integers. As the user enters the numbers, ask them to re-enter a number if it has been entered previously. Output the 7 unique numbers.
I have tried a lot of different combinations of while and for loops but nothing works
import java.util.Scanner;
public class arrayexcersisespart3num1 {
public static void main(String []arg) {
Scanner input = new Scanner(System.in);
noDuplicates(input);
}
public static void noDuplicates(Scanner input) {
boolean check = true;
int jumbo;
int[]noDuplicates = new int [7];
System.out.println("Please enter a unique Name");
for (int i = 0; i<noDuplicates.length;) {
System.out.println("Enter a number");
jumbo = input.nextInt();
while(check ==true|| i>0) {
check = false;
System.out.println("Please enter another number");
jumbo = input.nextInt();
if (jumbo==(noDuplicates[i])) {
check = true;
System.out.println("this Name has been previously added. Please choose another number");
}
}
jumbo = noDuplicates[i];
System.out.print("this Number has been previously successfully added in position ");
System.out.println(i+1);
check = false;
i++;
}
}
}
I don't understand your code, but:
final int N = 7; // Constant, used multiple times throughout the program
Scanner sc = new Scanner (System.in);
int[] noDuplicates = new int[N];
noDuplicates[0] = sc.nextInt();
for(int i=1; i<N; i++){ // Loops through the array to put numbers in
int query = sc.nextInt(); // Number to be put into the array
for(int j=0; j<i-1; j++){
if(noDuplicates[j] == query){ // If they are the same
i--;
continue; // Tells them to input a new number, skips all code ahead
}
}
noDuplicates[i] = query;
}
Try this logic of Collection.contains then add it in collection. It will ask the input from user from console and check whether data store in List or Not. Like this it will ask the value from user for 7 unique time on list used that
public void uniqueDataCheckOnConsoleOnLimitByList() {
int capacity = 7;
List<String> dataList = new ArrayList<>(capacity);
while (capacity != 0) {
System.out.println("Please enter a number");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
if (dataList.contains(s)) {
System.out.println("You already entered the number:" + s);
//System.out.println("Please Enter a New Number");
} else {
dataList.add(s);
capacity--;
}
}
}
As i did not check the requirement on Array. Please check it in case of array.
public void uniqueDataCheckOnConsoleOnLimitByArray() {
int capacity = 7;
String data[]= new String[capacity];
while (capacity != 0) {
System.out.println("Please enter a number");
Scanner in = new Scanner(System.in);
String s = in.nextLine();
if (containsArray(data, s)) {
System.out.println("You already entered the number:" + s);
//System.out.println("Please Enter a New Number");
} else {
data[capacity-1]=s;
capacity--;
}
}
}
public boolean containsArray(String data[],String input){
for(String s:data){
if(input.equalsIgnoreCase(s))
return true;
}
return false;
}
This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 6 years ago.
I'm trying to write a simple program using an ArrayList that adds values, removes values, and prints values. However, I'm having an issue with removing values that the user inputs. The user should input a designated amount of values (determined by the user) and then the program should remove those values (if there are duplicates then it should just remove the first instance of the number which is fine). It's not removing the values and in some cases removes one value. I'm a bit confused as to where my code is bugged. Here is my code for remove values:
private static void removeVals() {
System.out.println("How many values would you like to remove?");
int amountToRemove = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToRemove + " values:");
for(int i = 0; i < amountToRemove; i++) {
int vals = scanner.nextInt();
if(arrayList.get(i).equals(vals)) {
arrayList.remove(i);
}
}
System.out.println("Values removed");
}
And here is my full code:
public class Main {
private static ArrayList<Integer> arrayList = new ArrayList<Integer>();
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
printOptions();
int option = scanner.nextInt();
while (option != 0) {
switch(option) {
case 1:
addVals();
printOptions();
option = scanner.nextInt();
break;
case 2:
removeVals();
printOptions();
option = scanner.nextInt();
break;
case 3:
printVals();
printOptions();
option = scanner.nextInt();
break;
case 4:
printOptions();
printOptions();
option = scanner.nextInt();
break;
default:
System.out.println("Not a valid option, please enter again:");
option = scanner.nextInt();
break;
}
}
}
private static void addVals() {
System.out.println("How many values would you like to add?");
int amountToAdd = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToAdd + " values:");
for(int i = 0; i < amountToAdd; i++) {
int vals = scanner.nextInt();
arrayList.add(vals);
}
}
private static void removeVals() {
System.out.println("How many values would you like to remove?");
int amountToRemove = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter " + amountToRemove + " values:");
for(int i = 0; i < amountToRemove; i++) {
int vals = scanner.nextInt();
if(arrayList.get(i).equals(vals)) {
arrayList.remove(i);
}
}
System.out.println("Values removed");
}
private static void printVals() {
for(int i = 0; i < arrayList.size(); i++) {
System.out.print(arrayList.get(i) + " ");
}
System.out.println();
}
private static void printOptions() {
System.out.println();
System.out.println("Program options: ");
System.out.println("1. Add values\n2. Remove values\n3. Print values\n4. Print options\n0. Exit\n");
System.out.println("\nWhat would you like to do? (enter an option):");
}
}
arrayList.remove(i) removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).
that is the bug your code
for more details refer below link
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(int) ,
I have been trying to find the answer to this question but to no avail!
Basically I have to write a program where 'x' number of players can enter a guessing game and input their guesses and then get a score.
However, right after they input their guesses, i have to output it in a table form like this "NAME GUESS SCORE"
I do not know how i can do this with a for loop since a for loop println can only print values from playersArray. How can I print another array like guessesArray to the side of it?
I can only use Arrays and Methods to do this.
Below I will show u what i have right now:
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class game
{
static int[] guessesArray;
static int guess;
static String [] playersArray;
static int[] currscoresArray;
static int [] addscoresArray;
static int [] finalscoresArray;
public static void main(String [] args){
System.out.print("Number of players? ");
Scanner kb = new Scanner(System.in);
int numplayers = kb.nextInt();
//Initialize
playersArray = new String[numplayers];
guessesArray = new int [numplayers];
currscoresArray = new int [numplayers];
addscoresArray = new int [numplayers];
finalscoresArray = new int [numplayers];
populateArray(playersArray);
displayMenu();
}
public static void populateArray( String[] x){
Scanner kb = new Scanner(System.in);
for (int i = 0; i<x.length ; i++){
System.out.print("Enter Player "+(i+1)+": ");
x[i]=kb.nextLine();
}
}
public static void displayMenu(){
int choice=0;
Scanner kb = new Scanner(System.in);
String[] args = {};
while(true){
System.out.println("Menu ");
System.out.println("1. Make Guess");
System.out.println("2. List Winner");
System.out.println("0. Exit");
System.out.print("Enter choice: ");
choice = kb.nextInt();
if (choice==0){
System.out.print("Do you want to play a new game? Y/N: ");
String ans = kb.next();
if (ans.equals ("Y") || ans.equals ("y")){
main(args);
}
break;
}
switch (choice){
case 1: makeGuess(); break;
case 2: listWinner(); break;
default: System.out.println("Invalid choice");
}
}
System.out.println("End of program");System.exit(0);
}
public static void makeGuess(){
Scanner kb = new Scanner(System.in);
Random rand = new Random();
int secret = rand.nextInt(10)+1;
for (int i=0; i < guessesArray.length; i++){
System.out.print("Enter your guess "+playersArray[i]+": ");
guessesArray[i]=kb.nextInt();
}
int diff = (int)(Math.abs(guess - secret));
int score=0;
if (diff == 0){
score=score+10;
}else if(diff<=1){
score=score+5;
}else if(diff<=2){
score=score+2;
}
for (int i=0; i< currscoresArray.length; i++){
currscoresArray[i]=score;
}
System.out.println();
System.out.println("Generated number is "+secret);
System.out.println("Current Score Listing");
System.out.println(" Name Guess Score Added Final Score");
System.out.println("1. "+playersArray[0]+" \t "+guessesArray[0]+" \t"+currscoresArray[0]+"");
System.out.println("1. "+playersArray[1]+" \t "+guessesArray[1]+" \t"+currscoresArray[1]+"");
}
public static void listWinner(){
}
}
just reuse a int x variable when printing from each array?
for( int x = 0; x < playersArray.length; x++ ) {
System.out.println( playersArray[ x ] + ” ” + guessArray[ x ] + " " + finalScoresArray[ x ] );
}
you already give an example in your code where you print the 3 values with a single print method. you used a for loop for indexing an element in an array. So combing the 2 techniques shouldn't be too difficult to grasp.
Instead of using an enhanced for loop (e.g. for (String player : playersArray) {}, you can use an indexed one:
for (int i = 0; i < playersArray.length; i++) {
String name = playerArray[i];
double score = scoresArray[i];
}
That being said, you should really make a Player class, that holds all information of a single player, and then have just one array, of that type. That's much nicer, not only because you can use enhanced fors, but because you don't need to make sure the arrays are always synced, and your code becomes way easier to understand.
I'm quite new to java, and I've just started the course for a few days. I wrote the following code to make a simple phone book. It gets names and phone numbers first, then it gets a name and passes the phone number. Except the first name, if I enter any name it will print the last line (the name is not in the list) then the related number!!! Why?
import java.util.Scanner;
class MyPhoneBook {
public static void main(String[] args) {
Scanner myScan = new Scanner(System.in);
String[] name = new String[200];
String[] number = new String[200];
System.out.println("when finished all contacts, just type : finish");
for (int a = 0; a < 200; a++) {
System.out.print("\nenter name:");
name[a] = myScan.nextLine();
if (name[a].equals("finish")) {
break;
} else {
}
System.out.print("enter number:");
number[a] = myScan.nextLine();
}
for (int a = 1; a > 0; a++) {
System.out.println("\nenter name to find number:\n");
String name2 = myScan.nextLine();
for (int b = 0; b < 200; b++) {
if (name2.equals(name[b])) {
System.out.println("number is " + number[b]);
break;
}
}
System.out.println("----THE NAME IS NOT IN THE LIST----\n");
}
}
}
Add a flag for when you find a name that matches user's input and dont print out last line when you find match, for that you could change your code like this:
for (int a = 1; a > 0; a++) {
System.out.println("\nenter name to find number:\n");
String name2 = myScan.nextLine();
boolean isNameFound = false;
for (int b = 0; b < 200; b++) {
if (name2.equals(name[b])) {
System.out.println("number is " + number[b]);
isNameFound = true;
break;
}
}
if (!isNameFound)
System.out.println("----THE NAME IS NOT IN THE LIST----\n");
}
Using a map will simplify this
Map<> contactBook = new Hashmap<>()
//then load the map using the phone number and name
You can also use data structure which will not allow dup names
I am trying to call my add method to add a score to my array
I've got this so far, but I keep getting an error saying myQuiz was never initialized.
......................................................................................
import java.util.Scanner;
public class Assignment7 {
public static void main (String[] args) {
//new scanner
Scanner in = new Scanner (System.in);
String choice;
char command;
// print the menu
int count = 0;
int counter = 0;
printMenu();
int array[] = new int[0];
//do while loop testing using user input
do{
// ask a user to choose a command
System.out.println("\nPlease enter a command or type ?");
choice = in.next().toLowerCase();
command = choice.charAt(0);
//start switch statement for user input cases
switch (command)
{
switch (command)
{
case 'n': //ask and read the size of the input array and name
System.out.print("\n\t n [Create a new Quiz]: ");
System.out.print("\n\t [Input the size of quizzes]: ");
int num=in.nextInt(); // read the integer
array = new int[num];
System.out.print("\n\t [Input the name of the student]: ");
String name = in.next(); //read name
Quiz myQuiz = new Quiz(num, name);
break;
case 'a': // ask and add score to array
System.out.print("\n\t a [Add a score]: ");
array[count] = in.nextInt();
myQuiz.add(array[count]);
counter++;
break;
/*
case 'a': // ask and add score to array
System.out.print("\n\t a [Add a score]: ");
array[count] = in.nextInt();
myQuiz.add(array[count]); //HELP
counter++;
break;
And my Quiz.java with add method
public class Quiz {
private int count;
private int[] scores;
private String name;
public Quiz(int a,String name){
scores = new int [a];
for (int i = 0; i<scores.length; i++){
scores[i] = -1;
}
this.count = 0;
this.name = "";
}
public void add(int b){
for(int i : scores){
if(scores[i] == count){
System.out.println("Array is full. The value " + b + " cannot be added.");
}
else {
scores[count] = b;
count++;
}
Watch your scopes more carefully: You define myQuiz in one branch of your switch-case statement, but you access it in another branch, too. What happens, if case 'a' is accessed? The myQuiz variable is unknown there!
case 'n': //ask and read the size of the input array and name
System.out.print("\n\t n [Create a new Quiz]: ");
System.out.print("\n\t [Input the size of quizzes]: ");
int num=in.nextInt(); // read the integer
array = new int[num];
System.out.print("\n\t [Input the name of the student]: ");
String name = in.next(); //read name
Quiz myQuiz = new Quiz(num, name);
break;
case 'a': // ask and add score to array
System.out.print("\n\t a [Add a score]: ");
array[count] = in.nextInt();
myQuiz.add(array[count]);
counter++;
break;
You have to define myQuiz outside of your switch-case statement, before it, to be more specific.
You create an empty array :
int array[] = new int[0];
and try to assign numbers to it :
array[count] = in.nextInt();
It can't work.
You must give it a positive length.