Java得到“非法的表达式开始”和“';' 方法的预期错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19581173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:31:25  来源:igfitidea点击:

Java getting "Illegal start of expression" and "';' expected" errors for a method?

java

提问by

EDIT: I figured it out and finished the program (finally). Thanks everyone for your help!

编辑:我想通了并完成了程序(最后)。感谢大家的帮助!

I'm trying to create a simple paint program where the user can click on radio buttons to choose a shape that they can draw on the panel by dragging with the mouse. I do simply want the code to do this, as I want to figure it out on my own and think that I can. BUT I'm getting these errors on the line declaring the method "public void newShape(String shape) {". I am getting 4 errors on this one line. Two of them are "error: illegal start of expression", and the other two are "error: ';' expected". If someone could help me out and tell me what I'm doing wrong I would greatly appreciate it.

我正在尝试创建一个简单的绘画程序,用户可以在其中单击单选按钮来选择可以通过鼠标拖动在面板上绘制的形状。我只是想让代码做到这一点,因为我想自己弄清楚并认为我可以。但是我在声明方法“public void newShape(String shape){”的行中遇到了这些错误。我在这一行上收到 4 个错误。其中两个是“错误:表达式的非法开始”,另外两个是“错误:';' 预期的”。如果有人可以帮助我并告诉我我做错了什么,我将不胜感激。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.event.*;

public class HW4_Paint extends JFrame {

private static Color color = Color.BLACK; // current selected drawing color
    private static boolean filled = false; // fill mode - "Filled" or "Empty"
    private static String currentShape = "Line"; // current selected shape
    private static ArrayList<Shape> shapes = new ArrayList<Shape>(); // a list of all of the shapes in the current drawing

    public static void main(String[] args) {

        // create the frame and format it
        JFrame frame = new HW4_Paint();
        frame.setTitle("Paint Program");
        frame.setSize(800,500);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public HW4_Paint() {

        // create the menu bar
        JMenuBar jmb = new JMenuBar();
        setJMenuBar(jmb);

        // make the file menu
        JMenu fileMenu = new JMenu("File");
        fileMenu.setMnemonic('F');
        jmb.add(fileMenu);

        // make the exit menu item under the file menu
        JMenuItem exitMenuItem = new JMenuItem("Exit", 'X');
        fileMenu.add(exitMenuItem);
        exitMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
        });

        // make the help menu
        JMenu helpMenu = new JMenu("Help");
        helpMenu.setMnemonic('H');
        jmb.add(helpMenu);

        // make the help menu item under the help menu
        JMenuItem helpMenuItem = new JMenuItem("Help", 'H');
        helpMenu.add(helpMenuItem);
        helpMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String message = "This program allows you to draw pictures using different shapes and colors.\n" 
                             + "To change what shape you are drawing with, select the button next to Line, Oval, or Rectangle, depending on which shape you want to draw with.\n"
                             + "If you want the shape to be filled in (only applicable with oval and rectangle), select the checkbox next to Filled.\n"
                             + "To change the color of the shape that you are drawing, click the button of the color that you want to change to.\n"
                             + "To undo the last shape that you drew, click the undo button once. You can repeat this as many times as you want until there are no remaining shapes.\n"
                             + "To clear all of the shapes that you have drawn, click the Clear All button.";

            JOptionPane.showMessageDialog(null, message, "Help", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        // make the about menu item under the help menu
        JMenuItem aboutMenuItem = new JMenuItem("About", 'A');
        helpMenu.add(aboutMenuItem);
        aboutMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String message = "HW4_Paint Program\n\n" + "Written by Joey Drees\n\n" + "CSC 360-001";
            JOptionPane.showMessageDialog(null, message, "About", JOptionPane.INFORMATION_MESSAGE);
        }
        });

        // make the panels that will be added to the frame for the GUI
        JPanel guiPanel = new JPanel();
        guiPanel.setLayout(new BorderLayout());
        JPanel colorPanel = new JPanel(new FlowLayout());
        JPanel buttonPanel = new JPanel(new GridLayout(6,1));
        JPanel drawingPanel = new DrawingPanel();

        // add the guiPanel to the frame and them add the other panels to the guiPanel
        add(guiPanel);
        guiPanel.add(colorPanel, BorderLayout.SOUTH);
        guiPanel.add(buttonPanel, BorderLayout.EAST);
        guiPanel.add(drawingPanel, BorderLayout.CENTER);

    // create and add the buttons that will allow the user to change the color of the shapes
        JButton blackButton = new JButton("Black");
        colorPanel.add(blackButton);
        blackButton.setSelected(true);
        JButton whiteButton = new JButton("White");
        colorPanel.add(whiteButton);
        JButton grayButton = new JButton("Gray");
        colorPanel.add(grayButton);
        JButton redButton = new JButton("Red");
        colorPanel.add(redButton);
        JButton yellowButton = new JButton("Yellow");
        colorPanel.add(yellowButton);
        JButton greenButton = new JButton("Green");
        colorPanel.add(greenButton);
        JButton blueButton = new JButton("Blue");
        colorPanel.add(blueButton);
        JButton newColorButton = new JButton("New Color");
        colorPanel.add(newColorButton);

        // create and add the radio buttons to a button group that will allow the user to change the shape they are drawing with
        ButtonGroup jbtGroup = new ButtonGroup();
        JRadioButton jrbLine = new JRadioButton("Line");
        jrbLine.setMnemonic('L');
        jbtGroup.add(jrbLine);
        buttonPanel.add(jrbLine);
        jrbLine.setSelected(true);
        jrbLine.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent E) {
            currentShape = "Line";
            guiPanel.newShape(currentShape);
            repaint();
        }
        });
        JRadioButton jrbOval = new JRadioButton("Oval");
        jrbOval.setMnemonic('O');
        jbtGroup.add(jrbOval);
        buttonPanel.add(jrbOval);
        jrbOval.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent E) {
            currentShape = "Oval";          
            guiPanel.newShape(currentShape);
            repaint();
        }
        });
        JRadioButton jrbRectangle = new JRadioButton("Rectangle");
        jrbRectangle.setMnemonic('R');
        jbtGroup.add(jrbRectangle);
        buttonPanel.add(jrbRectangle);
        jrbLine.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent E) {
            currentShape = "Rectangle";
            guiPanel.newShape(currentShape);
            repaint();
        }
        });

        // create and add the check box that will allow the user to create filled shapes
        JCheckBox jcbFilled = new JCheckBox("Filled");
        jcbFilled.setMnemonic('F');
        buttonPanel.add(jcbFilled);
        if (jrbLine.isSelected())
        jcbFilled.setEnabled(false);
        else
        jcbFilled.setEnabled(true);

        // create and add the buttons that will allow the user to undo their last shape and clear the whole panel
        JButton undoButton = new JButton("Undo");
        undoButton.setMnemonic('U');
        buttonPanel.add(undoButton);
        JButton clearAllButton = new JButton("Clear All");
        clearAllButton.setMnemonic('C');
        buttonPanel.add(clearAllButton);

        // create the action listener for the undo button
        undoButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!shapes.isEmpty()) {
            shapes.remove(shapes.size() - 1);
            repaint();
        }
        }
    });

    // create the action listener for the clear all button
        clearAllButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if (!shapes.isEmpty()) {
            shapes.clear();
        repaint();
        }
    }
    });

    public void newShape(String shape) {

    switch (shape) {
        case "Line":
            Shape line = new Line(startX, startY, endX, endY);
        shapes.add(line);
        break;
            case "Oval":
        Shape oval = new Oval(startX, startY, endX, endY);
        shapes.add(oval);
        break;
        case "Rectangle":
        Shape rectangle = new Rectangle(startX, startY, endX, endY);
        shapes.add(rectangle);
        break;
        default:
        System.out.println("ERROR. Check logic.");
    }
    }
}
}

private class DrawingPanel extends JPanel {

private int startX, startY, endX, endY;

    public DrawingPanel() { // sets the background to white and adds the required listeners

        setBackground(Color.WHITE);
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
            startX = endX = e.getX();
            startY = endY = e.getY();
        }
        });
        addMouseMotionListener(new MouseMotionAdapter() {
        @Override
        public void mouseDragged(MouseEvent e) {
            endX = e.getX();
            endY = e.getY();
            Shape lastShape = shapes.get(shapes.size()-1);
            lastShape.setEnd(endX, endY);
            repaint();
        }
        });
    }   

public void paintComponent(Graphics g) {

        super.paintComponent(g);
        for (Shape shape: shapes)
        shape.draw(g);
    }
}

回答by SpringLearner

There are two extra curly braces

有两个额外的花括号

}
}

Remove these two

去掉这两个

You need to keep one }in the constructor HW4_Paint()and remove one }from the method newShape(String shape)

您需要}在构造函数中保留一个HW4_Paint()}从方法中删除一个newShape(String shape)

回答by Christian Ternus

Welcome to StackOverflow! I commend your desire to solve your problem on your own, so I won't just hand you the answer.

欢迎使用 StackOverflow!我赞扬你想自己解决问题的愿望,所以我不会只给你答案。

You're getting that message because newShape()is in the wrong place. Perhaps it's too far into a scope? Perhaps it's too far out of it? Check the indentation of your program in its IDE -- where is it sitting? Do you expect it to be there?

你收到这条消息是因为newShape()在错误的地方。也许它太远了?也许它太远了?检查程序在其 IDE 中的缩进——它在哪里?你希望它在那里吗?

回答by Alex

} // ADD IT HERE

       public void newShape(String shape) {

        switch (shape) {
            case "Line":
                Shape line = new Line(startX, startY, endX, endY);
            shapes.add(line);
            break;
                case "Oval":
            Shape oval = new Oval(startX, startY, endX, endY);
            shapes.add(oval);
            break;
            case "Rectangle":
            Shape rectangle = new Rectangle(startX, startY, endX, endY);
            shapes.add(rectangle);
            break;
            default:
            System.out.println("ERROR. Check logic.");
        }
        }
    } // REMOVE IT FROM HERE
    }

回答by MadProgrammer

You seem to be declaring the newShapemethod within the constructor of the HW4_Paintclass.

您似乎newShapeHW4_Paint类的构造函数中声明了该方法。

Add a }before the public void newShape(String shape) {and remove one }after the method.

在方法}之前添加一个public void newShape(String shape) {}在方法之后删除一个。

It should look more like...

它应该看起来更像...

        // create the action listener for the clear all button
        clearAllButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (!shapes.isEmpty()) {
                    shapes.clear();
                    repaint();
                }
            }
        });
    } // Add me

    public void newShape(String shape) {

        switch (shape) {
            case "Line":
                Shape line = new Line(startX, startY, endX, endY);
                shapes.add(line);
                break;
            case "Oval":
                Shape oval = new Oval(startX, startY, endX, endY);
                shapes.add(oval);
                break;
            case "Rectangle":
                Shape rectangle = new Rectangle(startX, startY, endX, endY);
                shapes.add(rectangle);
                break;
            default:
                System.out.println("ERROR. Check logic.");
        }
    }
    // Remove a } from here, so you should end with these 3, not 4
}

回答by Louise

As far as I have found, errors like "illegal start of expression" or "';' expected" usually means you did something wrong with the {}. I had 38 errors entirely unrelated to the actuall lines of code but all due to a forgotten }.

据我发现,诸如“非法开始的表达”或“';'之类的错误 预期”通常意味着您对 {} 做错了。我有 38 个与实际代码行完全无关的错误,但都是由于忘记了}。