【问题标题】:Card Description method improper use? Java卡片说明方法使用不当?爪哇
【发布时间】:2015-09-14 19:04:51
【问题描述】:

我正在编写一个程序,它接受用户输入来打印卡片的完整描述。 (即 4S = 黑桃四) 完成 Card 类后,我尝试使用它通过 getDescription 方法返回卡片的描述,但它不会编译。

import java.util.*;

public class CardDescription {


public static void main(String[] args) {
Card c1 = new Card("KS");
System.out.println("Your card is" + c1.getDescription());
}}

public class Card {
private String value;
private String suite;
private String string1;
private String string2;

public Card(String s1){
value = s1.substring(0, 1);
suite = s1.substring(1);
}
public String getDescription(){
if (value.equalsIgnoreCase("A")){
    string1 = "Ace";
}
else if(value.equalsIgnoreCase("K")){
    string1 = "King";
}
else if(value.equalsIgnoreCase("Q")){
    string1 = "Queen";
}
else if(value.equalsIgnoreCase("J")){
    string1 = "Jack";
}
else if(value.equals("10")){
    string1 = "Ten";
}
else if(value.equals("9")){
    string1 = "Nine";
}
else if(value.equals("8")){
    string1 = "Eight";
}
else if(value.equals("7")){
    string1 = "Seven";
}
else if(value.equals("6")){
    string1 = "Six";
}
else if(value.equals("5")){
    string1 = "Five";
}
else if(value.equals("4")){
    string1 = "Four";
}
else if(value.equals("3")){
    string1 = "Three";
}
else if(value.equals("2")){
    string1 = "Two";
}

if(suite.equalsIgnoreCase("D")){
    string2 = "Diamonds";
}
else if(suite.equalsIgnoreCase("H")){
    string2 = "Hearts";
}
else if(suite.equalsIgnoreCase("S")){
    string2 = "Spades";
}
else if(suite.equalsIgnoreCase("C")){
    string2 = "Clubs";
}

return string1 + " of " + string2;         
}
}

感谢您的帮助。

【问题讨论】:

  • 从“公共类卡”中删除公共关键字
  • 另外看看使用switch语句而不是多个else if。

标签: java methods substring


【解决方案1】:

如果两个类都在同一个源文件中,它们就不能都是公共的。将 Card 类移动到 Card.java 或使其不公开。

如果这些类不在同一个文件中,它们应该属于同一个包,或者您应该导入 Card 类以便在 CardDescription 类中使用它。

除此之外,您的代码可以正常工作。

【讨论】:

  • 我确实把它带到了 Card.java,但它仍然无法工作。问题似乎出在这一行 Card c1 = new Card("KS");
  • @SamerBaslan CardDescription 类呢?是在CardDescription.java吗?
  • @SamerBaslan 我尝试了您发布的代码,并且成功了,所以我能看到的唯一潜在问题是类的位置。
  • 是的,它在 CardDescription.java 我也试过让它们不公开,不会编译错误是:线程“main”中的异常 java.lang.RuntimeException:无法编译的源代码 - 找不到符号符号:类卡位置:类 carddescription.CardDescription 在 carddescription.CardDescription.main(CardDescription.java:19) Java 结果:1
  • @SamerBaslan 两个类都在同一个包中吗?
猜你喜欢
  • 2011-07-23
  • 2015-05-23
  • 2012-01-19
  • 1970-01-01
  • 2011-01-27
  • 1970-01-01
  • 2020-08-08
  • 2015-02-05
  • 1970-01-01
相关资源
最近更新 更多