Two-Dimensional Array of contacts (Java) - java

I'm trying to make a basic program that allows the use to input and remove up to 10 contacts (a [10][4] array supposed to be filled with First Name, Last Name, Phone #, and age). However when I try to input the 5th contact eclipse gives me an error message. I'd like to know why I'm receiving an error message. (I assume it's something to do with the columns since it's whenever i'm inputting something >4, but i'm not sure what exactly.)
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args){
new Lab2 ();
}
// This will act as our program switchboard
public Lab2 (){
Scanner input = new Scanner(System.in);
String[][] personalInfo = new String[10][4];
System.out.println("Welcome to the contacts database.");
System.out.println("Please select a number from the options below");
System.out.println("");
while(true){
// Give the user a list of their options
System.out.println("1: Add a new contact.");
System.out.println("2: Remove an existing contact.");
System.out.println("0: Exit the database.");
// Get the user input
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addContact(personalInfo);
break;
case 2:
removeContact(personalInfo);
break;
case 0:
System.out.println("Thank you for using the contact database.");
System.exit(0);
}
}
}
private void addContact(String personalInfo[][])
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println( " Hello user, please enter your contact info. (I.E. First and Last Names, Phone #, and Age. Max 10 Contacts)");
String addedContact = input.nextLine();
int j;
for(int i = 0; i < personalInfo.length; i++)
{
for(j = 0; j < personalInfo.length; j++){
if(personalInfo[i][j] == null)
{
personalInfo[i][j] = addedContact;
break;
}
}
}
}
private void removeContact(String personalInfo[][]) {
Scanner input = new Scanner(System.in);
System.out.print( " Please enter an existing contact that you would like to remove. ");
String deleteContact = input.nextLine();
int i , j;
for(i = 0; i < personalInfo.length; i++)
{
for(j = 0; j < personalInfo.length; j++){
if(personalInfo[i][j].equals(deleteContact))
{
personalInfo[i][j] = null;
break;
}
}
}
}
}

Try like this for(j = 0; j < personalInfo[i].length; j++){

First things first:
String[][] personalInfo = new String[10][4];
This statement creates a 2dimensional array of Strings, thus creating an array that is capable of holding an array that is capable of holding strings. (in this case 10 arrays that keep 4 strings each)
Now the error:
String addedContact = input.nextLine();
This line puts the entire line you added in a single string.
Now the loops:
1. The outer loop loops correctly through the 10 arrays of strings.
2. The inner loop does not loop through the '2nd dimension', that is the actual array which will hold your contact. This loop should be as #Kannan Thangadurai described:
for(j = 0; j < personalInfo[i].length; j++){
(add relevant code here)
}
The last error you made is more of a bug, and is in the way you read out the user input. You actually only ever put a string in the first array and so your four contacts that you saved will all be under personalinfo[1] then you try to add another contact in the fifth place of the array that does not exist, thus raising your error.

You're working with jagged array (or array of arrays)
String[][] personalInfo = new String[10][4];
so in order to itterate it you should use different lengths for dimensions (in general case the
required length is personalInfo[i].length):
for (int i = 0; i < personalInfo.length; ++i) // <- outer array
for (int j = 0; j < personalInfo[i].length; ++j) // <- inner length depends on i
if (personalInfo[i][j] == null) {
personalInfo[i][j] = addedContact;
break;
}

Related

Else statement not printing, wondering if I am calling from setter method incorrectly in java

I'm trying to make a program in java which creates an array. I am trying to have OOP approach. I've made a class file which contains a setter method and my array:
public class MenuTestClass{
private int myMonths[];
private double average; //store average value of numbers
private boolean averageCanBeCalculated;
private int max; // store max number from array. to be calculated
public MenuTestClass(){
myMonths = new int[5];
}
public MenuTestClass(int[] myMonths){
this.myMonths = myMonths;
}
public void setMyMonths(int[] values){ //declare setter method
myMonths = values;
}
The elements of the array is taken from the user in my main method:
//Menu loop
int myMonths[] = new int[5];
int index = 0;
int num;
while(choice !=6){
switch (choice){
case 1:
int n = 1; //int n = number of projects
Scanner sc = new Scanner(System.in);
System.out.println("How many months was your project?");
for(int i=0; i<1; i++){
int a = sc.nextInt();
//if months is lesser than 2/greater than 12
if((a < 2) || (a > 12)){
System.out.println("Please enter an amount between 2 and 12 months");}
//if months is between 2 and 12 add it to the array
else{myMonths[index++] = a;}
}
calc.setMyMonths(myMonths); //creating the object
break;
I am trying to create a function which displays all the elements of the array. If the array is empty I want it to display a message stating this. However, my else statement will not run. I am trying to figure out why this is & am I calling the array incorrectly? Please see my code below:
case 2:
if(myMonths.length > 0){
// print the values
for(int i=0; i < myMonths.length; i++){
System.out.println(myMonths[i] + " ");
}
} else {
System.out.println("No values entered");
}
Any help would be great! Thanks in advance
Your code :
for(int i=0; i < myMonths.length; i++){
if(myMonths.length != 0){ //if the array is not empty display all items
System.out.println(myMonths[i] + " ");
}
else{System.out.println("No values entered");} //if array is empty display this message
}
if myMonths.length > 0 then it will check for length !!
your code should be:
if(myMonths.length > 0){
// print the values
for(int i=0; i < myMonths.length; i++){
System.out.println(myMonths[i] + " ");
}
} else {
System.out.println("No values entered");
}
UPDATE:
before you create your Array .. Ask the User for Size,
then you can check if empty or not
System.out.println("inter the size:");
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int[] arr = new int[size];
if (arr.length > 0) {
// do your loop
System.out.println("Not Empty");
} else {
// Empty array
System.out.println("Empty");
}

can't sort array in descending order using external class

I need help with my java code regarding ascending order display, which I'm receiving error on the temp assignment ..specifically these two assignments listed
Customer1Purchase[i].getProductId() = Customer1Product[j].getProductId();
Customer1Purchase[i].getProductId() = temp;
error reads__[The left-hand side of an assignment must be a variable]
below is my code when, part when user choose option 3:
please let me know if I need to provide more information
I'm new to stalk over flow..... Thanks
c1_pNumber relates to number of purchase by customer1
Condition when Customer Invoice Number is Entered
[c1_pNumber] is size or number of elements in array
Customer1Purchase[i].getProductId() Position of FirstElement
// user option 3 ..... using switch case
case 3:
// allow user input
Scanner scan = new Scanner(System.in);
System.out.print("Enter the Invoice Number: ");
int invoice = scan.nextInt();
// if condition is true it should loop to display arranged data in ascending order
// condition where user input = invoice number in record
if(invoice == c1_InvoiceNumber) {
for(int i=0; i<c1_pNumber; i++) {
for(int j=i+1; j<c1_pNumber; j++) {
if(Customer1Purchase[i].getProductId() > Customer1Purchase[j].getProductId()) {
int temp = Customer1Purchase[i].getProductId();
Customer1Purchase[i].getProductId() = Customer1Product[j].getProductId();
Customer1Purchase[i].getProductId() = temp;
}
}
}
System.out.print("Ascending Order: ");
for(int i=0; i<c1_pNumber-1; i++) {
System.out.println(Customer1Purchase[i]);
}
System.out.print(Customer1Purchase[c1_pNumber-1]);
}

2D array, Storing and calling

I think I may be misunderstanding how to store my information into my array and then to call it for later use.
The following code is to ask a user for how many Cd's they have and allow them to enter the Genre, Artist, and Title. Then it is to go back into the loop if there is more than one cd. I believe that I have everything mostly correct but my output is not right. Whenever entering in for 2 Cd's I will be allowed to enter the first three items in for CD 1 but it will then print CD 2 and just go straight to the end of the program.
-I have posted the code along with what happens when entering 1 CD vs 2 CDs
import java.util.Scanner;
public class RiverCDs
{
public static void main (String args[])
{
Scanner scnr = new Scanner (System.in);
int cdTotal = 0; // user controlled, controls the number of rows.
int col = 3; // constant that controls array col.
String value = " "; // holds input for array.
int intervals = 1;
String [][] list = new String [cdTotal][col];
System.out.println("The River Catalog:\n");
System.out.print("How many CD's do you have: ");
cdTotal = scnr.nextInt();
do
{
if (cdTotal <= 0) // checking for bad data.
{
System.out.print("Must be a number greater than 0.\n");
System.out.print("How many CD's do you have: ");
cdTotal = scnr.nextInt();
}
}while(cdTotal <= 0); // set up to catch more bad data.
System.out.print("\nFor each CD, enter the genre, then the artist, then the title.\n");
for (int i = 1; i <= cdTotal; i++) // incrementing cd based on user input.
{
System.out.print("\nFor CD " + i + ":\n");
while (intervals <= 3)// condition to exit while loop for next cd.
{
System.out.print("Enter: "); // outside of for-loop to Enter three items.
value = scnr.nextLine();
scnr.next(); // clearing buffer so as to to print a double Enter.
for (int r = 0; r < list.length ; r++) // enters row according to how many cdTotal equals.
{
for (int c = 0; c < list[col].length; c++) // enters col in each row up to three.
{
list[r][c] = value;// storing array in value for later use.
}
}
intervals++; // incrementing so as to break loop and print next cd statement.
}
}
System.out.print("\nHere is your catalog:\n");
System.out.printf("\n%-20s" + "%-20s" + "%-20s\n","Genre","Artist","Title");
System.out.println();
for (int r = 0; r < list.length; r++)// accessing list rows
{
for (int c = 0; c < list[r].length; c++)// accessing list col to pull out individual parts of data.
{
System.out.printf("%-20s","%-20s","%-20s",list[r][c],list[r][c],list[r][c]); // constant to check for data in array-
//not working
//System.out.printf("%-20s","%-20s","%-20s",list[1][0],list[1][1],list[1][2]);
}
}
scnr.close(); // turning off scanner to allow no more input.
}
}
1CD-
The River Catalog:
How many CD's do you have: 1
For each CD, enter the genre, then the artist, then the title.
For CD 1:
Enter: top
Enter: cami
Enter: havana
Here is your catalog:
Genre Artist Title
2CD-
The River Catalog:
How many CD's do you have: 2
For each CD, enter the genre, then the artist, then the title.
For CD 1:
Enter: top
Enter: cami
Enter: havana
For CD 2:
Here is your catalog:
Genre Artist Title
It looks like this code is a problem:
for (int r = 0; r < i ; r++) // enters row according to how many cdTotal equals.
{
for (int c = 0; c <= col-1; c++) // enters col in each row up to three.
{
list[r][c] = value; // storing array in value for later use.
}
}
This code sets every value in the array to value, if i is large. And you aren't changing value inside the loop, so everything in your array will be exactly the same thing.

Print a value from 2d array in Java

I am working on a program that allows a user to add values to a 2d array and then search the array and display the value. The information is being stored properly, but all I can get to display is the animal name and not the food. Before I get grilled I've searched and implemented a bunch of different methods trying to get the correct output. I'm sure my error is pretty simple if someone could just help me understand, thanks!
/*This program will allow a user to enter information into the zoo
or search by animal for the type of food it eats*/
import java.util.Scanner;
class zoo {
//create array
static String[][] animalFood;
String[][] addArray(int x) {
animalFood = new String[x][2];
Scanner in = new Scanner(System.in);
//loop through array and add amount of items user chose
for (int row = 0; row < animalFood.length; row++){
System.out.print("Enter an animal name: ");
animalFood[row][0] = in.nextLine();
System.out.print("Enter the food the animal eats: ");
animalFood[row][1] = in.nextLine();
}
System.out.println("Thank you for adding information to the zoo!");
System.out.println("You entered the following information: ");
//loop through and print the informationa added
for(int i = 0; i < animalFood.length; i++)
{
for(int j = 0; j < animalFood[i].length; j++)
{
System.out.print(animalFood[i][j]);
if(j < animalFood[i].length - 1) System.out.print(" - ");
}
System.out.println();
}
//prompt the user to search or quit
System.out.println("Please enter the name of the animal to search for or Q to quit: ");
String animalName = in.nextLine();
animalName = animalName.toUpperCase();
if(animalName.equals("Q")){
System.out.println("Thanks for using the program!");
}
else {
searchArray(animalName);
}
return animalFood;
}
String[][] searchArray(String name) {
String matchResult = "There was no " + name + " found in the zoo!";
String itemToMatch = name.toUpperCase();
String arrayItem = "";
String food = "";
for (int i = 0; i < animalFood.length; i++) {
for (int j = 0; j < animalFood.length; j++) {
arrayItem = animalFood[i][j];
arrayItem = arrayItem.toUpperCase();
if(arrayItem.equals(itemToMatch)){
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[j];
}
else {
//nothing found
}
}
}
System.out.println(matchResult);
if (food != null) {
System.out.println(food);
}
return animalFood;
}
//constructor
public zoo() {
}
//overloaded constructor
public zoo(int x) {
int number = x;
animalFood = addArray(x);
}
//method to get users choice
public static int menu() {
int selection;
Scanner input = new Scanner(System.in);
System.out.println("Please make a choice in the menu below");
System.out.println("-------------------------\n");
System.out.println("1 - Add animals and the food they eat.");
System.out.println("2 - Search for an animal in the zoo.");
System.out.println("3 - Exit the program");
selection = input.nextInt();
return selection;
}
//main method
public static void main(String[] args) {
//create a new object
zoo myZoo = new zoo();
//variables and scanner
int userChoice;
int numberAnimals;
String animalName = "";
Scanner input = new Scanner(System.in);
//call the menu
userChoice = menu();
//actions based on user choice
if (userChoice == 1) {
System.out.println("How many animals would you like to enter information for?");
numberAnimals = input.nextInt();
myZoo.addArray(numberAnimals);
}
if (userChoice == 2) {
System.out.println("Please enter the name of the animal to search for: ");
animalName = input.nextLine();
myZoo.searchArray(animalName);
}
if (userChoice == 3) {
System.out.println("Thank you for using the program!");
}
}
}
It looks to me like your problem is in searchArray. Your nested for loops are iterating over the size of only one dimension of the array:
for (int i = 0; i < animalFood.length; i++) {
for (int j = 0; j < animalFood.length; j++) {
...
}
}
Replace animalFood.length with animalFood[i].length, like you did correctly in the addArray method.
EDIT
It also looks like your output method is incorrect.
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[j];
In this line, animalFood[j] should be animalFood[i][j]. The strange output you're seeing is Java's attempt at converting an array into a String.
2nd Edit
After examining the addArray method, it seems I've made an incorrect assumption about your array. It appears your array is structured such that each index has 2 items, the animal, and its food. So it looks like so:
animalFood[0][0] = 'Cat'
animalFood[0][1] = 'Cat food'
animalFood[1][0] = 'Dog'
animalFood[1][1] = 'Dog food'
etc.
If this is the case, then you're going to want to change your loop to only iterate over the outer index. This means removing the inner for loop inside of searchArray. Then, you're only going to compare the first index of the inner array to the item you want to match, and if there's a match, then the food will be the second index. I'll leave implementation up to you (since this looks like a homework question). If something I've said here sounds wrong, let me know.

How do I get my value to print every time the loop increments in Java (For Loop)

I need to create a code that prints a pyramid like structure, given the user integer input which will be printed last. (I have attached an image of a final product below). I am new to programming, have been enjoying it, but am stuck in this problem.
My code can currently produce the user input 4 times. So I feel like I am close, just a little bit of tweaking will get the job done
I need my code to print out every single time that the loop increments instead of just displaying the user input a certain amount of times. I converted the integer to a string so that I can show the value x amount of times, but I feel that this is what is throwing me off. If I can somehow get the string to display the values at every incrementation then I will be golden. PLEASE HELP! Below is my code
import java.util.Scanner; //import scanner
public class NumberStack { // class
static Scanner myScanner; //declare scanner
public static void main(String[] args){ //add main method
myScanner= new Scanner (System.in); //scanner input declaration
int input= 0;
while (true) {
System.out.print("Enter an integer between 0 and 9 inclusive: ");
if (!myScanner.hasNextInt()) {
System.out.println("You have not entered an integer");
}
input= myScanner.nextInt();
if ( (input>=0) && (input<=9) ) {
String smln= Integer.toString(input);
String out="";
for (int p=0; p<input; p++) {
for (int j=0; j<input; j++) {
for (int i=0; i<((input*2)-1);i++) {
out += smln;
}
System.out.println(""+out);
out="";
smln= Integer.toString(input);
}
}
} //end of if statement
else {
System.out.println("You have not entered an integer within range");
}
} //end of while loop
} //end of main method
} //end of class
when you are facing problems like this one, you should try to look for a pattern...check this out
int input = 4;
for(int i = 1; i <= input; i++)
{
int times = i;
int length = 2 * i - 1;
String str = "";
for(int j = 0; j < length; j++)
{
str += i;
}
for(int k = 0; k < times; k++)
{
System.out.println(str);
}
}
Since your method is currently printing the data fro a particular number properly eg for input 4 it is printing
4444
4444
4444
4444
I would suggest that extract ur code for display into a separate function. And call that function using the number from a loop.
for(int i=1; i<=num;i++)
function_f1(i);
This should do the trick for you and since you are starting off with coding , it will also give you ideas on using methods.

Categories

Resources