如何使用子字符串将变量的一部分打印到屏幕上,并使用 indexOf 方法确定输入中是否有'@'符号



我的作业:程序应验证输入的电子邮件地址是否包含 @ 符号。否则,程序应通知用户电子邮件地址无效。然后,程序应在打印"再见!"消息后退出程序。

提示:如果电子邮件输入不正确,请考虑使用分支语句(if/else(来处理继续程序或退出程序。

提示:请考虑使用属于 String 类的 indexOf(( 方法来确定电子邮件地址是否包含 @ 符号。

我不确定该怎么做;电子邮件地址是由用户的输入声明的,所以它要求您使用此输入声明变量用户名,但@符号(juliariccio@gmail.com - 希望您将juliariccio打印为用户名(。

**另外,试图弄清楚如何解决所有分支语句不断弹出的错误:

        case "1": System.out.println("nClassification:       Freshman");
             ^
  required: char
  found:    String
My code for the program is below:
````````//import Scanner documentation
import java.util.Scanner;
public class Riccio_Lesson6  {
    public static void main (String [ ] args) {
    //declare variables
    String fname, lname;
    String emailAddress;
    int atSign;
    //create a scanner object
    Scanner keyboard = new Scanner (System.in);
    //prompt user for first and last name
    System.out.print("Please enter your first and last name: ");
    //read user's first name
    fname = keyboard.next();
    //read user's last name
    lname = keyboard.next();
    //prompt user for their email address
    System.out.print("nPlease enter your email address: ");
    //read user's input
    emailAddress = keyboard.next();
    //prompt user for their major & classification code
    System.out.print("Pleast enter two characters (Character #1: Major Code and Character #2: Classification Code): ");
    //read user's input
    String input = keyboard.next();
    char major = input.charAt(0);
    char classification = input.charAt(1);
    //print banner to screen
    System.out.print("n*******************************************************************************************************");
    System.out.print("n             " + fname.toUpperCase() );
    System.out.print(", please review your profile below and learn more about your major.");
    System.out.print("n*******************************************************************************************************");
    //create username
    atSign = emailAddress.lastIndexOf("@");
    username = emailAddress.substring(atSign);
    //print outputs to screen
    System.out.print("nnFirst Name:       " + fname);
    System.out.print("nLast Name:        " + lname);
    System.out.print("nnUsername:       " + username);
    System.out.print("nEmail Address:    " + emailAddress);
       //use a switch statement to determine the user's classification
    switch (classification){
        case "1": System.out.println("nClassification:       Freshman");
                    break;
        case "2": System.out.println("nClassification:       Sophomore");
                   break;
        case "3": System.out.println("nClassification:       Junior");
                    break;
        case "4": System.out.println("nClassification:       Senior");
                    break;
        case "5": System.out.println("nClassification:       Graduate");
                    break;
        default: System.out.println("nYou've entered an invalid year code!");
   }
    //use a switch statement to determine the user's major
    switch (major){
          case "A": System.out.println("nMajor:       Accounting");
                    System.out.println("nMajor Description:   Accounting supplies quantitative information essential to management decision-making and control, as well as a wide variety of tax and consulting services and information on management's effective use of an organization's resources. This major helps prepare students for careers in public, industrial, or governmental accounting and also provides an appropriate background for those planning to enter law school or graduate school. Public accounting is carried on by independent practitioners, most of whom are certified public accountants.");
                      break;
          case "B": System.out.println("nMajor:       Biology");
                    System.out.println("nMajor Description:   Biology examines the fundamental concepts of nature and all aspects of the living environment, from the molecular level to the biosphere. Biology can open doors to many specialized fields, including genetics, biotechnology, environmental biology, and medicine. A Biology major can prepare students for further study in graduate or professional schools, and also trains students for careers in industry, education, or government.");
                      break;
          case "C": System.out.println("nMajor:       Computer Science");
                    System.out.println("nMajor Description:   Computer Science is primarily concerned with the analysis, design, and applications of computing software and systems. It includes programming languages, data structures, compilers, operating systems, data bases, and artificial intelligence.");
                      break;
          case "E": System.out.println("nMajor:       Economics");
                    System.out.println("nMajor Description:   Economics' studies how individuals make choices in the face of scarcity. Whether dealing with how households determine what goods they buy, why firms produce certain quantities of goods and services, and what forces shape the aggregate performance of economic institutions. Economics is valuable not only for the topic it treats, but also for its rigorous methods of analysis. Economic majors often attend graduate school, law school or business school. Majors who choose to work immediately upon graduation may find employment in financial institutions, manufacturing corporations, consulting firms, and state and federal agencies.");
                      break;
          case "H": System.out.println("nMajor:       History");
                    System.out.println("nMajor Description:   History examines the human experience from its origins to the present. The history of countries such as Europe, Canada, America, China, Japan, India, Africa, or Latin America may be studied. Focus may be placed on public events of political, diplomatic, and constitutional history, or on the examination the social, cultural, or economic history of subjects such as villages, cities, witchcraft, sex, literacy, and work. History majors may go on to graduate school, law school or business school. Some may go into the work force, finding jobs with multinational corporations, governmental agencies, or small businesses.");
                      break;
          case "I": System.out.println("nMajor:       Information Sciences and Technology");
                    System.out.println("nMajor Description:   This major is structured to provide students with the theoretical frameworks and skill sets necessary to compete and be productive in the information technology -intensive global context that defines the new Information Age. Specifically, the degree will be focused on a program that will build an understanding of core information technologies and related areas of study; will prepare students for the practical application of various information sciences and related technologies; and engage students in sharpening their abilities to think critically and to work in teams.");
                      break;
          case "J": System.out.println("nMajor:       Journalism");
                    System.out.println("nMajor Description:   Careers include newspaper reporting and editing, magazine writing, broadcast news, corporate public relations, and advertising account services. This major is based on knowledge of the social and professional responsibilities of communicators, and basic competence in journalistic skills.");
                      break;
          case "M": System.out.println("nMajor:       Mathematics");
                    System.out.println("nMajor Description:   Mathematics today is a vibrant and dynamic field, manifesting itself in such familiar things as CAT scans, compact discs, and satellite communication. Accordingly, the mathematics program is broad and varied, with studies in calculus, finite, actuarial sciences and algebra. After graduating, majors successfully pursue a variety of careers, working in industry, insurance (as actuaries), government, finance, and other fields. Many graduates may attend professional schools in law, medicine, or business. Others may go directly into teaching; and still others may go on to graduate programs in mathematics, applied mathematics, engineering, economics, and computer science.");
                      break;
          case "P": System.out.println("nMajor:       Physics");
                    System.out.println("nMajor Description:   Physics studies the fundamental properties and interactions of all forms of matter. Experimental and theoretical investigations are combined to formulate mathematical relationships that describe and predict the behavior of nature. The physics undergraduate program can prepare students for employment in an industrial or governmental laboratory. The program can also prepare students for further study at graduate or professional schools in physics, engineering, biophysics, medicine, education, law, or business.");
                      break;
          case "T": System.out.println("nMajor:       Telecommunications");
                    System.out.println("nMajor Description:   The primary goal of this major is to prepare students for administrative careers in the electronic media. Its professional emphasis is on management and public policy in telecommunications. Telecommunications may provide course work for students interested in television production, from the perspective of production management and administration. The major also serves students seeking greater understanding of the social role and social control of the broadcasting and cable industries. Telecommunications is especially designed for students considering careers in local cable systems operation, local radio and television station administration, television network and cable MSO operations, corporate video, local and federal public policy positions, and emerging media industries.");
                      break;
       default: System.out.println("nYou've entered an invalid major code!");
    }
    }//end of main
}//end of CLASS

要使用 switch 语句(并消除错误(,必须使用 char 值,而不是 String 类型。例如,代替:

    switch(major){
        case "A": //case 1
        case "B": //case 2
        case "C": //etc.

用:

switch(major){
    case 'A': //case 1
    case 'B': //case 2
    case 'C': //etc.

要使用 indexOf(( 检查 @ 符号,您希望它看起来更像这样:

atsign = emailAddress.indexOf('@');
if(atsign >= 0){
    username = emailAddress.substring(0, atsign);
}

基本上,indexOf(char c( 将返回找到指定字符 c 的第一个索引,或者如果该字符不在字符串中,它将返回 -1。 substring(int start, int end( 将返回 indeces [start, end] 中的字符串。 例如。

String str = "milkandcookies";
String sub = str.substring(0, 4);
//now printing sub will print "milk"
    Scanner keyboard = new Scanner(System.in);
    String emailAddress = keyboard.next();
    String userName = emailAddress.substring(0, emailAddress.indexOf('@'));
    System.out.println(userName);

要解决开关大小写错误,请将大小写值的双引号替换为单引号,例如

    case 'A'

最新更新