In Java, write the following program: You are writing a Nethack-style text-based
ID: 3877749 • Letter: I
Question
In Java, write the following program:
You are writing a Nethack-style text-based role-playing game that supports saving the game's current state to a text file. You decide to represent items in your character's inventory using certain symbols in the file: + weapon @ potion * dark chocolate bar (Your character is magically prevented from carrying milk chocolate bars.) Write a method that takes a string as a parameter and returns an array containing the quantity of weapons, potions, and dark chocolate bars in that order. You can assume that the input string contains only the three characters above. Required method header: public static int [] countItems (String s) Example input and output: Input: "@@+**+@***" Output: {2, 3, 5}Explanation / Answer
public static int[] countItems(String s){
int len = s.length(); // Find string length
int res[] = new int[3]; // Array which stores occurence count in same order
for(int i=0;i<len;i++){
if( s.charAt(i) == '+'){ // Traverse the string character by character
res[0]++;
}else if( s.charAt(i) == '@'){
res[1]++;
}else
res[2]++;
}
return res;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.