Counting the occurrences of a String in an ArrayList - java

I'm using an ArrayList to save the name, day and time of a show. My program requires me to output the number of shows that play on each day of the week. I've inputted 4 different shows, two of which are on the same day. So far, the only thing the output's given me is "On Thursday there are/is 2 show(s)." The other two didn't show. How can I make is so that it displays the number of shows for each day I've inputted? Here's my code for that:
String showDay = ((showInfo)show.get(0)).day.toString();
int totalShows = 0;
//print occurences for how many shows play each day
for (int i = 0; i < show.size(); i++) {
if (showDay.equals(((showInfo)show.get(i)).day.toString())) {
totalShows++;
}
}
System.out.println("On " + showDay + " there are/is " + totalShows + " show(s).");
}
Here's my code for the shows I input:
//input information
do{
showInfo temp = new showInfo();
System.out.print("Enter the name of show: ");
String showName = br.readLine();
temp.name = showName;
System.out.print("Enter which day of the week a new episode premieres: ");
String showDay = br.readLine();
temp.day = showDay;
System.out.print("Enter time in 24-hour format (e.g. 2100, 1900): ");
int showTime = Integer.valueOf(br.readLine()).intValue();
temp.time = showTime;
show.add(temp);
System.out.print("Would you like to add another show? (y/n) ");
}
while((br.readLine().compareTo("n")) != 0);
Keep in mind that I'm using Java 1.4. No other choice. By teacher's demand.
This is probably obvious, but I'm being oblivious right now. Any help would be great! Thanks in advance!
EDIT:
String showDay = ((showInfo)show.get(0)).day.toString();
if("sunday".equalsIgnoreCase(showDay)){
showdayCount[0]++;
System.out.println("There are/is " + showdayCount[0]++ + " show on Sunday.");
}else if("monday".equalsIgnoreCase(showDay)){
showdayCount[1]++;
System.out.println("There are/is " + showdayCount[1]++ + " show on Monday.");
}else if("tuesday".equalsIgnoreCase(showDay)){
showdayCount[2]++;
System.out.println("There are/is " + showdayCount[2]++ + " show on Tuesday.");
}else if("wednesday".equalsIgnoreCase(showDay)){
showdayCount[3]++;
System.out.println("There are/is " + showdayCount[3]++ + " show on Wednesday.");
}else if("thursday".equalsIgnoreCase(showDay)){
showdayCount[4]++;
System.out.println("There are/is " + showdayCount[4]++ + " show on Thursday.");
}else if("friday".equalsIgnoreCase(showDay)){
showdayCount[5]++;
System.out.println("There are/is " + showdayCount[5]++ + " show on Friday.");
}else if("saturday".equalsIgnoreCase(showDay)){
showdayCount[6]++;
System.out.println("There are/is " + showdayCount[6]++ + " show on Saturday.");
}
This is also only giving me one line. What am I doing wrong?! :(
EDIT:
What I want is to input name/day/time of a TV show, then later be able to display the amount of shows that are on that specific day!
For example, Big Bang Theory and Community are both on Thursday. So the code would output something like
There are 2 shows on Thursday.
Nothing's worked, so far.

You only get one day from this line:
String showDay = ((showInfo)show.get(0)).day.toString();
Here's my hack solution (may have some errors, like a misnamed variable but you should be able to fix it):
//Create a map that maps days to the shows that are on that day
LinkedHashMap showDays=new LinkedHashMap(); //String to Set map
String[] days={"Sunday","Monday", ....};//put the rest of the days in here
for(int dayIndex=0;dayIndex<days.length;dayIndex++){
String day=days[dayIndex];
showDays.put(day,new HashSet());
}
//iterate through the shows and put them in their respective days in the map
for (int i = 0; i < show.size(); i++) {
String dayForShow=((showInfo)show.get(i)).day.toString();
showDays.get(dayForShow).put(show.get(i));
}
//now print out how many shows are on each day
for(int dayIndex=0;dayIndex<days.length;dayIndex++){
String day=days[dayIndex];
int showsToday=showDays.get(day).size();
///do your print out now
}
You can make 'LinkedHashMap showDays' a class variable and add to it each time you add to show (and remove from it each time you remove from show).
PS. Tell your teacher it is no longer 2002, technology moves on and they make my job harder.

Create a Show class
public class Show {
String showName;
String showDay;
int showTime;
static int[] showdayCount = new int[7];
public Show(String showName, String, showDay, iny showTime){
this.showName = showName;
this.showDay = showDay;
this.showTime = showTime;
// increment showDayCOunt[] according to showDay from
switch(showDay){
case "Sunday": showDayCount[0]++; break;
case "Monday": showDayCount[1]++; break;
case "Tuesday": showDayCount[2]++; break;
case "Wednesday": showDayCount[3]++; break;
case "Thursday": showDayCount[4]++; break;
case "Friday": showDayCount[5]++; break;
case "Saturday": showDayCount[6]++; break;
}
}
}
Here's your main method from YourClass
public static void main(String[] args){
// Create Array of Shows
Show[] shosList = new Show[4]; // or how many ever shows you have
// Get your inputs for showName, showDay, showTime
Sting showName =
String showDay =
int showTime =
// Create show Object
Show show = new Show(showName, showDate, showTime);
// add show to ArrayList
showList[someIndex] = show;
// Do all other stuff then print
// when you print, you can get the showDayCount directly from the Show class
}
Now I don't want to do everything for you. I just want to get you headed in the right direction. Note that if you want the above to happen more than once, consider putting inside of a loop.
Edit: With getShowdayCount
Add this to my above Show class
public int getShowdayCount(String showday){
switch(showDay){
case "Sunday": return showDayCount[0]; break;
case "Monday": return showDayCount[1]; break;
case "Tuesday": return showDayCount[2]++; break;
case "Wednesday": return showDayCount[3]++; break;
case "Thursday": return showDayCount[4]++; break;
case "Friday": return showDayCount[5]++; break;
case "Saturday": return showDayCount[6]++; break;
}
}
Edit: With example if/else if from switch statement
// for main method inputs
if ("sunday"equalsIgnoreCase(showDay){
showdayCount[0]++
} else ("monday".equalsIgnoreCase(showDay){
showdayCount[1]++
} // finish if/else if statement
// for getShowdayCount method
if ("sunday"equalsIgnoreCase(showDay){
return showdayCount[0];
} else ("monday".equalsIgnoreCase(showDay){
return showdayCount[1];
} // finish if/else if statement
You can call it from your main class like this
show.getShowdayCount(show.showday);
Edit: Actually, Just put the above edit in you class with the main method
YourClassWithMainMethod{
static int[] showdayCount = new int[7];
public static void mina(String[] args){
// call getShowdayCount here
getShowdayCount(String showday);
}
public static int getShowdayCount(String showday){
}
}
Edit: What you do want and what you don't want
You dont need this in you if statement
System.out.println("There are/is " + showdayCount[5]++ + " show on Friday.");
When you want to print all the shows:
for (int i = 0; i < showdayCount.length; i++){
int showday;
if (i == 0){
showday = "Sunday
finish the if/else if statements
}
System.out.println("There is " + showDayCount[i] + " shows on " + showday);
}

Related

Trying to work off and input by the user to change a value

I am creating a small game-type program,
Firstly I'm asking the user to give his name,
Secondly, I'm asking the user to choose one of the spaceships,
Thirdly, I want the user to add 2 modification, to improve the stats...
Here is the problem, I want to change some values of the spaceship.
The problem is that I don't know how to determine the chosen spaceship and how to change its values. Example: The Heavy-type Armour is 90 right now​ if I add the Advanced Hull Armour modification, i want it to increase to 100
public class Game {
static void playerName() {
System.out.println("What's your name?:");
String name = Keyboard.readString();
System.out.println("Okay,"+name+" it is!\n");
}
static class StarShip {
String name;
String armour;
String attack;
String mobility;
}
public static void main (String args[]) {
System.out.println("Hello Rookie! \n");
playerName();
System.out.println("Let's pick your first ship!\n");
System.out.println("Choose one of these:");
//insert ships here:
StarShip ship1 = new StarShip();
ship1.name = "Heavy-type";
ship1.armour = "Armour=90";
ship1.attack = "Firepower=50";
ship1.mobility = "Mobility=40";
StarShip ship2 = new StarShip();
ship2.name = "Medium-type";
ship2.armour = "Armour=60";
ship2.attack = "Firepower=60";
ship2.mobility = "Mobility=60";
StarShip ship3 = new StarShip();
ship3.name = "Light-type";
ship3.armour = "Armour=20";
ship3.attack = "Firepower=60";
ship3.mobility = "Mobility=90";
System.out.println("1 -"+ship1.name+"- "+ship1.armour+" "+ship1.attack+" "+ship1.mobility);
System.out.println("2 -"+ship2.name+"- "+ship2.armour+" "+ship2.attack+" "+ship2.mobility);
System.out.println("3 -"+ship3.name+"- "+ship3.armour+" "+ship3.attack+" "+ship3.mobility);
int chosen = Keyboard.readInt();
switch (chosen) {
case 1:
System.out.println("Heavy-type! Excellent choice! Great armour and guns! \n");
break;
case 2:
System.out.println("Medium-type! An all-rounder, a mix of everything! \n");
break;
case 3:
System.out.println("Light-type! Fast and mobile, but has little armour! \n");
break;
}
System.out.println("Lets pimp out your ship! \n");
String advancedHull = "1 - Advanced Hull Armour - Armour +10";
String betterAmmo = "2 - Better Ammo \t - Firepower +10";
String booster = "3 - Booster \t\t - Mobility +10";
System.out.println(advancedHull+"\n"+betterAmmo+"\n"+booster);
}
}
Currently you the fields of the StarShip are all Strings, when you add two strings they are concatenated, eg "abc"+"def" = "abcdef" regardless of what they say. You want to use ints these are "java numbers" and add as you would expect eg 10 + 20 = 30
class StarShip {
String name;
int armour;
int attack;
int mobility;
}
...
StarShip ship1 = new StarShip();
ship1.name = "Heavy-type";
ship1.armour = 90;
ship1.attack = 50;
ship1.mobility = 40;
...
When the user selects the ship we want to save this chose into a variable, like so:
Starship chosenShip; // must be declared outside the switch statement
switch (shipChoice ) {
case 1:
System.out.println("Heavy-type! Excellent choice! Great armour and guns! \n");
chosenShip = ship1;
Break;
...
Assuming advancedHull is selected and you include logic similar to how ships are selected
if (modificationChoice = 1){
chosenShip.armour = chosenShip.armour + 10;
} ...
You may want to declare a toSting() methods in StarShip like so
#Override
public String toString() {
return name +" Armour=" + armour +", Firepower=" + attack +", Mobility=" + mobility;
}
This way you can call System.out.println(ship1.toString()) to print the ship info.
Example:
System.out.println(ship1.toString());
// outputs: Heavy-type Armour=90, Firepower=50, Mobility=40
ship1.armour += 10; // java shorthand for `ship1.armour + ship1.armour + 10`
System.out.println(ship1.toString());
// outputs: Heavy-type Armour=100, Firepower=50, Mobility=40

Text based survival Game

So I just whipped up this quick little demo game in like 30 minutes and I was wondering 2 things:
How could I organize my code more?
Would you be willing to play a game like this?
I know that I could use classes but I'm a bit inexperienced them. I'm confused on how to get variables from specific classes. Would I need to import them into the main method class?
import java.util.Scanner;
public class mainGame
{
public static Scanner kboard = new Scanner(System.in);
public static boolean loop = true;
public static int treesInArea = 0;
public static int day = 0;
public static int wood = 0;
public static int woodCollected = 0;
public static int woodLevel = 0;
public static void main(String[] args)
{
System.out.println("__________________________________");
System.out.println(" Welcome to seul...Lets begin ");
System.out.println(" You woke up in the middle of ");
System.out.println(" a forest. Use the command walk ");
System.out.println(" in order to walk into a new area ");
System.out.println("__________________________________\n");
while(loop == true)
{
String choice = kboard.nextLine();
if(choice.equalsIgnoreCase("walk"))
{
treesInArea = (int)(Math.random() * 20);
System.out.println("__________________________________");
System.out.println("The number of trees in this area is");
System.out.println(treesInArea + " trees");
System.out.println("__________________________________\n");
day++;
System.out.println(" It is day " + day + " ");
System.out.println("__________________________________\n");
System.out.println(" Current usuable commands are : ");
System.out.println(" - Chop tree\n");
} else
if(choice.equalsIgnoreCase("choptree") || choice.equalsIgnoreCase("chop tree"))
{
if(treesInArea < 1)
{
System.out.println("There are no trees in this area.");
} else
{
woodCollected = (int)(Math.random() * 10);
treesInArea --;
wood += woodCollected;
woodLevel += (int)(Math.random() * 2);
System.out.println("__________________________________");
System.out.println(" You collected " + woodCollected + " wood");
System.out.println(" Your total wood = " + wood);
System.out.println(" Your total woodcutting level = " + woodLevel);
System.out.println("__________________________________\n");
}
}
}
}
}
You could improve your code in 4 main ways:
1 • Your code-indentation is not great, it should be a 4 space(or just press tab) indent after class name, loops, if statements etc. Example:
private methodName() {
for(int i = 0; i < 10; i++;) {
//do something
}
}
2 • It is easier to read your code when braces are right after methods/loops, and it takes less space, such as(5 lines of neat code):
if (condition = true) {
//do something
} else {
//do something else
}
Rather than(7 lines of messy code):
if (condition = true)
{
//do something
} else
{
//do something else
}
because when you have long if-else blocks, or long loops, it can become hard to read.
3 • You do not need to add spaces after a line, this does nothing. So this:
System.out.println(" It is day " + day + " ");
Can become this:
System.out.println(" It is day " + day);
4 • Lastly, the best way to organize code is by "dividing and conquering". This means make methods even if they're very short, to prevent repeat-code and save time. For example, you printed this line: System.out.println("__________________________________"); 7 times in your program. If you make a method like the one below, you can save time and space, by avoiding repeat-code, and simply call the method using printDivider(); wherever you used this line:
private static void printDivider() {
System.out.println("__________________________________");
}
Yes, I would play your game(in fact i did play your game), but you could improve it, by adding more possibilities, or different 'paths' to go down, ending in different results.

Java: removing word from a list

I am currently working on making a vocable test were you can make your own vocables and their translation. I have faced a problem were I do not know how to make an option were you have different translations to pick from.
public static void WritingYourVocables(List<VocableList> data) {
String antal = JOptionPane.showInputDialog(null, "Write the numbers of vocables you want to have");
int temp = Integer.parseInt(antal);
for (int i = 0; i < temp; i++) {
String Vocable = JOptionPane.showInputDialog(null, "Write a vocable");
String Translation = JOptionPane.showInputDialog(null, "Write the translation for the vocable");
data.add(new VocableTest(Vocable, Translation));
}
}//WritingYourVocables ends
The method above is the the method were you write the numbers of vocables you want to have in your test, then you write your vocables and their translation.
public static void PlayWithAlternatives(List<Alternatives> data) {
int a = data.size();
for (int n = 0; n < a; n++) {
int Translate2;
int Translate3;
int Translate1 = (int)(Math.random() * data.size()) ;
do {
Translate2 = (int)(Math.random() * data.size()) ;
}while (Translate1 == Translate2);
do{
Translate3 = (int)(Math.random() * data.size()) ;
}while (Translate1 == Translate3 || Translate2 == Translate3);
int answer [] = {Translate1, Translate2, Translate3};
int Right = (int)(Math.random() * 3) ;
int choice = Integer.parseInt(JOptionPane.showInputDialog(null, "What is the translation of the vocable? " +
data.get(answer[Right]).getVocable() +
"\n1: " + data.get(Translate1).getTranslation() +
"\n2: " + data.get(Translate2).getTranslation() +
"\n3: " + data.get(Translate3).getTranslation()));
switch(choice){
case 1:
if (answer[Right] == Translate1){
data.remove(?);
JOptionPane.showMessageDialog(null, "Right");
}else{ JOptionPane.showMessageDialog(null, "Wrong");
}
break;
case 2:
if (answer[Right] == Translate2){
data.remove(?);
JOptionPane.showMessageDialog(null, "Right");
}else{ JOptionPane.showMessageDialog(null, "Wring");
}
break;
case 3:
if (answer[Right] == Translate3){
data.remove(?);
JOptionPane.showMessageDialog(null, "Right");
}else{ JOptionPane.showMessageDialog(null, "Wrong");
}
break;
default:
JOptionPane.showMessageDialog( null, "Wrong choice!");
}
}
}//PlayingWithAlternatives ends
The method above is a method for playing with different alternatives to the translation for a random generated vocable. If the player picks the right alternative, the vocable that the alternative is connected with is supposed to be deleted. To remove the vocable I use "data.remove()", the problem is that I do not know what to write in the brackets to remove the vocable.
Please help
There are better ways to handle your design but as far as your question is concerned just remove the vocable you asked in the first place.
data.remove(answer[Right]);
Remove elements from ArrayList :
You use :
arrlist.remove(index);
The parameter of List.remove is either the index of the thing you want to remove, or the object you want to remove.
It looks like Translate1, Translate2 and Translate3 are indexes into the list - so call
data.remove(Translate1); // or whichever variable is correct.
You can make life easier for yourself if you put your TranslateN variables in an array:
int[] Translate = new int[3];
So, replace every occurrence of Translate1 with Translate[0], Translate2 with Translate[1] etc.
Then, instead of the switch with almost identical handling of the 3 cases, you can simply use:
if (answer[Right] == Translate[choice-1]){
data.remove(Translate[choice-1]);
JOptionPane.showMessageDialog(null, "Right");
} else {
JOptionPane.showMessageDialog(null, "Wrong");
}
You should also watch out for the infinite loop in the code, when you have fewer than 3 choices left: you can't pick 3 different values for the Translate variables if there are only 2 possible values.

Need to start again at a certain point in java

I'm really new to java, and just programming in general. I am trying to make a simple "story game".
I want the program to start again where I commented "starting again point if walk.equals("b") (second time)"
Here is my code:
P.S. sorry if it is poorly written
import java.util.*;
public class leikur1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("|---------Welcome to the adventure------------|");
System.out.println("Please enter Name"); // inputs name
String nafn = scan.nextLine();
nafn = nafn.toLowerCase();
System.out.println("Gender, male or female");
String kyn = scan.nextLine();
kyn = kyn.toLowerCase();
while((!kyn.equals("male")) && (!kyn.equals("female")) ) //bara haegt ad velja male eda female
{
System.out.println("That is not valid input" );
kyn = scan.nextLine();
kyn = kyn.toLowerCase();
}
System.out.println("Are you ready for the adventure");
String leikur = scan.nextLine();
leikur = leikur.toLowerCase();
while((!leikur.equals("yes")) && (!leikur.equals("no")) ) //impossible to input something else than male or female
{
System.out.println("That is not valid input" );
leikur = scan.nextLine();
leikur = leikur.toLowerCase();
}
if(leikur.equals("no"))
{
System.out.println("Thank you anyway"); //if input = no program ends
}
// if input = yes the game begins
else
{
System.out.println("Write Start to begin or Quit to exit");
String start = scan.nextLine();
start = start.toLowerCase();
String gender;
if(kyn.equals("male"))
{
gender = "he";
}
else
{
gender = "she";
}
while((!start.equals("start")) && (!start.equals("quit")) )
{
System.out.println("That is not valid input" );
start = scan.nextLine();
start = start.toLowerCase();
}
if(start.equals("start"))
{
System.out.println("Walking instructions: left - l right - r forward - f back - b down - d up - u\n");
System.out.println(nafn + " is in a abandoned house late at night, stuck in the basement with no light.\n");
System.out.println("In wich way should " + gender + " go to find his way to the stairs?" ); **// starting again point if walk.equals("b") (second time)**
String walk = scan.nextLine();
walk = walk.toLowerCase();
//////////
while((!walk.equals("f")) && (!walk.equals("b")) ) // not possible bcus of walls or no stairs
{
System.out.println("That is not possible" );
walk = scan.nextLine();
}
if(walk.equals("f"))
{
System.out.println("Great choice, " + gender + " found the stairs right away. Should"+gender+" go upstairs or go back?" );
}
else if (walk.equals("b"))
{
System.out.println("Oh boy! " + nafn +" got stuck in a beartrap and died... GAME OVER" );
}
/////////
walk = scan.nextLine();
while(!walk.equals("u") && !walk.equals("b") )
{
System.out.println("That is not possible" );
walk = scan.nextLine();
}
if(walk.equals("u"))
{
System.out.println("Excelent!" + nafn + " is now upstairs" );
}
**else if(walk.equals("b") )
{
System.out.println("Now " + nafn + " is at stage 1 again" );
}**
//////////////
// code 4 the game should be here above
}
else if(start.equals("quit"))
{
System.out.println("Thank you anyway");
}
}
}
}
If you just want to repeat your content, a while loop is sufficient
boolean continue = true;
while(continue)
{
else if(walk.equals("b") )
{
System.out.println("Now " + nafn + " is at stage 1 again" );
continue = true;
}
else if(start.equals("quit"))
{
System.out.println("Thank you anyway");
continue = false;
}
}
the reason I'm using the variable continue is to better illustrate the while loop. you can also use while(true), which will normally loop forever. to skip to the beginning of the next iteration you use continue; and to break out, you can use break
while(true)
{
else if(walk.equals("b") )
{
System.out.println("Now " + nafn + " is at stage 1 again" );
continue;
}
else if(start.equals("quit"))
{
System.out.println("Thank you anyway");
break;
}
}
If you really wanted to take your coding to the next level, you could take a more data-driven approach, and have a data model to define your game. The following is a sample data model in xml
<Places>
<Place name="YourRoom" text="You are in your room. Where would you like to go?">
<Option text="Enter the hallway." result="Hallway"></Option>
</Place>
<Place name="Hallway" text="You are in the hallway. Where would you like to go?">
<Option text="Go to your room" result="YourRoom"></Option>
</Place>
</Places>
And then you'd write your program something like this
pseudocode:
xmlElement currentRoom = // get starting element
while(true)
{
print(currentRoom.Attributes[text])
for(int i=0; i<currentRoom.Elements.length; i++)
{
print(currentRoom.Elements[i] + "type " + i+1;
}
int choice = getInt();
int result = currentRoom.Elements[choice].result;
currentRoom GetElementWithName(result);
}
You should rather learn Java, OOP and other base constructs. If you really insist, you can use labels (to be honest since the advent of structured programming, in the sixties people try not to use GOTO anymore... but if you want to fail a job interview go ahead ;-) )
// ...
// label is your label, you can use any text
label:{
// ...
// here is your GOTO
break label;
}
Side note : it works like a charm, but please don't do it (or at least don't say I'm the one who told you about labels) !

First, last and sometime middle name detection Java

I am trying to write a code to give off the user's name in different formats after they enter it. However, if a user does not have a middle name, the system should print that there was an error. I have it so it works perfectly if the user enters three names but does not work if the user enters two names. Here is my code:
import java.util.Scanner;
public class Assignment3
{
public static void main(String[] args)
{
String fullName;
Scanner in = new Scanner(System.in);
System.out.print ("What are your first, middle, and last names? ");
fullName = in.nextLine();
System.out.println(fullName);
if (fullName.contains(" "))
{
String[] nameParts = fullName.split(" ");
String firstInitial = nameParts[0].substring(0,1).toUpperCase();
String secondInitial = nameParts[1].substring(0,1).toUpperCase();
String thirdInitial = nameParts[2].substring(0,1).toUpperCase();
if (nameParts[2].isEmpty())
{
System.out.println("No Middle Name Detected");
}
else
{
System.out.println ("Your initials are: " + firstInitial + secondInitial + thirdInitial);
String lastVariationOne = nameParts[2].substring(0, nameParts[2].length());
lastVariationOne = lastVariationOne.toUpperCase();
String firstVariationOne = nameParts[0].substring(0, nameParts[0].length());
firstVariationOne = firstVariationOne.substring(0,1).toUpperCase() + firstVariationOne.substring(1, nameParts[0].length());
System.out.println("Variation One: " + lastVariationOne + ", " + firstVariationOne + " " + secondInitial + ".");
String lastVariationTwo = nameParts[2].substring(0, nameParts[2].length());
lastVariationTwo = lastVariationTwo.substring(0,1).toUpperCase() + lastVariationTwo.substring(1, nameParts[2].length());
System.out.println("Variation Two: " + lastVariationTwo + ", " + firstVariationOne);
}
}
else
{
System.out.println("Wrong. Please enter your name properly.");
}
}
}
Instead of this:
if (nameParts[2].isEmpty())
{
System.out.println("No Middle Name Detected");
}
something like
if(nameParts.length != 3)
{
System.out.println("Invalid entry");
}
might be preferrable.
Basically, in the case that there are only two names entered, split() will return an array of length 2, whose elements are accessible by indices 0 and 1.
But in your if condition you attempt to access index 2, which could be out of bounds (it would be OOB for the case where you entered only two names).
To resolve this, you could either (a) try it like you do, but catch the ArrayIndexOutOfBoundsException or (b) check first that split produced a properly sized array, then go from there (this was the approach I took with the change I listed).
I'd suggest (b), but both approaches seem fine.
If you don't input middlename, would the array size be 2?
So there is NO namespart[2].
Just check size of namespart.
#jedwards jedwards's solution is there.

Categories

Resources