在 Java 中使用位串设置麻烦

发布于 2024-12-27 02:23:03 字数 2086 浏览 0 评论 0原文

public class BitStringOperations3
{

public static void main (String args[])
 {
  Scanner in = new Scanner (System.in);

  int setA = 0;
  int setB = 0;
  int elementsSetA = 0;
  int elementsSetB = 0;


  System.out.println ("How many integers are in set A?");
  elementsSetA = in.nextInt ();
    while (elementsSetA > 9 || elementsSetA < 0)
      {
       System.out.println ("This input is invalid. Please enter a number between 0 and 9 and try again.");
        elementsSetA = in.nextInt();
      }



  System.out.println ("How many integers are in set B?");
  elementsSetB = in.nextInt ();
    while (elementsSetB > 9 || elementsSetB < 0)
      {
       System.out.println ("This input is invalid. Please enter a number between 0 and 9 and try again.");
        elementsSetB = in.nextInt();
      }




    for (int i = 1; i <= elementsSetA; i++)
     {
      System.out.println ("Please enter integer number " + i + " in set A: ");
       setA = add(setA, in.nextInt() );
     }

     for (int i = 1; i <= elementsSetB; i++)
      {
       System.out.println ("Please enter integer number " + i + " in set B: ");
        setB = add(setB, in.nextInt () );
      }








 }


 public static boolean setContainsValue (int set, int value)
 {
boolean setContainsValue = (set & maskForValue) != 0;
return true;
 }


 public static int addValueToSet (int set, int newValue)
 {
 set = set | maskForValue;
 return set;
 }

 public static void printSet (int set, int value)
{
 int mask = 1;
 System.out.print ("{");
  for (int i = 0; i<= 9; i++)
  {
    if(( mask & set ) == 1)
     System.out.print(i + " " );
        int maskForValue = 1 << value;
        set >>= 1; //set = (set >> 1);

  }

  System.out.println ("} ");


}







  }

我在学校作业上遇到了麻烦。我们得到通用集合 U = {0-9}。我必须收集两个集合的用户输入,然后使用位字符串(我们不允许在java中使用Set或HashSet类)来存储集合并对它们执行操作,例如求补、集合A并集B和这样的。我知道如何执行这些操作,但我的代码没有将 A 组和 B 组正确转换到内存中,因此我无法对它们执行任何操作。我们将非常乐意提供帮助!提前致谢。 :)

编辑 1:

好的,我读了你的想法并尝试尽我所能地实现它们,我已经给出了上面的结果。这个计划确实让我走出了舒适区,我非常感谢所有的帮助。

public class BitStringOperations3
{

public static void main (String args[])
 {
  Scanner in = new Scanner (System.in);

  int setA = 0;
  int setB = 0;
  int elementsSetA = 0;
  int elementsSetB = 0;


  System.out.println ("How many integers are in set A?");
  elementsSetA = in.nextInt ();
    while (elementsSetA > 9 || elementsSetA < 0)
      {
       System.out.println ("This input is invalid. Please enter a number between 0 and 9 and try again.");
        elementsSetA = in.nextInt();
      }



  System.out.println ("How many integers are in set B?");
  elementsSetB = in.nextInt ();
    while (elementsSetB > 9 || elementsSetB < 0)
      {
       System.out.println ("This input is invalid. Please enter a number between 0 and 9 and try again.");
        elementsSetB = in.nextInt();
      }




    for (int i = 1; i <= elementsSetA; i++)
     {
      System.out.println ("Please enter integer number " + i + " in set A: ");
       setA = add(setA, in.nextInt() );
     }

     for (int i = 1; i <= elementsSetB; i++)
      {
       System.out.println ("Please enter integer number " + i + " in set B: ");
        setB = add(setB, in.nextInt () );
      }








 }


 public static boolean setContainsValue (int set, int value)
 {
boolean setContainsValue = (set & maskForValue) != 0;
return true;
 }


 public static int addValueToSet (int set, int newValue)
 {
 set = set | maskForValue;
 return set;
 }

 public static void printSet (int set, int value)
{
 int mask = 1;
 System.out.print ("{");
  for (int i = 0; i<= 9; i++)
  {
    if(( mask & set ) == 1)
     System.out.print(i + " " );
        int maskForValue = 1 << value;
        set >>= 1; //set = (set >> 1);

  }

  System.out.println ("} ");


}







  }

I am having trouble with an assignment for school. We are given the universal set U = {0-9}. I have to gather user input for both sets, and then use bit strings (we are not allowed to use the Set or HashSet classes in java) to store the sets and perform operations on them, such as complement, Set A union Set B and such. I know how to do those, but my code does not convert Sets A and B into the memory correctly and therefore, I cannot perform any operations on them. Help will be gladly appreciated! Thanks in advance. :)

Edit 1:

Alright, I read your ideas and tried to implement them as good as I could, and I have given the result above. This program really pushes me out of my comfort zone and I really appreciate all the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一指流沙 2025-01-03 02:23:03

首先,帮自己一个忙并创建辅助方法。然后只集中精力使它们正确:

public static boolean contains(int set, int value) {
   //return true if value bit is 1 in set
}

public static int add(int set, int newValue) {
   //add newValue to set and return it
}

之后您可以更清楚地表达您的逻辑:

if ( contains(set, 1) ) {
   //print 1
}

一些一般提示:

  • 不要使用Math.pow(),因为它是为浮点数而设计的。要获得 2 的整数次方,请使用位移位:

    int maskForValue = 1 <<价值;
    
  • 要检查是否设置了某个位,请找到该位的掩码并使用 &。这会将除您正在检查的位之外的所有位清零。

    boolean setContainsValue = (set & maskForValue) != 0;
    
  • 要在位字段中设置位,请找到该位的掩码并使用|。这确保该位变为1

    <前><代码>设置=设置|值掩码;

编辑

至于您的直接问题,请看一下:

  for (int i = 1; i <= elementsSetB; i++)
  {
     System.out.println ("Please enter integer number " + i + " in set B: ");
     setB = in.nextInt ();
  }

您每次都会覆盖 setAsetB 。最后,setAsetB 将包含用户指定的最后一个值。然后,您执行以下操作:

  for (int i = 0; i <=9; i++)
     setB |= (int)pow(2.0, i-1);

这只是忽略用户的输入并覆盖所有位 0-9(尽管以不安全的方式!)。因此,用户输入的内容当然无关紧要。

摆脱后者的 for 循环,然后像这样存储输入(使用我上面描述的辅助方法):

  for (int i = 1; i <= elementsSetB; i++)
  {
     System.out.println ("Please enter integer number " + i + " in set B: ");
     setB = add(setB, in.nextInt());
  }

编辑 2

您似乎无法理解我对这些“辅助”方法的想法的来源。如果这是您第一次使用带有参数的方法,很抱歉让问题变得模糊。但它们可以让您一次专注于让一项功能正常工作。我将在这里进一步阐述我的意思:

public static boolean setContainsValue(int set, int value) {
   //return true if the bit string (or bit set) represented by the "set" parameter
   //contains the value stored in the "value" parameter
   //see the FIRST and SECOND bullet points above for how to do this
}

public static int addValueToSet(int originalSet, int valueToAdd) {
   //add the value stored in the "valueToAdd" parameter to the set represented by the
   //"originalSet" parameter and return the result
   //see the FIRST and THIRD bullet points above for how to do this.
}

我什至还会为您编写一些测试。至少在以下所有打印结果为 true 之前,上述方法尚未正确实现:

int set = 0;

System.out.println( ! contains(set, 1) ); //make sure set doesn't contain 1

set = addValueToSet(set, 1);
System.out.println( contains(set, 1) ); //make sure set now contains 1
System.out.println( !contains(set, 2) ); //make sure set doesn't contain 2

set = addValueToSet(set, 2);
System.out.println( contains(set, 1) ); //make sure set still contains 1
System.out.println( contains(set, 2) ); //make sure set now contains 2

First of all, do yourself a favour and create helper methods. Then concentrate only on making them correct:

public static boolean contains(int set, int value) {
   //return true if value bit is 1 in set
}

public static int add(int set, int newValue) {
   //add newValue to set and return it
}

Afterwards you can express your logic more clearly:

if ( contains(set, 1) ) {
   //print 1
}

Some general hints:

  • Don't use Math.pow() as that is made for floating-point numbers. To get a power of 2 as an integer, use bit shifting:

    int maskForValue = 1 << value;
    
  • To check if a certain bit is set, find the mask for that bit and use &. This zeros out all bits except for the bit you're checking.

    boolean setContainsValue = (set & maskForValue) != 0;
    
  • To set a bit in a bit field, find the mask for that bit and use |. This ensures that that bit becomes 1.

    set = set | maskForValue;
    

Edit

As to your direct problem, take a look at this:

  for (int i = 1; i <= elementsSetB; i++)
  {
     System.out.println ("Please enter integer number " + i + " in set B: ");
     setB = in.nextInt ();
  }

You're overwriting setA and setB every time. In the end, setA and setB will contain the last value the user specified. Then later, you do this:

  for (int i = 0; i <=9; i++)
     setB |= (int)pow(2.0, i-1);

Which just ignores the user's input and overwrites all bits 0-9 (though in an unsafe way!). So of course what the user inputs is irrelevant.

Get rid of the latter for loops and then store the input like this (using the helper methods I described above):

  for (int i = 1; i <= elementsSetB; i++)
  {
     System.out.println ("Please enter integer number " + i + " in set B: ");
     setB = add(setB, in.nextInt());
  }

Edit 2

You seem to be having problems understanding where I'm coming from with my idea of these "helper" methods. If this is the first time you've worked with methods that have parameters, sorry for clouding up the issue. But they allow you to focus on getting one piece of functionality working at a time. I'll expand on what I mean more here:

public static boolean setContainsValue(int set, int value) {
   //return true if the bit string (or bit set) represented by the "set" parameter
   //contains the value stored in the "value" parameter
   //see the FIRST and SECOND bullet points above for how to do this
}

public static int addValueToSet(int originalSet, int valueToAdd) {
   //add the value stored in the "valueToAdd" parameter to the set represented by the
   //"originalSet" parameter and return the result
   //see the FIRST and THIRD bullet points above for how to do this.
}

I'll even write some tests for you too. The methods above haven't been implemented properly until at least all of the following print true:

int set = 0;

System.out.println( ! contains(set, 1) ); //make sure set doesn't contain 1

set = addValueToSet(set, 1);
System.out.println( contains(set, 1) ); //make sure set now contains 1
System.out.println( !contains(set, 2) ); //make sure set doesn't contain 2

set = addValueToSet(set, 2);
System.out.println( contains(set, 1) ); //make sure set still contains 1
System.out.println( contains(set, 2) ); //make sure set now contains 2
如果没有 2025-01-03 02:23:03

首先,您需要一个类(这是面向对象编程,对吧?)来包含“DigitSet”。

public DigitSet {

   private BitSet digits;

   public DigitSet() {
     // digits contains one bit for each digit
     digits = new BitSet(10);
   }

   ... rest of DigitSet code goes here, like ...
   /**
    * Check if this set contains a particular digit.
    */
   public boolean contains(int value) {
     // check to see if value is a valid input (0-9)
     // look in digits to see if the "right" bit is set.
   }

   public void set(int value) {
     // check to see if value is a valid input (0-9)
     // set the "right" bit in digits to 1.
   }

   public void clear(int value) {
     // check to see if value is a valid input (0-9)
     // set the "right" bit in digits to 0.         
   }

   public DigitSet union(DigitSet other) {
     // construct a "new" output DigitSet.
     // Walk through all of the digits in "this" set
       // if a digit is set in this set, set it in the output set.
     // Walk through all of the digits in the "other" set
       // if a digit is set in the other set, set it in the output set.
   }

   public String toString() {
     // return a display string based on the set "digit" bits
   }

}

然后剩下的就是输入处理和“执行操作”

public static void main(String[] args) {
  DigitSet first = new DigitSet();
  // read in the values for the first digit set, for each value
    // set the digit in first like so
    first.set(value);
  DigitSet second = new DigitSet();
  // read in the values for the second digit set, for each value
    second.set(value);

  DigitSet result = first.union(second);
  System.out.println("Result: " + result.toString());

}

First, you need a class (this is object-oriented programming, right?) to contain the "DigitSet".

public DigitSet {

   private BitSet digits;

   public DigitSet() {
     // digits contains one bit for each digit
     digits = new BitSet(10);
   }

   ... rest of DigitSet code goes here, like ...
   /**
    * Check if this set contains a particular digit.
    */
   public boolean contains(int value) {
     // check to see if value is a valid input (0-9)
     // look in digits to see if the "right" bit is set.
   }

   public void set(int value) {
     // check to see if value is a valid input (0-9)
     // set the "right" bit in digits to 1.
   }

   public void clear(int value) {
     // check to see if value is a valid input (0-9)
     // set the "right" bit in digits to 0.         
   }

   public DigitSet union(DigitSet other) {
     // construct a "new" output DigitSet.
     // Walk through all of the digits in "this" set
       // if a digit is set in this set, set it in the output set.
     // Walk through all of the digits in the "other" set
       // if a digit is set in the other set, set it in the output set.
   }

   public String toString() {
     // return a display string based on the set "digit" bits
   }

}

Then the rest is just input handling and "perform the operation"

public static void main(String[] args) {
  DigitSet first = new DigitSet();
  // read in the values for the first digit set, for each value
    // set the digit in first like so
    first.set(value);
  DigitSet second = new DigitSet();
  // read in the values for the second digit set, for each value
    second.set(value);

  DigitSet result = first.union(second);
  System.out.println("Result: " + result.toString());

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文