有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVAutil。扫描器为什么Java扫描器的这种方法在代码2中工作而不是在代码1中工作?

原因是什么?为什么代码2起作用而代码1显示错误
我首先使用了代码1方法。。它显示错误,然后我尝试将其添加到方法中。。它不知怎么起作用了。。请告诉我原因

代码1:

import java.util.*;
class alpha /*This is not the main class btw */
{
   Scanner x=new Scanner(System.in);
   int k;flag=0;
   String s1=new String();
   s1=x.nextLine(); /* This Line Produces error */
}

代码2:

import java.util.*;
class alpha /*This is not the main class btw */
{
   Scanner x=new Scanner(System.in);
   int k;flag=0;
   String s1=new String();
   void input()
   {
     s1=x.nextLine(); /* Voila this works */
   }
}

共 (1) 个答案

  1. # 1 楼答案

    您的第一个示例没有运行,因为我们不能将语句放在任何方法之外,我们只能将声明和初始值设定项放在像

    int x = 5;

    Hello h = new Hello;

    这就是第一个示例显示错误的原因

    您不应该将像s1=x.nextLine();这样的语句放在任何方法之外