This is my code so far:
public class CustomerListerArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
//creating the array
String[] customerName = new String [7];
customerName[0] = "Beth";
customerName[1] = "Jerry";
customerName[2] = "Rick";
customerName[3] = "Summer";
customerName[4] = "Morty";
// first loop/test
for(String x : customerName) {
System.out.println(x);
}
System.out.println(" ");
//second loop/test
customerName[5] = customerName[3];
customerName[6] = customerName[4];
customerName[3] = "Rick";
customerName[4] = "Jessica";
for(String x : customerName) {
System.out.println(x);
}
System.out.println(" ");
//third loop/test
int i = 0;
int p = 0;
for(String x : customerName) {
for(i = 0; i < customerName.length - 1; ++i) {
if((customerName[i] == "Rick")){
for (p = i; p < customerName.length; ++p){
customerName[i] = customerName[i +1];
}
}
}
System.out.println(x);
}
System.out.println(" ");
}
}
In the third loop test, I am trying to take the "Rick"s from the array, delete them and move the remaining elements up. The output should be this:
"Beth
Jerry
Jessica
Summer
Morty"
Right now, the program outputs this:
"Beth
Jerry
Rick
Summer
Morty
null
null
Beth
Jerry
Rick
Rick
Jessica
Summer
Morty
Beth
Jerry
Jessica
Jessica
Jessica
Summer
Morty"
I don't understand why three "Jessica"s are printing at the end. Any help would be appreciated!
FIRST OF ALL -- doing customerName[i] == "Rick" is a classic newbie mistake; whatever it looks like, it does NOT tell you whether that value is "Rick" (unless you've done some special things we won't go into). It will tell you whether the object at customerName[i] is the same object as your literal "Rick", which isn't likely in a production environment. You need the equals() method of the String class; look it up and remember this. For example, if (customerName[i].equals("Rick")).
Read this for more information: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
As for Jessica, if you move that value from [i] to [j], then she is still in [i]; if you want to "remove" jessica, you should set the value at [i] to something else.
Try this.
private static void output() {
String[] str_array = {"Beth", "Jerry", "Rick", "Summer", "Morty"};
List<String> list = new ArrayList<>(Arrays.asList(str_array));
list.remove("Rick");
str_array = list.toArray(new String[0]);
for (String x : str_array) {
System.out.println(x);
}
}
Please remember to import the appropriate API's above your class declaration.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
I was recently trying to build a program that takes two inputs and checks whether they are equally represented in other bases(bases are up till 20). But i keep getting the index out of bounds exception at line number 28...what to do?
For example: 12(base 10) = 5(base 3) [both are represented as '12' in their respective bases.]
import java.util.Scanner;
import java.util.Arrays;
class Bases
{
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Two Numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("Thank You for inputting the numbers!");
String basea[] = new String[20];
String baseb[] = new String[20];
int i=0 , j=0;
for( i=0;i<20;i++)
{
basea[i] = convert(a,i+1);
baseb[i] = convert(b,i+1);
}
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++)
{
if(basea[i].equals(baseb[j]))
{//this is where the exception keeps popping
break ;
}
}
}
if(i!=20){
if(i==0){
i=9;
System.out.println(a+"(base "+(i+1)+") ="+b+"(base "+(j+1)+")");
}
else
System.out.println(a+"(base "+(i+1)+") ="+b+"(base "+(j+1)+")");
}
else System.out.println("Numbers dont match at all till base 20!!");
}
private static String convert(int number,int base)
{
return Integer.toString(number,base);
}
}
for(j=0;i<=19;j++)
This above loop should be j <= 19
for(j=0;j<=19;j++)
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++)
{
if(basea[i].equals(baseb[j]))
{//this is where the exception keeps popping
break ;
}
}
}
You can see in this original snippet of code you had a typo
for(i=0;i<=19;i++)
{
for(j=0;i<=19;j++) <---- the middle parameter is 'i' instead of 'j'
{
Simply fix this by fixing your typo, and if you want to you can make it <20 for some added neatness.
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{
I'm making a card game, and I've arrived at the shufflin' time.
I've to shuffle a few cards (that are chosen before from the user, so they're not always the same amount) and then display them to the user one by one.
As I'm still developing the game's logic I'm displaying cards' name by changing a button text.
But I get stuck when I try to get the cards' name and set them as the button's text.
What happens is me gettin' a blank button or just with "Masons" or "Villager" String. Infact if I check the log I see that all the others cards(characters) get displayed as "null".
This is how I tried to achieve the goal (Yes I'm a newbie):
This is the head:
int demoniac;
int guard;
int masons;
int medium;
int mythomaniac;
int owl;
int villager;
int werehamster;
int all;
int i;
int t;
String[] characters = new String[24];
Button randomButton;
My method to addAll the cards(characters):
public void addAll(){
for(i = 0; i < all; i++){
add(demoniac, "Demoniac");
add(guard, "Guard");
add(medium, "Medium");
add(mythomaniac, "Mythomaniac");
add(owl, "Owl");
add(werehamster, "Werehamster");
add(villager, "Villager");
add(masons, "Masons");
}
}
My method to add and manage the various types of cards(characters):
public int add(int character, String name){
if(character != 0 && name == "Villager"){
for(t = 0; t < character; t++){
i+=t;
characters[i] = name;}
}
else if(character == 2 && name == "Masons"){
characters[i] = name;
i++;
characters[i] = name;
Toast.makeText(randomSelection.this, "works", Toast.LENGTH_SHORT).show();
}else if(character != 0){
characters[i] = name;
}
return i;
}
To randomize:
public void randomize(){
Collections.shuffle(Arrays.asList(characters));
for (int s = 1; s < characters.length; s++)
{
System.out.println(characters[s]);
}
}
The method to display a different card(character) each time the user clicks the button:
public void show(View view){
for (int s = 1; s < characters.length; s++)
{
randomButton.setText(characters[s]);
}
}
EDIT:
I've noticed the no sense for loop I've done, by the way you should know although most of the characters are only 1 of their kind (demoniac, guard, etc..) there are 2 Masons and from 5 to 12 Villagers, so We need to retrieve these ints and add as much Strings to the Array as much we're told from those ints.
Example: If I get 6 Villagers, I've to add the String "Villager" 6 times into the String Array.
Then I've set that s value to 1 'cause I've to display the first
String ([0]) as soon as the Activity gets started, so on the OnCreate() method.
Maybe I'm wrong, if so I please you to correct me!
Getting a blank button or just with "Masons" or "Villager" String
That is because you only set the Button's text with the last element of the list. Which is either null or "Masons" (not seeing how it could be "Villager").
for (int s = 1; s < characters.length; s++)
{
randomButton.setText(characters[s]);
}
If I check the log I see that all the others cards(characters) get displayed as "null"
You only set position 0 of your array. For example, you don't initialize the positions, so these int values default to 0.
int demoniac;
int guard;
int all;
Then
for(i = 0; i < all; i++){
add(demoniac, "Demoniac");
add(guard, "Guard");
Really, that loop shouldn't be entered because all equals 0.
Additionally
Collections are zero-indexed, so this doesn't print element 0. You need to set int s = 0;.
for (int s = 1; s < characters.length; s++)
It isn't clear to me what the add(int character, String name) method is returning, but if you explain it, I will update this answer.
I believe this code fulfills most of what you are trying to achieve
// Where the characters are stored
private ArrayList<String> characters;
public void initDeck() {
if (characters == null)
characters = new ArrayList<String>();
// Extract the numbers if you actually need them, otherwise, they just are constants
addCharacter("Demoniac", 1, characters);
addCharacter("Guard", 1, characters);
addCharacter("Medium", 1, characters);
addCharacter("Mythomaniac", 1, characters);
addCharacter("Owl", 1, characters);
addCharacter("Werehamster", 1, characters);
addCharacter("Villager", 5, characters);
addCharacter("Masons", 1, characters);
}
public void addCharacter(String name, int amount, ArrayList<String> cards) {
if (amount < 0) {
throw new IllegalArgumentException("Must add a non-negative number of characters for " + name);
}
// Don't use '==' for Strings
if (name.equals("Villager")) {
if (amount != 5 || amount != 12) {
throw new IllegalArgumentException("There can only be 5 or 12 " + name);
}
}
for (int i = 0; i < amount; i++) {
cards.add(name);
}
}
public int searchCharacters(String character, ArrayList<String> cards) {
return cards.indexOf(character);
}
public Map<String, Integer> getAllCharacterPositions() {
Map<String, Integer> allPositions = new LinkedHashMap<String, Integer>();
for (int i = 0; i < characters.size(); i++) {
allPositions.put(characters.get(i), i);
}
return allPositions;
}
void run() {
// initialize the characters
initDeck();
// shuffle them
Collections.shuffle(characters);
// print them all out
for (int i = 0; i < characters.size(); i++) {
System.out.printf("%d: %s\n", i, characters.get(i));
}
// Find the position of a character
System.out.println();
String findCharacter = "Owl";
// Option 1 -- always linear search lookup
System.out.printf("%d: %s\n", searchCharacters(findCharacter, characters), findCharacter);
// Option 2 -- one-time linear scan, constant lookup
Map<String, Integer> positions = getAllCharacterPositions();
System.out.printf("%d: %s\n", positions.get(findCharacter), findCharacter);
// Get a random character
System.out.println();
Random rand = new Random(System.currentTimeMillis());
int randPos = rand.nextInt(characters.size());
System.out.printf("%d: %s\n", randPos, characters.get(randPos));
// randomButton.setText(characters.get(randPos));
}
Given the array is already shuffled, just look at the first card:
public void show(View view){
randomButton.setText(characters[0]);
}
If you want to navigate that deck I suggest you put the shuffled list in to a Queue, where you can look at the next card (peek) or take the next card (poll):
private static Queue<string> buildNewShuffledDeck(String[] characters){
List<String> shuffledCharacterList = new ArrayList<String>(characters);
Collections.shuffle(shuffledCharacterList);
Queue<string> deck = new ArrayDeque(shuffledCharacterList);
return deck;
}
public void show(View view){
String nextCard = deck.peek();
if (nextCard != null)
randomButton.setText(nextCard);
else
//deck is empty...
}
Then to take from the deck, say on the random button click:
String nextCard = deck.poll();
General advice on arrays: Stop using them in favor of other data types that are far more useful and interchangeable.
Then next step advice, make a class that represents a Card and stop using Strings, the string you currently have is just one property of a card.
You are just displaying the last character name that you add
Replace with this
public void show(View view){
Random r = new Random(System.currentTimeMillis());
randomButton.setText(characters[r.nexInt(characters.length)])
}
I am trying to add marker New direction to the arrayList mergeArray when I found the second 3 value in the buffer arrayList but I am always getting the first 3 value in the ArrayList. How can I get the second one after Amsterdam?
I appreciate any help.
output:
paris
3
water
ball
money
Amsterdam
3
door
output should looks like this:
paris
3
water
ball
money
New direction
Amsterdam
3
door
Code:
public static void main(String[] args) {
ArrayList<String> buffer = new ArrayList<String>();
ArrayList<String> mergeArray = new ArrayList<String>();
String route = "3";
String direction = "paris";
String start = "Amsterdam";
buffer.add("paris");
buffer.add("3");
buffer.add("water");
buffer.add("ball");
buffer.add("money");
buffer.add("Amsterdam");
buffer.add("3");
buffer.add("door");
for (String line : buffer) {
if (line.equals(route)) {
mergeArray.add(line);
int index = buffer.indexOf(line);
String prevElement = buffer.get(index - 1);
if (prevElement == direction) {
String addElem = buffer.get(index + 1);
mergeArray.add(addElem);
} else if (prevElement == start) {
mergeArray.add("New direction");
}
}
}
for (String key : mergeArray) {
System.out.println(key);
}
}
Do not use indexOf as it will always retrieve the index of the first appearance.
Keep an auxiliary index variable and use it in your loop:
int auxIndex = 0;
for (String line : buffer) {
if (line.equals(route)) {
mergeArray.add(line);
String prevElement = buffer.get(auxIndex - 1);
if (prevElement.equals(direction)) {
String addElem = buffer.get(auxIndex + 1);
mergeArray.add(addElem);
} else if (prevElement.equals(start)) {
mergeArray.add("New direction");
}
}
auxIndex++
}
also add safety checks so the index will not under/over-flow
Try using a clasic for, instead of one that uses Iterable
for (int i=0; i<buffer.size(); i++) {
String line = buffer.get(i);
if (line.equals(route)) {
mergeArray.add(line);
String prevElement = buffer.get(i - 1);
if (prevElement == direction) {
String addElem = buffer.get(i + 1);
mergeArray.add(addElem);
} else if (prevElement == start) {
mergeArray.add("New direction");
}
}
}
Also, consider checking for over/underflow problems. You refer to index-1 and index+1, which will cause trouble if the appearance is on the first or last position.
So I need to compare two different ArrayLists elements. If the element from the first ArrayList(tweets) does not match any from the second(hashTags) I want to add the element(from tweets) to the second ArrayList(hashTags)
Here is my code thus far:
package edu.bsu.cs121.albeaver;
import java.util.*;
public class HashTagCounter {
public static void main(String args[]) {
System.out
.println("Please tweet your tweets,and type 'done' when you are done.");
Scanner twitterInput = new Scanner(System.in);
ArrayList<String> tweets = new ArrayList<String>();
ArrayList<String> hashTags = new ArrayList<String>();
while (true) {
String tweet = twitterInput.next();
tweets.add(tweet);
if ("done".equals(tweet))
break;
}
System.out.println(tweets);
twitterInput.close();
int count = 0;
for (String tweet : tweets) {
if (tweet.contains("#") && count == 0) {
hashTags.add(tweet);
hashTags.add(1, "");
count++;
} else if (tweet.contains("#")) {
for (String hashTagged : hashTags) {
if (tweet.equalsIgnoreCase(hashTagged) != true) {
hashTags.add(hashTagged);
}
}
}
}
System.out.println(hashTags);
System.out.println("Number of unique '#' used is: "
+ (hashTags.size() - 1));
}
}
(edit)I seem to get a 'java.util.ConcurrentModificationException' error.
Thank you for any and all help:)
for (String hashTagged : hashTags) {
if (tweet.equalsIgnoreCase(hashTagged) != true) {
hashTags.add(hashTagged);
-----------------------------^
}
}
The issue is while iterating the hashTags list you cant update it.
You are getting java.util.ConcurrentModificationException because you are modifying the List hashTags while you are iterating over it.
for (String hashTagged : hashTags) {
if (tweet.equalsIgnoreCase(hashTagged) != true) {
hashTags.add(hashTagged);
}
}
You can create a temporary list of items that must be removed or improve your logic.