Note: The switch is not at all的用法suitat请问是什么意思

New Java 7 Features: Using String in the Switch Statement Tutorial
Looking for something else?
+ Show More
Share this item with your network:
& TheServerSide
& SearchSAP
& TheServerSide
&Palo Alto
&Dell Compellent
First, I hate the switch statement. It is so darned procedural, and quite often when I see a junior programmer fiddling around with a switch statement, I’m always convinced that there’s probably a much more object oriented way of approaching the problem at hand. But love it or hate it, the switch statement is part of the Java language, and it is part of the Oracle Certified Professional exam, so you need to know how to use it, especially if you want to obtain your OCP designation.
By submitting your email address, you agree to receive emails regarding relevant topic offers from TechTarget and its . You can withdraw your consent at any time. Contact
at 275 Grove Street, Newton, MA.
You also agree that your personal information may be transferred and processed in the United States, and that you have read and agree to the
Java 7 and the Switch Statement
Prior to Java 7, the condition of the switch had to be either a non-long integer type (byte/Byte, short/Short, char/Character and int/Integer), or an enumerated type. So, a basic switch statement might look like this:
public class IntSwitch {
public static void main(String[] args) {
int numberOfPlayers = 6;
String sport =
switch (numberOfPlayers) {
sport = &tennis&;
sport = &volleyball&;
sport = &baseball&;
sport = &redrover&;
System.out.println(&You're playing & + sport);
The code above prints out: You're playing volleyball
It is interesting that you can’t switch on a long. Attempting a piece of code such as this:
long sport = 0;
switch (sport) {}
Would generate a compile time error such as this: Cannot switch on a value of type long. Only convertible int values, strings or enum constants are permitted
Switching on a String
New in Java 7 is the ability for your programs to switch on a String:
public class StringSwitch {
public static void main(String[] args) {
int numberOfPlayers = 0;
String sport = &volleyball&;
switch (sport) {
case &tennis&:
numberOfPlayers = 1;
case &volleyball&:
numberOfPlayers = 6;
case &baseball&:
numberOfPlayers = 9;
System.out.println(numberOfPlayers + & players are needed.&);
In this case, the code switches on the name of the sport, which is of type String, and initializes the int variable named numberOfPlayers depending upon which conditional case in the switch statement is met. When compiled and executed, the code above prints out: 6 players are needed.
By the way, you can group cases together to allow for an initialization to occur under multiple conditions. Take a look at the following example, where the String sport is initialized to &hockey&:
public class StringSwitch {
public static void main(String[] args) {
int numberOfPlayers = 0;
String sport = &hockey&;
switch (sport) {
case &tennis&: case &pingpong&: case &badminton&:
numberOfPlayers = 1;
case &volleyball&: case &hockey&:
numberOfPlayers = 6;
case &baseball&: case &softball&:
numberOfPlayers = 9;
System.out.println(numberOfPlayers + & player(s) are needed.&);
In this switch statement, the numberOfPlayers variables gets initialized to the number 6, and the following is printed out to the console: 6 player(s) are needed.
String and only Strings
And one other thing to note is that the in Java 7 you can switch on a variable of type String, but the variable must be referenced as a String, and not simply initialized as a String, so the following code would fail:
public class StringSwitch {
public static void main(String[] args) {
int numberOfPlayers = 0;
Object sport = &hockey&;
switch (sport) {
case &tennis&: case &pingpong&: case &badminton&:
numberOfPlayers = 1;
case &volleyball&: case &hockey&:
numberOfPlayers = 6;
case &baseball&: case &softball&:
numberOfPlayers = 9;
System.out.println(numberOfPlayers + & player(s) are needed.&);
In this case, the code fails with the following error:& Cannot switch on a value of type Object. Only convertible int values, strings or enum constants are permitted
Passing null references to a switch statement
By the way, one thing you need to be careful of is passing a null to a switch statement. It wasn’t a problem when switch statements just worked with basic primitive types, but when you’re working with wrapper classes, there’s always the possibility that a null object has found it’s way into the mix.
There are two key things you need to know about nulls and switch statements. First, if you pass a null to a switch statement, you’ll get a NullPointerException at runtime. Secondly, there is no way to test &a null case condition in the body of the switch. Trying to add a case null: will generate the following compile time exception: case expressions must be constant expressions
So, the following code&is a complete and total fail in several different ways:
int numberOfPlayers = 0;
String sport =
switch (sport) {
case null:
numberOfPlayers = -1;
case &tennis&: case &pingpong&: case &badminton&:
numberOfPlayers = 1;
case &volleyball&: case &hockey&:
numberOfPlayers = 6;
case &baseball&: case &softball&:
numberOfPlayers = 9;
System.out.println(numberOfPlayers + & player(s) are needed.&);
The code will fail to compile due to the null case, and even if that was removed, the fact that the code switches on a null String would trigger a NullPointerException at runtime. So let that be a lesson to you: avoid null values, especially when you’re working with switch statements.
Java Certification Books and Learning Resources
Check out these other tutorials from TheServerSide's Sal Pece and Cameron McKenzie covering the new Java 7 features:
Dig Deeper on Software development techniques and Agile methodologies
At Red Hat Summit, Ansible playbooks look to find common ground between dev and ops teams.
RAID is so yesterday. Hyperscale software-defined storage is a modern model that unites disparate storage resources and recovers ...
Find out how the world's largest betting site, Paddy Power Betfair, leveraged a private cloud to accelerate application delivery.
A new MicroProfile specification promises to simplify microservice development on Java EE. George Lawton explains why this is ...
Due to the nature of containers, achieving persistent storage is often a challenge in containerized environments. Chris Tozzi ...
As RESTful design becomes synonymous with API creation, it may be helpful to spruce up some knowledge on it. This quick quiz ...
Even Agile organizations get stuck sometimes. What to do? OpenSpace Agility is a bold new way to work through problems, but it ...
Expert Gerie Owen traveled to Tallinn, Estonia for Nordic Testing Days. Here's her first-hand look at this vibrant, grass-roots ...
There are a lot of moving parts involved when deciding on APM/test tools. Choosing the right ones can often be a strenuous ...
Tagetik allows John Hancock and Manulife to reduce the time it takes to produce financial reports and to automatically update ...
PROACTIS helps organizations streamline the procurement process with the spend control applications in its procurement suite, ...
With SMART by GEP, users have access to a wide range of Microsoft Azure-powered, cloud-based e-procurement software, which can be...
Small companies in micro-vertical industries, such as food and beverage, find resellers -- and SAP itself -- eager to exploit ...
The new SAP Geographic Enablement Framework extends the integration of geospatial data from GIS into HANA applications. Also, SAP...
A new report from Nucleus Research says six out of 10 SAP customers would not buy SAP products again, and even in the core ERP ...
At its 2016 user conference, Infor featured the Lift and Shift program, which the company hopes will get legacy on-premises ...
With Microsoft Dynamics AX, users have a fully realized, fully supported, cloud-based ERP software that works in both the public ...
With SAP ERP modules like accounting and finance and inventory and distribution management, SAP Business One Cloud is a ...Results from an unscientific survey of Washington Post readers
How the team became the Redskins in the first place is either a story of honor or shame, depending on who is telling it. In one version, Marshall changed it from the Braves in 1937 to honor then-coach William “Lone Star” Dietz, a Sioux Indian. But a historian has since cast doubt on Dietz’s Indian roots, saying he stole the identity of a Native American man. Many people question whether Marshall, an anti-integrationist, would have honored him. Marshall famously resisted
until 1961 under threat from the federal government, making the Redskins the last NFL team with an all-white roster. In his will, he stipulated that not a single dollar of the Redskins Foundation, to be created with his estate, go toward “any purpose which supports or employs the principle of racial integration in any form.” Marshall was still majority owner at the time of the 1972 meeting. Despite his history, he agreed to have the cheerleaders stop wearing “Indian-style” wigs and to change the fight song. But the team’s name would remain untouched. “We would not carry a symbol offensive to any group,” Williams told The Washington Post later that year. “Had I been persuaded, we would have taken action accordingly.”
Snyder declined a request for an interview, but his attorney Lanny Davis said Saturday that the name is “our history and legacy and tradition.” “We at the Redskins respect everyone,” Davis said in a statement. “But like devoted fans of the Atlanta Braves, the Cleveland Indians and the Chicago Blackhawks (from President Obama’s home town), we love our team and its name and, like those fans, we do not intend to disparage or disrespect a racial or ethnic group.” Former Redskins coach Joe Gibbs recently told radio station WNEW, “I never ever thought of it as anything negative, but it’s all been a positive and I think that’s what I reflect on when I reflect on the song, the games and everybody being loyal Redskin people.” Davis said Obama was probably unaware of a 2004 poll by the Annenberg Institute showing that nine out of 10 Native Americans were not offended by the team’s name. The study, the only major survey on the issue that has focused on Native Americans, has long been held up by defenders as a reason to leave the name alone. “If the population that is supposed to be offended isn’t, then why should everyone else be upset about it?” said Lisa Delpy-Nerotti, professor of tourism and sport management at George Washington University. Former FCC chairman Reed Hundt said polling numbers are not the final word. “If you can’t look at somebody and use a certain name because it is an insult, then that is the moment of awareness that it is time for the name to be changed,” he said. Since January, he has led an effort to get the FCC to convene a public meeting between broadcasters and Native American leaders on the subject. His hope is that broadcasters will voluntarily agree to stop using it, much the way individual journalists have. “At the end of the day, if the owner can’t get the media to use the name, then it doesn’t have any brand value,” he said. John Banzhaf, a George Washington University law professor who pressured the FCC in the 1960s to allot air time for anti-tobacco ads, was writing letters to major Washington stations 14 years ago warning them they could lose their broadcasting licenses for airing the team’s name. Ultimately, he said, the commission could take a harder stance on the Redskins issue. In the 1970s, the commission advised stations against playing music that gave a nod to drug use. “If the FCC can come out and say ‘Lucy in the Sky with Diamonds’ is wrong and a station could lose their license for playing it, I think it’s much more of a sin for a station to repeatedly use the word ‘Redskins,’ ” he said. Hundt’s FCC strategy comes as a number of prominent sportswriters, most recently , have declared they will not use the word. At The Washington Post, several columnists, including , have long denounced it. In September, the newspaper’s
took a stance against it, arguing that the moniker “no matter its storied tradition or importance to many fans — is a racial slur of Native Americans so offensive that it should no longer be tolerated.” Martin Baron, The Post’s executive editor, said the paper’s policy is to use the names that institutions select for themselves. The origins of the word remain in dispute, with some scholars saying Native Americans coined the term in the 18th century to describe themselves. Others link it to a time when a price was paid for the scalps of American Indians. Whatever its origins, Merriam-Webster’s dictionary currently defines the word “redskin” as
Phil Gover was a 23-year-old recent graduate of the University of Virginia when he joined a lawsuit to revoke the Redskins’ federal trademark protection. A similar suit, brought by Suzan Harjo and seven other Native Americans in 1992, was
on a technicality in 2009. Now with final arguments presented before the Trademark Trial and Appeal Board, a decision in the current case could come any day. If the ruling falls in favor of Gover, now 31, and the four other plaintiffs, the team would not be forced to change its name but would lose its registered trademark status, which helps protect it from individuals looking to sell merchandise with the moniker on it. In the past, trademark office examiners have rejected four other applications that used the word Redskins, including “Redskins Pigskins” and “Redskins Fanatics,” on grounds that they were disparaging. “There is no other culture that we get to wholesale market and misappropriate — intentionally misappropriate — in order to sell something,” said Gover, whose father, Kevin Gover, heads the Smithsonian’s National Museum of the American Indian. “But more than being wrong, it has bad effects. It translates to people’s perceptions of themselves.” A member of the Paiute tribe who grew up on reservations in Nevada, Gover said as soon as he headed east to attend boarding school, he was reminded of the stereotypes reinforced by mainstream imagery. He was teased about tepees and headdresses. When he played football, he was asked why the paint on his face wasn’t more elaborate. Shortly before he joined the lawsuit, Gover had a son and said he worried about the image that boy, whose mother is also Native American, would have of his culture. In Charlottesville, where they live, the Redskins logo is all around: in grocery store aisles, on passing cars, on the backs of second-graders the last Friday of every month — team day. “How will he grow up to think about himself, to think about his identity and where his family came from?” Gover said. As soon as the season opened, the Oneida Indian Nation in New York launched a national campaign targeting the Redskins, scheduling radio ads to follow the players from city to city. It said the goal was to educate the public about the “dehumanizing” nature of the word.
The Oneida Nation has become one of the most prominent voices in the campaign to change the name of the Washington football team within the past year. The push began in earnest after it helped a Cooperstown, N.Y., high school change its nickname from the Redskins to the Hawkeyes, spokesman Joel Barkin said. The tribe “wanted to use it as a teachable moment,” he said.
The tribe, which has about 1,000 members and is based in Central New York, has prospered in the casino and resort business and become a player in Washington on Native American issues, most notably as a major supporter of the Smithsonian’s Museum of the American Indian. The tribe has promised the museum $10 million over 10 years. It has organized a Monday conference at the Ritz-Carlton in Georgetown as “a chance for NFL officials, policymakers, and other concerned citizens to hear from federal legislators, community leaders and experts about the campaign.”
Not all Native Americans are offended by the name. Two polls focusing on the Indian community — conducted in 2002 and 2004 — showed the vast majority supported it. For one family on the Rosebud Sioux reservation in South Dakota, it is even a point of pride. Ida “One Star” Marshall (no relation to the team’s late owner) said her family has been mostly quiet about the issue over the years, even after team representatives visited them under the leadership of Jack Kent Cooke. But then they heard about the Oneida Nation’s push to change the name. “They have no business saying that,” Marshall said recently. “He doesn’t belong to them,” she said of “Lone Star” Dietz. Marshall, 60, said she and her siblings are relatives of Dietz and that he had hoped the name would encourage children who, like him, attended the Carlisle Indian Industrial School, which aimed at assimilation. “He wanted the kids at Carlisle school to not forget who they were, where they came from,” she said. Linda Waggoner, a historian who has written papers debunking Dietz’s Indian roots, has spoken with Marshall and believes she and her siblings are connected to Dietz — but not by blood. She said her research shows the family is related to the Indian man whose identity Dietz stole, a charge to which he pleaded not guilty when the government tried him for using it to avoid military service. Instead, the story about Marshall honoring Dietz is likely just one of many fabrications the team has put forward over time, she said. The most recent one came in May when Snyder’s public relations team touted an Indian chief who described the Redskins as a term of endearment — saying “When we were on the reservation, we’d call each other ‘Hey, what’s up, redskin?’ ” But Deadspin reporter Dave McKenna later turned up evidence that he was not a chief, and maybe not even Native American. Still, it was believable enough that in June, NFL Commissioner Roger Goodell used the alleged chief’s remarks to defend the team’s name in a letter he wrote to 10 members of Congress. The lawmakers have introduced a bipartisan bill that, like the lawsuit, would strip the team of its trademark protection. In his letter, Goodell called the name “a unifying force that stands for strength, courage, pride and respect.” Last month, however, Goodell took a much more tempered stance. During a radio interview, he said: “If one person’s offended, we have to listen.” But he stopped there. Ultimately, he said, the decision would be Snyder’s. Through a spokesman, the NFL declined to comment about Obama’s statement.
Unlike most debates, the one surrounding the team’s name does not consist of two sides shouting at each other. Some of the most powerful voices in the fight are speaking by saying nothing. Liz Aquilino, a spokeswoman for Bob’s Discount Furniture, “the official furniture partner of the Washington Redskins,” said no one was available to comment. Pat Morrissey, a spokesman for General Motors, which owns GMC, the official vehicle of the NFL, said it wouldn’t be appropriate for the company to comment on any issue involving a single team. Shareholders at FedEx, which owns the naming rights to the team’s Landover, Md., stadium, recently rejected a resolution by shareholder activists that called for exploring the cost of ending the company’s deal with the team. Marketing experts say it is not in the interest of the NFL’s top sponsors — beer companies, pizza purveyors and cellphone carriers — to take a stance on the name because they need the league’s 181 million viewers during the regular season. “As long as they are getting ratings, their attitude is, ‘I don’t care what they’re called,’ ” said Bob Leffler, founder of the Leffler Group in Baltimore, the nation’s largest sports entertainment advertising agency. Instead, advertisers are likely to wait the controversy out, as they have in the past, he said.
In the end, the group that could wield the most influence is the one that buys the team’s gear and fills the stadium’s seats: the fans. The Redskins are one of the league’s most profitable franchises, earning more than $381 million in revenue last year, according to Forbes. Polls show that even if support for the name has eroded over time, it has only slightly.
revealed that 28 percent of people in the region said the name should be changed. An Associated Press poll conducted a month later showed that nationally the number was even lower: 11 percent. Three months before Snyder declared in a USA Today interview what has now become a mantra among his supporters — “We’ll never change the name. It’s that simple. NEVER – you can use caps.” — the Smithsonian Institution sponsored a symposium dedicated to discussing racist stereotypes in American sports. Toward the end of the day, a young black man named Andre Holland stepped up to the microphone. A lifelong Redskins fan, he was attending the symposium with his Anne Arundel Community College sports history class. He hadn’t given a second thought to wearing gear with the name of his favorite team. It was on his cap and his earmuffs and the T-shirt tucked under his polo shirt. But as he waited to make a comment, he said, he felt a tap on his shoulder and an older Indian man asked him to please remove the hat because it was offensive. “It woke me up,” Holland, now 21, recalled. “What if they called a team the Los Angeles Negroes?” In a moment that several people would later describe as “beautiful,” he tossed his Redskins baseball cap on the floor, apologized to the crowd for wearing it and said the name should change. The room filled with applause. But in the months that followed, Holland said he didn’t hear much about the name-change effort. There were no local protests to join, he said. No online effort to spread. Then a few weeks ago, he was getting ready to attend a game and found himself with a choice. His girlfriend had bought him a new RGIII Redskins jersey for his birthday. Holland said he paused and thought about it. Then he put it on.
post_newsletter348 follow-orlando true after3th false
Please provide a valid email address.
You’re all set!
post_newsletter353 follow-dallas false endOfArticle false
Please provide a valid email address.
You’re all set!
SuperFan Badge SuperFan badge holders consistently post smart, timely comments about Washington area sports and teams.
Culture Connoisseur Badge Culture Connoisseurs consistently offer thought-provoking, timely comments on the arts, lifestyle and entertainment.
Fact Checker Badge Fact Checkers contribute questions, information and facts to .
Washingtologist Badge Washingtologists consistently post thought-provoking, timely comments on events, communities, and trends in the Washington area.
Post Writer Badge This commenter is a Washington Post editor, reporter or producer.
Post Forum Badge Post Forum members consistently offer thought-provoking, timely comments on politics, national and international affairs.
Weather Watcher Badge Weather Watchers consistently offer thought-provoking, timely comments on climates and forecasts.
World Watcher Badge World Watchers consistently offer thought-provoking, timely comments on international affairs.
Post Contributor Badge This commenter is a Washington Post contributor. Post contributors aren’t staff, but may write articles or columns. In some cases, contributors are sources or experts quoted in a story.
Post Recommended Washington Post reporters or editors recommend this comment or reader post.
You must be logged in to report a comment.
You must be logged in to recommend a comment.
To pause and restart automatic updates, click "Live" or "Paused". If paused, you'll be notified of the number of additional comments that have come in.
Spam Offensive Disagree Off-Topic
Our Online Games
Play right from this page
Success! Check your inbox for details.
Please enter a valid email address
You might also like:
Sign Up No Thanks
Close video player
Now Playing

我要回帖

更多关于 im switch not found 的文章

 

随机推荐