gpt4 book ai didi

java - 有没有更好的方法 - Java 条件语句

转载 作者:太空宇宙 更新时间:2023-11-04 07:24:17 24 4
gpt4 key购买 nike

我刚刚开始编程。我为我的编程课编写了这个类(class)。它从老师给我们的驱动程序中提取参数,然后将比例形状放入用户选择的 jPanel 象限中。它工作正常,但我想知道是否有更有效和更干净的方式来编写代码。老师没有对早期的项目提供任何反馈,所以我想在这里问一下。感谢您的帮助。

import java.awt.*;

public class LearnGraphics {


public static void drawRectangle(Graphics g, int size, String cord_x, String cord_y) {
int longside = size / 4;
int shortside = size / 8;
int x = 0;
int y = 0;
if(cord_x.equals("top")&&cord_y.equals("right")) {
x = size-(size/3);
y = size/8;
}
if(cord_x.equals("top")&&cord_y.equals("left")) {
x = size/12;
y = size/8;
}
if(cord_x.equals("bottom")&&cord_y.equals("right")) {
x = size-(size/3);
y = size-(size/4);
}
if(cord_x.equals("bottom")&&cord_y.equals("left")) {
x = size/12;
y = size-(size/4);
}
g.drawRect(x, y, longside, shortside);

}

public static void drawLine(Graphics g, int size, String cord_x, String cord_y) {

int x = 0;
int y = 0;
int x1 = 0;
int y1 = 0;
if(cord_x.equals("top")&&cord_y.equals("right")) {
x = size/12;
y = size/6;
x1 = size/3;
y1 = size/6;
}
if(cord_x.equals("top")&&cord_y.equals("left")) {
x = (size/2)+(size/6);
y = size/6;
x1 = size-(size/12);
y1 = size/6;
}
if(cord_x.equals("bottom")&&cord_y.equals("right")) {
x = size/12;
y = size-(size/6);
x1 = size/3;
y1 = size-(size/6);
}
if(cord_x.equals("bottom")&&cord_y.equals("left")) {
x = (size/2)+(size/6);
y = size-(size/6);
x1 = size-(size/12);
y1 = size-(size/6);
}
g.drawLine(x, y, x1, y1 )
}
public static void drawOval(Graphics g, int size, String cord_x, String cord_y) {
int longside = size / 4;
int shortside = size / 8;
int x = 0;
int y = 0;
if(cord_x.equals("top")&&cord_y.equals("right")) {
x = size-(size/3);
y = size/8;
}
if(cord_x.equals("top")&&cord_y.equals("left")) {
x = size/12;
y = size/8;
}
if(cord_x.equals("bottom")&&cord_y.equals("right")) {
x = size-(size/3);
y = size-(size/4);
}
if(cord_x.equals("bottom")&&cord_y.equals("left")) {
x = size/12;
y = size-(size/4);
}
g.drawOval(x, y, longside, shortside);
}
}

最佳答案

如果你执行if-else语句,那么一旦你输入其中一个语句,你就不会再执行if语句,这样会更高效,而且你不会两次询问相同的条件

public static void drawRectangle(Graphics g, int size, String cord_x, String cord_y) {
int longside = size / 4;
int shortside = size / 8;
int x = 0;
int y = 0;
if(cord_x.equals("top")) {
if(cord_y.equals("right"))
{
x = size-(size/3);
y = size/8;
}
else
{
if(cord_y.equals("left"))
{
x = size/12;
y = size/8;
}
}
}
else
{

if(cord_x.equals("bottom")) {
if(cord_y.equals("right"))
{
x = size-(size/3);
y = size-(size/4);
}
else
{
if(cord_y.equals("left"))
{
x = size/12;
y = size-(size/4);
}
}
}
}
g.drawRect(x, y, longside, shortside);

}

除此之外,目前没有什么可担心的,因为现代计算机速度非常快,而且这段代码并不长,所以它会很快

关于java - 有没有更好的方法 - Java 条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18814025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com