我希望用户能够点击应用程序的按钮并从FactBook.java的列表中获取随机事实(String)。我通过调用initFacts()方法(静态)首次打开应用程序时初始化列表,然后每次用户点击按钮(如果列表为空)时进行检查。如果是,我必须重新初始化列表,以便它不会保持为空。但是,当我点击按钮时应用程序崩溃,但我找不到错误,一切似乎都适合我。有人能帮我吗?提前谢谢。
package com.spdesigns.funfacts;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.Random;
public class FunFactsActivity extends AppCompatActivity {
//private FactBook factBook = new FactBook();
private ColorWheel colorWheel = new ColorWheel();
// Declare our View vars
private RelativeLayout relativeLayout;
private TextView factTextView;
private Button showFactButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fun_facts);
// Assign the Views from the layout file to the corresponding variables
relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
factTextView = (TextView) findViewById(R.id.factTextView);
showFactButton = (Button) findViewById(R.id.showFactButton);
FactBook.initFacts();
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
// Update the screen with our new fact
int color = colorWheel.getColor();
relativeLayout.setBackgroundColor(color);
showFactButton.setTextColor(color);
factTextView.setText(FactBook.getFact());
}
};
showFactButton.setOnClickListener(listener);
}
}
FactBook.java
package com.spdesigns.funfacts;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
* FunFacts was
* Created by Stelios Papamichail on 11/2/2017.
* <p>
* This file belongs to the com.spdesigns.funfacts package.
*/
class FactBook {
private static List<String> facts;
static void initFacts() {
facts = Arrays.asList("If you somehow found a way to extract all of the gold from the bubbling core of our lovely little planet, you would be able to cover all of the land in a layer of gold up to your knees.",
"McDonalds calls frequent buyers of their food “heavy users.",
"The average person spends 6 months of their lifetime waiting on a red light to turn green.",
"The largest recorded snowflake was in Keogh, MT during year 1887, and was 15 inches wide.",
"You burn more calories sleeping than you do watching television.",
"There are more lifeforms living on your skin than there are people on the planet.",
"Southern sea otters have flaps of skin under their forelegs that act as pockets. When diving, they use these pouches to store rocks and food.",
"In 1386 a pig in France was executed by public hanging for the murder of a child.",
"One in every five adults believes that aliens are hiding in our planet disguised as humans.",
"If you believe that you’re truly one in a million, there are still approximately 7,184 more people out there just like you.",
"A single cloud can weight more than 1 million pounds.",
"A human will eat on average 70 assorted insects and 10 spiders while sleeping.",
"James Buchanan, the 15th U.S. president continuously bought slaves with his own money in order to free them.",
"There are more possible iterations of a game of chess than there are atoms in the known universe.",
"The average person walks the equivalent of three times around the world in a lifetime.",
"Men are 6 times more likely to be struck by lightning than women.",
"Coca-Cola would be green if coloring wasn’t added to it.",
"You cannot snore and dream at the same time.",
"The world’s oldest piece of chewing gum is over 9,000 years old!",
"A coyote can hear a mouse moving underneath a foot of snow.",
"Bolts of lightning can shoot out of an erupting volcano.",
"New York drifts about one inch farther away from London each year.",
"A U.S. dollar bill can be folded approximately 4,000 times in the same place before it will tear.",
"A sneeze travels about 100 miles per hour.",
"Earth has traveled more than 5,000 miles in the past 5 minutes.",
"It would take a sloth one month to travel one mile.",
"10% of the World’s population is left handed.",
"A broken clock is right two times every day.",
"According to Amazon, the most highlighted books on Kindle are the Bible, the Steve Jobs biography, and The Hunger Games.",
"Bob Marley’s last words to his son before he died were “Money can’t buy life.",
"A mole can dig a tunnel that is 300 feet long in only one night.",
"A hippo’s wide open mouth is big enough to fit a 4-foot-tall child in.",
"Chewing gum while you cut an onion will help keep you from crying.",
"If you were to stretch a Slinky out until it’s flat, it would measure 87 feet long.",
"Al Capone’s business card said he was a used furniture dealer",
"There are more collect calls on Father’s Day than on any other day of the year.",
"Banging your head against a wall burns 150 calories an hour.",
"95% of people text things they could never say in person.",
"A crocodile can’t poke its tongue out.",
"It is physically impossible for pigs to look up into the sky.",
"Guinness Book of Records holds the record for being the book most often stolen from Public Libraries.",
"The word “gorilla” is derived from a Greek word meaning, “A tribe of hairy women.”" ,
"Prisoners in Canadian war camps during WWII were treated so well, that a lot of them didn’t’ want to leave when the war was over." ,
"Gorillas burp when they are happy " ,
"In New York, it is illegal to sell a haunted house without telling the buyer." ,
"In 2006 someone tried to sell New Zealand on eBay. The price got up to $3,000 before eBay shut it down." ,
"It is considered good luck in Japan when a sumo wrestler makes your baby cry." ,
"A man from Britain changed his name to Tim Pppppppppprice to make it harder for telemarketers to pronounce." ,
"A woman from California once tried to sue the makers of Cap’n Crunch, because the Crunch Berries contained “no berries of any kind.”" ,
"Apple launched a clothing line in 1986. It was described as a “train wreck” by others." ,
"In Japan, crooked teeth are considered cute and attractive." ,
"A Swedish woman lost her wedding ring, and found it 16 years later- growing on a carrot in her garden." ,
"Donald duck comics were banned from Finland because he doesn’t wear pants." ,
"The chance of you dying on the way to get lottery tickets is actually greater than your chance of winning." ,
"Cherophobia is the fear of fun." ,
"The toothpaste “Colgate” in Spanish translates to “go hang yourself”",
"Pirates wore earrings because they believed it improved their eyesight.",
"Human thigh bones are stronger than concrete." ,
"Cockroaches can live for several weeks with their heads cut off, because their brains are located inside their body. They would eventually die from being unable to eat." ,
"Scientists have tracked butterflies that travel over 3,000 miles." ,
"To produce a single pound of honey, a single bee would have to visit 2 million flowers." ,
"The population is expected to rise to 10.8 billion by the year 2080." ,
"You breathe on average about 8,409,600 times a year" ,
"More than 60,000 people are flying over the United States in an airplane right now." ,
"Hamsters run up to 8 miles at night on a wheel." ,
"A waterfall in Hawaii goes up sometimes instead of down." ,
"A church in the Czech Republic has a chandelier made entirely of human bones." ,
"Under the Code of Hammurabi, bartenders who watered down beer were punished by execution." ,
"Our eyes are always the same size from birth, but our nose and ears never stop growing." ,
"During your lifetime, you will produce enough saliva to fill two swimming pools." ,
"You are 1% shorter in the evening than in the morning" ,
"The elephant is the only mammal that can’t jump!" ,
"Most dust particles in your house are made from dead skin!",
"If 33 million people held hands, they could make it all the way around the equator." ,
"Earth is the only planet that is not named after a god." ,
"The bloodhound is the only animal whose evidence is admissible in court." ,
"You are born with 300 bones, but by the time you are an adult you only have 206." ,
"A ten-gallon hat will only hold ¾ of a gallon." ,
"Just like fingerprints, everyone has different tongue prints." ,
"ATM’s were originally thought to be failures, because the only users were prostitutes and gamblers who didn’t want to deal with tellers face to face." ,
"Of all the words in the English language, the word “set” has the most definitions. The word “run” comes in close second." ,
"A “jiffy” is the scientific name for 1/100th of a second." ,
"One fourth of the bones in your body are located in your feet" ,
"111,111,111 X 111,111,111 = 12,345,678,987,654,321" ,
"Blue-eyed people tend to have the highest tolerance of alcohol." ,
"A traffic jam lasted for more than 10 days, with cars only moving 0.6 miles a day." ,
"The tongue is the strongest muscle in the body." ,
"Every year more than 2500 left-handed people are killed from using right-handed products." ,
"More than 50% of the people in the world have never made or received a telephone call." ,
"The cigarette lighter was invented before the match.",
"A flea can jump up to 200 times its own height. That is the equivalent of a human jumping the Empire State Building." ,
"There are 5 temples in Kyoto, Japan that have blood stained ceilings. The ceilings are made from the floorboards of a castle where warriors killed themselves after a long hold-off against an army. To this day, you can still see the outlines and footprints." ,
"There is a snake, called the boomslang, whose venom causes you to bleed out from every orifice on your body. You may even turn blue from internal bleeding, and it can take up to 5 days to die from the bleeding." ,
"A ball of glass will bounce higher than a ball of rubber." ,
"Saturn’s density is low enough that the planet would float in water." ,
"68% of the universe is dark energy, and 27% is dark matter; both are invisible, even with our powerful telescopes. This means we have only seen 5% of the universe from earth." ,
"The founders of Google were willing to sell Google for $1 million to Excite in 1999, but Excite turned them down. Google is now worth $527 Billion." ,
"In the past 20 years, scientists have found over 1,000 planets outside of our solar system." ,
"There are 60,000 miles of blood vessels in the human body." ,
"If a pregnant woman has organ damage, the baby in her womb sends stem cells to help repair the organ." ,
"If you started with $0.01 and doubled your money every day, it would take 27 days to become a millionaire." ,
"Only one person in two billion will live to be 116 or older." ,
"A person can live without food for about a month, but only about a week without water.",
"If the amount of water in your body is reduced by just 1%, you’ll feel thirsty\n" +
"If it’s reduced by 10%, you’ll die." ,
"On average, 12 newborns will be given to the wrong parents daily." ,
"You can’t kill yourself by holding your breath."
);
}
static String getFact() {
// Randomly select a fact
if(facts.isEmpty()) {
initFacts();
}
Random randomGenerator = new Random();
int randomNumber= randomGenerator.nextInt(facts.size());
String fact = facts.get(randomNumber);
facts.remove(randomNumber);
return fact;
}
}
PS:我认为错误可能是因为我试图在getFact()方法中删除它,但我不明白为什么。是因为列表是在一个方法中初始化的,因为它的内容无法访问?
答案 0 :(得分:1)
由于您使用Arrays.asList
创建列表,因此此列表是不可修改的,您无法添加或删除任何元素。
Arrays.asList
:返回指定支持的固定大小列表 阵列。
所以当你到达 p>行时
facts.remove(randomNumber);
你得到如下的异常(只是猜测,因为你没有共享任何堆栈跟踪或日志):
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at blah.FactBook.getFact(FactBook.java:131)
...
要使列表可修改,请从List
创建一个新的Arrays.asList
对象,例如
facts = new ArrayList<String>(Arrays.asList("If you somehow found a way to extract all..."));