无法编译Java代码以实现“接口”

时间:2017-09-07 17:54:00

标签: java multiple-inheritance

我无法编译和执行java Code.This是关于实现多重继承的接口的程序 这是下面的代码:

//Interface Implementation
import java.util.Scanner;
interface Sports
{
int sportswt = 12;
}
class Student
{
int rollno;
String name;
Scanner sc = new Scanner(System.in);
void getData()
{
    System.out.println("Name and Roll no :");
    rollno = sc.nextInt();
    name = sc.nextLine();
}
}
class Marks extends Student implements Sports
{
 Scanner sc = new Scanner(System.in);
 int m1 = sc.nextInt();
 int m2 = sc.nextInt();
 System.out.println("Name is : " + name + "\nRoll no is : " + rollno);
 System.out.println("Marks1 : " +m1+ "\nMarks2 : " +m2+"\nTotal is : " + 
 (m1+m2+sportswt)); 
 }
  class InterfaceImplementation6
  {
   public static void main(String[] args){
    Marks mobj = new Marks();
    mobj.getData();
   }
  }

有人可以帮忙!! 我收到了这个错误:

enter image description here

1 个答案:

答案 0 :(得分:0)

主要问题是使用nextLine()而非next()

我重构了一些代码,使其更清晰:

import java.util.Scanner;

interface Sports {
    int sportswt = 12;
}

class Student {
    int roll;
    String name;

    void getData() {
        System.out.println("Name and roll number:");
        Scanner sc = new Scanner(System.in);
        name = sc.next(); //if you first ask for name, read the name first
        roll = sc.nextInt();
    }
}

class Marks extends Student implements Sports {

    @Override
    void getData() {
        super.getData();
        Scanner sc = new Scanner(System.in);
        int mark1 = sc.nextInt(); //be more descriptive on your variable names
        int mark2 = sc.nextInt();
        int total = mark1 + mark2 + sportswt; //try to extract operations out of the println() function, so is easier to understand
        System.out.println("Name is : " + name + "\nRoll no is : " + roll);
        System.out.println("Marks1 : " + mark1 + "\nMarks2 : " + mark2 + "\nTotal is : " + total);
    }
}

class InterfaceImplementation6 {

    public static void main(String[] args) {
        Marks mobj = new Marks();
        mobj.getData();
    }
}