adding values to an array using counter - java

I've been learning java for the last 1.5 month. Now the instructor has asked us to create a program that take the name and phone number (but in a method) from the user until the user enters "E". The program should then print all the information stored in the all the arrays.
The program has a main menu and the user will enter "1" to create an account (name and phone number) and then the main menu appears again and the user create another account and so on and so forth... until he chooses another option from the menu or enter "E" to exist and print the summary for all the accounts.
My problem is that I tried to create a counter as a references to each account spot in the arrays(index in array); so after each time the user enters a name and a number the counter add 1 and the arrays index add 1 and moves to the next spot… but that didn't work.
I didn't complete the code, stopped at choice 1 to test the create account method
public static void addDonor(String[] a1, String[] a2, char[] a3, int[] a4, int [] a5){
Scanner input = new Scanner(System.in);
System.out.print(" Enter the name (first and last):" + " ");
String name = input.nextLine();
System.out.print(" Enter Mobile No.:" + " ");
String phone = input.next();
if (phone.length() < 10 && phone.startsWith("0") == false){
while (true){
System.out.println("Wrong Mobile NO... try again!");
System.out.print(" Enter Mobile No.:" + " ");
phone = input.next();
if (phone.length() > 10 || phone.startsWith("0") == true)
break;
}
}
System.out.print(" Enter Blood Group Type (A, B or O):" + " ");
char blood = input.next().charAt(0);
while (blood != 'a' || blood != 'b' || blood != 'c'){
System.out.println("Wrong Blood Group Type... try again!");
System.out.println(" Enter Blood Group Type (A, B or O):" + " ");
blood = input.next().charAt(0);
if (blood == 'A' || blood == 'B' || blood == 'O')
break;
}
int counter = 0;
a1[counter] = name;
a2[counter] = phone;
a3[counter] = blood;
a4[counter] = 1;
a5[counter] = 1;
counter++;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] Name = new String[20];
String[] Mobile = new String[20];
char[] Blood_Gp = new char[20];
int[] Count_o_Donation = new int[20];
int[] Blood_Stock = new int[20];
while (true){
displayMainMenu();
readAndVerify();
String choice = readAndVerify();
switch (choice){
case "1":
addDonor(Name, Mobile, Blood_Gp, Count_o_Donation, Blood_Stock);
break;
}
if (choice.equals("e"))
break;
}
System.out.println(Name[0]);
System.out.println(Name[1]);
}

The problem is thar you are creating the variable index inside the addDonor method. So everytime the method is invoked a new variable with value 0 is going to be created, that's why it's not moving. You should create the varible outside the method and pass it as parameter.
Something like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] Name = new String[20];
String[] Mobile = new String[20];
char[] Blood_Gp = new char[20];
int[] Count_o_Donation = new int[20];
int[] Blood_Stock = new int[20];
int index = 0;
while (true){
displayMainMenu();
readAndVerify();
String choice = readAndVerify();
switch (choice){
case "1":
addDonor(Name, Mobile, Blood_Gp, Count_o_Donation, Blood_Stock, index);
index++
break;
}
if (choice.equals("e"))
break;
}
System.out.println(Name[0]);
System.out.println(Name[1]);
}
public static void addDonor(String[] a1, String[] a2, char[] a3, int[] a4, int [] a5), int index{
Scanner input = new Scanner(System.in);
System.out.print(" Enter the name (first and last):" + " ");
String name = input.nextLine();
System.out.print(" Enter Mobile No.:" + " ");
String phone = input.next();
if (phone.length() < 10 && phone.startsWith("0") == false){
while (true){
System.out.println("Wrong Mobile NO... try again!");
System.out.print(" Enter Mobile No.:" + " ");
phone = input.next();
if (phone.length() > 10 || phone.startsWith("0") == true)
break;
}
}
System.out.print(" Enter Blood Group Type (A, B or O):" + " ");
char blood = input.next().charAt(0);
while (blood != 'a' || blood != 'b' || blood != 'c'){
System.out.println("Wrong Blood Group Type... try again!");
System.out.println(" Enter Blood Group Type (A, B or O):" + " ");
blood = input.next().charAt(0);
if (blood == 'A' || blood == 'B' || blood == 'O')
break;
}
a1[index] = name;
a2[index] = phone;
a3[index] = blood;
a4[index] = 1;
a5[index] = 1;

This isn't really a java question as much as it is a debug question. Your counter is local to the method it is in, so every time the method gets called the counter gets reset.
A variable has a scope. The scope of a variable depends on where you define it. Inside a method block (or inside the parameter section) a variable will live as long as the method block. If defined inside a class as non-static it will live as long as the instance. If defined as static inside a class it will live as long as the class (most of the time this means forever)
In your case you have 2 options: Either you make the variable static, define it outside of your addDonor method and pass it down into the addDonor method by value (so you cannot increment it inside addDonor, do this whereever you call addDonor).
If you go with the static variable then your code remains unchanged. Static variables generally are defined at the top of the class.
If you go with the passing variable down into addDonor then the main method becomes responsible for keeping and incrementing the counter variable. Make sure it only gets incremented on a succesful iteration.
There are other things you can do but they need you to know about Objects.

There are many mistakes here.
First of you should really gather all the information you need in a class. That way you could easily store it all in one array.
public class donor{
String name;
String mobile
...
}
Secondly since you don't know how many inputs you are getting and array is really a stupid way of storing it. If you use a list you can simply do:
List<Donor> donors = new ArrayList<>();
donors.add(donor);
If you need to use an array you could try to use a counter. I would probably do it something like this:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String[] name = new String[20];
String[] mobile = new String[20];
char[] bloodGroup = new char[20];
int[] countODonation = new int[20];
int[] bloodStock = new int[20];
int counter = 0;
boolean continue = true;
while (continue){
displayMainMenu();
String choice = readAndVerify();
switch (choice){
case "1":
name[counter] = readName();
...
counter++;
break;
}
if (choice.equals("e"))
continue = false;
}
}
But once again you should really use a class for the donor stuff. And a list.

Related

Replacing Position in Array Amongst Other Methods

Firstly - I thank anyone who takes the time to actually look at this since I feel like it's a rather annoying request.
I just completed a large challenge at the end of a series of Java 101 videos. The challenge is to design a guest list method ( as in for a restaurant or a party ) and some features along with it. This is really the first time I've written anything with multiple methods.
As the final step in this challenge, I need to design a method that allows the user to insert a new guest at a certain position while not removing any other guests. In other words, inserting a new guest and shifting the remaining guests downwards by a single index.
The issue I have is that the new guest is always inserted not only for the position I want, but also the position one after. It inserts itself twice and ends up over-writing the previous guest in the process.
import java.util.Scanner;
import java.io.*;
import java.lang.*;
import java.util.*;
public class GuestList_Edited {
public static void main(String[] args) {
// Setup for array, setup for scanner
String[] guests = new String[11];
Scanner scanner = new Scanner(System.in);
// A method to put these here so we don't always have to add guests. This method automatically inserts five guests into the guest list.
InsertNames(guests);
// Do-while loop to make sure that this menu screen shows up every time asking us what we want to do.
// It also makes certain that the menu shows up when we initially run the program.
do {
displayMenu(guests);
// This must remain in main for the rest of the program to reference it.
int option = getOption();
// If loop that will allow people to add guests
if (option == 1) {
addGuest(guests);
} else if (option == 2) {
RemoveGuest(guests);
} else if (option == 3) {
RenameGuest(guests);
} else if (option == 4) {
insertGuest(guests);
} else if (option == 5) {
System.out.println("Exiting...");
break;
}
} while (true);
}
// This displays the starting menu
public static void displayMenu(String SentArr[]) {
System.out.println("-------------");
System.out.println(" - Guests & Menu - ");
System.out.println();
GuestsMethod(SentArr); // Makes all null values equal to --
System.out.println();
System.out.println("1 - Add Guest");
System.out.println("2 - Remove Guest");
System.out.println("3 - Rename guest");
System.out.println("4 - Insert new guest at certain position");
System.out.println("5 - Exit");
System.out.println();
}
// This prints all the guests on the guest list and also adjusts the guest list when a guest is removed
public static void GuestsMethod(String RecievedArr[]) {
// If loop which prints out all guests on the list.
// "Null" will be printed out for all empty slots.
for (int i = 0; i < RecievedArr.length - 1; i++) {
// Make all null values and values after the first null value shift up in the array.
if (RecievedArr[i] == null) {
RecievedArr[i] = RecievedArr[i + 1];
RecievedArr[i + 1] = null;
}
// Make all null's equal to a string value.
if (RecievedArr[i] == null) {
RecievedArr[i] = " ";
}
// If values are not equal to a blank string value, assign a number.
if (RecievedArr[i] != " ") {
System.out.println((i + 1) + ". " + RecievedArr[i]);
}
// If the first value is a blank string value, then print the provided line.
if (RecievedArr[0] == " ") {
System.out.println("The guest list is empty.");
break;
}
}
}
// I've really got no idea what this does or why I need a method but the course I'm taking said to create a method for this.
// It gets the desired option from the user, as in to add a guest, remove a guest, etc.
static int getOption() {
Scanner scanner = new Scanner(System.in);
System.out.print("Option: ");
int Option = scanner.nextInt();
return Option;
}
// Allows users to add guests
public static String[] addGuest(String AddArr[]) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < AddArr.length; i++) {
// The below if statement allows the program to only ask for a name when a given space is "null", meaning empty.
if (AddArr[i] == " ") {
// so the loop runs until it hits a null value.
System.out.print("Name: ");
AddArr[i] = scanner.nextLine();
// Then that same value which was null will be replaced by the user's input
break;
}
}
return AddArr;
}
public static String[] RemoveGuest(String RemoveArr[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RemoveArr.length; i++) {
if (RemoveArr[number] != null) {
RemoveArr[number] = null;
break;
}
}
return RemoveArr;
}
// This inserts names into the array so we don't have to add guests everytime.
public static String[] InsertNames(String InsertNames[]) {
InsertNames[0] = "Jacob";
InsertNames[1] = "Edward";
InsertNames[2] = "Rose";
InsertNames[3] = "Molly";
InsertNames[4] = "Christopher";
// guests[5] = "Daniel";
// guests[6] = "Timblomothy";
// guests[7] = "Sablantha";
// guests[8] = "Tagranthra";
return InsertNames;
}
public static String[] RenameGuest(String RenamedGuests[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RenamedGuests.length; i++) {
if (RenamedGuests[number] != null) {
RenamedGuests[number] = null;
System.out.println("What would you like the guest's name to be?");
String NewName = scanner.next();
RenamedGuests[number] = NewName;
break;
}
}
return RenamedGuests;
}
// The final method which I am struggling with.
public static String[] insertGuest(String NewPositionArray[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number: ");
int num = scanner.nextInt();
scanner.nextLine();
if (num >= 1 && num <= 10 && NewPositionArray[num - 1] != null)
System.out.print("Name: ");
String name = scanner.nextLine();
for (int i = 10; i > num - 1; i--) {
NewPositionArray[i] = NewPositionArray[i - 1];
NewPositionArray[num - 1] = name;
}
if (num < 0 || num > 10) {
System.out.println("\nError: There is no guest with that number.");
}
return NewPositionArray;
}
}
Once again, thanks. I realize I've probably done 1000 things wrong here. I appreciate your consideration.
I recommend you to declare ArrayList object instead of the normal array declaration; to avoid heavy work on the code where you can add an element into the ArrayList object with predefined add(int position, an element with your data type) method in a specific position and the ArrayList automatically will shift the rest elements to the right of it.
and for several reasons.
for more info about ArrayList in Java, please look at: -
Array vs ArrayList in Java
Which is faster amongst an Array and an ArrayList?
Here an example of add() method; which inserts the element in a specific position: -
Java.util.ArrayList.add() Method

Do While loop not coordinating with a Scanner the 2nd time

I have a project that I need help with. I'm a beginner in programming, and I don't understand this. I'm hoping to get an answer.
Scanner reg_input = new Scanner(System.in);
int ctr = 0,item = 1;
char reg_mn = 'y', choice;
String[] user = new String[item];
String[] pass = new String[item];
reg_mn = 'y';
do {
System.out.println("[REGISTER]");
System.out.println("==========");
System.out.print("Username: ");
user[ctr] = reg_input.next(); //Line 11
System.out.print("Password: ");
pass[ctr] = reg_input.next();
System.out.println("==========");
System.out.println("Do you wish to Continue? [Y/N]");
choice = reg_input.next().charAt(0);
if (choice == 'y' || choice =='y') {
item = item + 1;
}
else if (choice == 'n' || choice == 'N') {
reg_mn = 'n';
item = item + 1;
return;
}
ctr++;
} while (reg_mn == 'y' || reg_mn == 'Y');
the 1st loop is fine. The problem here is when I type "y" to
try and get the 2nd loop, I get an error from the scanner at Line 11
I researched for problems like this but I seem to get dead ends, that or I haven't read it properly.
Because you have declared a string with the size of an item whose value is 1 initially.
So if you increment the item by 1 but the string array size would not be incremented because it is declared with size 1.
String[] user = new String[item];
String[] pass = new String[item];
Change like this
String[] user = new String[30];
String[] pass = new String[30];
You have to declare with some maximum size.
I suggest you use any java Collections for this like HashMap.
Because here you are declaring the string array with maximum size so it allocated that size however if you are storing only 2 users remaining size would be waste. For this use Collections.

How do I set the conditional statement in this program?

So this code asks for a name and a number 1-20, but if you put in a number over 20 or below 1 the program still runs and I know I need a conditional statement right around figuring out the amount for "ano" to stop and re-ask the statement and re-run the segment but I don't know how to implement it into the code.
// library - for interactive input
import java.util.Scanner;
//---------------------------------
// program name header
public class feb24a
{
//--------FUNCTION CODING ---------------
// FUNCTION HEADER
public static void seeit(String msg, String aname, int ano)
{
// statement to accomplish the task of this function
System.out.print("\n The message is " + msg + "\t" + "Name is:" + aname + "\t" + "number is: " + ano);
// return statement without a variable name because it is a void
return;
}
//------------------- MAIN MODULE CODING TO CALL FUNCTIONS ----------------
// Main module header
public static void main (String[] args)
{
String msg, aname;
int ano, again, a, b;
msg = "Hello";
a = 1;
b = 20;
//Loop control variable
again = 2;
while(again == 2)
{
System.out.print("\n enter NAME: ");
Scanner username = new Scanner(System.in);
aname = username.nextLine();
System.out.print("\n enter number 1-20: ");
Scanner userno = new Scanner(System.in);
ano = userno.nextInt();
seeit(msg, aname, ano);
//ask user if they want to do it again, 2 for yes any other for no
System.out.print("\n do you want to do this again? 2 for yes ");
Scanner useragain = new Scanner(System.in);
again = useragain.nextInt();
} //terminate the while loop
}
}
Replace your while loop with this:
Scanner scanner = new Scanner(System.in);
while (again == 2) {
ano = 0;
System.out.print("\n enter NAME: ");
aname = scanner.nextLine();
while (ano < 1 || ano > 20) {
System.out.print("\n enter number 1-20: ");
ano = scanner.nextInt();
}
seeit(msg, aname, ano);
System.out.print("\n do you want to do this again? 2 for yes ");
again = scanner.nextInt();
}
Try to surround your ano = userno.nextInt() in a while loop. (i.e., while(ano < 1 || ano > 20)) and put a prompt inside that while loop. That way, it will keep reading a new number until it finally no longer fulfills the while loop and will break out.

Java iterate through array [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I am trying to write a java program with 2 arrays 1 for name (String) and the other representing age (integer) the program should iterate and ask for a max of 10 names and ages of each, then display all array items as well as max and min ages of each, or unless the user enters 'done' or 'DONE' mid-way through.
I have the following code although struggling to loop around and ask user for names and ages x10.
Any suggestions?
Thank you.
import java.util.Scanner;
public class AgeName {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int numTried = 1;
int ageTried = 1;
boolean stop = false;
String name = "";
String[] num = new String[10];
int[] age = new int[10];
while(numTried <= 10 && ageTried <=10 && !stop){
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
if(name.toUpperCase().equals("DONE")){
stop = true;
}else{
num[numTried - 1] = name;
age[ageTried -1] = userAge;
}
numTried ++;
ageTried ++;
}
for(String output : num){
if(!(output == null)){
System.out.print(output + "," );
}
}
input.close();
}
}
You can use a Map<String,Integer>:
HashMap<String, Integer> map = new HashMap<String, Integer>();
String[] num = new String[10];
for (int i = 0; i < 10; i++) {
System.out.print("Enter name " + numTried + ": ");
name = input.nextLine();
System.out.print("Now enter age of " + name + ": ");
int userAge = input.nextInt();
num[i] = name;
map.put(name, userAge);
}
for (String output : num) {
if (!(output == null)) {
System.out.print(output + ","+ map.get(output));
}
}
Map as its name suggests allows you to map one object type to another. the .put() method adds a record that contains a pair of String and an integer and maps the string to the int. The String has to be UNIQUE!!
You should ask in any iteration if the user is done. For example you could set a string variable as answer = "NO", and ask the user at the end of any iteration if he is done. If you try this remember to replace stop variable with answer at your iteration block condition.
System.out.println("Are you done: Choose -> YES or NO?");
answer = input.nextLine();
if (answer == "YES")
break;

Using a sentinel While loop in Java to go add cell phone plan options

I'm really stuck on this one. I have to create a menu of cell phone plan add ons. I then have to write a java code segment that will display a menu of these options and loop to allow the user to choose the desired options until the user enters a -1. This is what I have so far:
import java.util.Scanner;
public class CellPhone {
public static void main(String[] args) {
//new array
String [] plans = new String[4];
plans[0] = "a. 200 or less text messages a month: $5.00";
plans[1] = "b. Additional line: $9.99";
plans[2] = "c. International calling: $3.99";
plans[3] = "d. Early nights and weekends: $16.99";
System.out.println("Here are your plan options: ");
//outputs the contents of the array
for(int i = 0; i < 4; i++) {
System.out.println(plans[i]);
}
// Sentinel loop for adding options
final String SENTINEL = "-1";
String choices = plans[0];
Scanner scanner = new Scanner(System.in);
System.out.println("What would you like to add to your plan (options are a,b,c, or d. Enter -1 when you are finished): ");
String yourChoice = scanner.nextLine();
while (yourChoice != SENTINEL) {
}
}
}
How exactly can I make this happen and what do I need to put inside the while loop? Thanks!
You could do something like this.
while(true) {
System.out.println("What would you like to add to your plan (options are a,b,c, or d. Enter -1 when you are finished): ");
String yourChoice = scanner.nextLine();
if(yourChoice.equals(SENTINEL))
return;
}
or if you have to use sentinel:
do {
System.out.println("What would you like to add to your plan (options are a,b,c, or d. Enter -1 when you are finished): ");
yourChoice = scanner.nextLine();
} while (!yourChoice.equals(SENTINEL));
This is one way to get the total Price:
double price = 0.0;
do {
System.out.println("What would you like to add to your plan (options are a,b,c, or d. Enter -1 when you are finished): ");
yourChoice = scanner.nextLine();
switch (yourChoice) {
case "a":
price += Double.parseDouble(plans[0].substring(plans[0].length()-4, plans[0].length()));
break;
case "b":
price += Double.parseDouble(plans[1].substring(plans[1].length()-4, plans[1].length()));
break;
case "c":
price += Double.parseDouble(plans[2].substring(plans[2].length()-4, plans[2].length()));
break;
case "d":
price += Double.parseDouble(plans[3].substring(plans[3].length()-5, plans[3].length()));
break;
}
} while (!yourChoice.equals(SENTINEL));
System.out.println("Total price: " + price);

Categories

Resources