setType只存储大写

时间:2013-11-04 19:12:06

标签: java

我正在为我的Java类简介工作一个项目,Public BookOrder类中的一个UML方法如下:

+setType(type:char):void
// accepts (R,r,O,o,P,p,F,f,U,u,N), but stores
// UPPERcase letters. For any other type entered, the value N is stored

由此,我有两个问题:

  1. 以下代码是否有效?

    public class BookOrder
    {
    private String author;      
    private String title;
    private int quantity;
    private double costPerBook;
    private String orderDate;
    private double weight;
    private char type;      //R,O,F,U,N
    
    
    public void setType(char type)
    {
        if (type=r || type=R || type=o || type= O || type= f || type= F || type= u || type= U || type= n || type= N)
            this.type= type;
        else
            this.type= N;
    }
    
  2. 如何让它只存储大写字母?我读到Character.isUpperCase可以工作,但我在课堂上告诉你,你只能做String.toUpperCase,而不是char。

3 个答案:

答案 0 :(得分:0)

替换您的每个条件

type=='r'

由于java使用==来检查相等性,因此需要''来表示字符

答案 1 :(得分:0)

if (type=='r' || type=='R' /*etc etc*/)
{
    if(type < 97) //Upper case
        this.type = type;
    else //Lower case
        this.type = (type - 32);
}

或者...

else
    this.type = ((String.valueOf(type)).toUpperCase()).charAt(0);

这会将type转换为String,将其大写,然后将其转换回char以分配给this.type

答案 2 :(得分:0)

比较事情时你必须小心。比较字符串时,==运算符检查参考值。使用Strings.equals函数是一个更安全的选择(如果你被允许,或者自己创建)。

import java.util.*;

public class Main{

    public static String setType(String type)
    {
        if (type.equals("r") || type.equals("R") || type.equals("o") || type.equals("O") || type.equals("f") || type.equals("F") || type.equals("u") || type.equals("U") || type.equals("n") || type.equals("N"))
            type=type;
        else
            type="N";

        return type;
    }


   public static void main(String [] args){
    System.out.println("Try different stuff");
    System.out.printf("%s\n",setType(args[0]));
   } 
}

在这个例子中,我从命令行中获取参数,然后将它们与指定值进行比较。阅读java函数文档可能会有所帮助:http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

相关问题