繁体   English   中英

打印用户输入的字符串变量所需的Java帮助

[英]Java help needed for printing user entered string variable

我正在尝试编写一个程序,接受用户输入的全名和性别(m / f)。

import java.util.Scanner;
public class CSCD210Lab2 { // class declaration

public static void main(String[]args) { // main method
    Scanner userInput = new Scanner(System.in); // scanner object for console input
    System.out.print("Enter Your Full Name: ");
    String fullName;
    fullName = userInput.next( );

    System.out.print = fullName; // print user input
    }
}

目前,我只有用户输入其姓名的代码。 我想确保存储了fullName变量,因此我尝试让控制台打印用户键入的内容。 但是,我在System.out.print = fullName;上收到语法错误System.out.print = fullName; 它给了我这个错误信息:

CSCD210Lab2.java:12: error: cannot find symbol
      System.out.print = fullName;
                ^
  symbol:   variable print
  location: variable out of type PrintStream
  1 error

我在这里做错了什么?

错误的语法。 System.out.print是一个函数,因此不适合作为赋值操作的左侧。 尝试这个

System.out.print(fullName); 
//or
System.out.println(fullName);

print是一种方法,而不是变量:

System.out.print(fullName);

不要使用.next() ,而是尝试将其放入: userInput.nextLine();

意思是只添加.nextLine()方法调用而不是next()方法。 还有System.out.println("text goes here "); 是如何使用此功能的。 希望这会有所帮助,欢呼。

fullName = userInput.nextLine();    //next()will stop with first space ,so it is not compatible with your code , but it is right
System.out.print(fullName);//print() is method you need to pass  to it argument not to assign to it values like variables 

我运行了您的代码并进行了测试,发现当您使用时,

System.out.print

您需要在打印后加上括号()。 不管它只是像fullName一样打印的变量

所以这是你的解决办法

System.out.print(fullName);

另外,我注意到当您输入全名时,它只会打印名字。 为了解决这个问题,请使用nextLine();方法nextLine(); 而不是next();

这将允许打印全名。

import java.util.Scanner;
public class CSCD210Lab2 { // class declaration

public static void main(String[]args) { 
Scanner userInput = new Scanner(System.in); 
System.out.print("Enter Your Full Name: ");
String fullName;
fullName = userInput.nextLine( );

System.out.print(fullName); // print user input
}
}

完整的代码在这里。 nextline()将允许您在实体之间使用空格。 每行将被视为单个条目。

干杯!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM