473,585 Members | 2,512 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

gcd method

19 New Member
I'm very new to Java and I was looking for some help on this particular problem.

I need to create a method that takes a String as a parameter and returns "true" if the parameter is the letter Y or the letter N (in either upper or lower case), or false otherwise.

Most of the methods we've been working on are numbers (integers mostly) not strings, so this one confuses me quite a bit. How do you make the computer look for a certain character like y, Y, n, N. I don't want to declare them as variables, I just want Java to see them as letters.

I have:
public static boolean isYorN(String str)
{
boolean character;
switch (character)
{
case 'y':
character = true;
return true;
break;

case 'Y':
character = true;
return true;
break;

case 'n':
character = true;
return true;
break;

case 'N':
character = true;
return true;
break;

default:
character = false;
return false;

}
}
}

I think a switch case is the best method, but I'm missing something about naming because all my compiling errors are telling me that I have incompatible types (i.e. found: boolean, required: int).

Thank you in advance for any help.
May 23 '07 #1
11 3251
sicarie
4,677 Recognized Expert Moderator Specialist
I believe the errors are coming from the fact that you are using 'Y', 'y', 'N', and 'n' as the cases, when you tell the switch statement (swtich (character)) that it should expect a boolean - either a true or a false.

I would recommend using the .equals() function in the String class. That returns a boolean, so you can resolve it as being either true or false (use the fact that it will return as either true or false).

(And in future posts, please use [code ] and [/code ] around your code - only without the spaces at the end, it really helps with readability. Thanks!)
May 23 '07 #2
nomad
664 Recognized Expert Contributor
I believe the errors are coming from the fact that you are using 'Y', 'y', 'N', and 'n' as the cases, when you tell the switch statement (swtich (character)) that it should expect a boolean - either a true or a false.

I would recommend using the .equals() function in the String class. That returns a boolean, so you can resolve it as being either true or false (use the fact that it will return as either true or false).

(And in future posts, please use [code ] and [/code ] around your code - only without the spaces at the end, it really helps with readability. Thanks!)

Can PvtBillPilgrim use scanner and do this
if(kbd.equalsIg noreCase("Y"));

then use the switch or if statement
...
May 23 '07 #3
PvtBillPilgrim
19 New Member
I am a beginner programmer in Java. Just started learning the past few weeks.

I'm taking a class and need to create a method that finds the greatest common divisor of two integers. I can assume that both are positive, but I cannot use the Euclidean Algorithm.

I'm sort of lost, but I think I'm on the right track, although this may look confusing:
Expand|Select|Wrap|Line Numbers
  1. public static int gcd(int a, int c)
  2. {
  3. int gcd;
  4. int attempt;
  5. if (a > c)
  6. {
  7.  if (a % c == 0)
  8. {
  9. gcd = c;
  10. return gcd;
  11. }
  12. else
  13. {
  14. for (attempt = c; attempt = 1; attempt--)
  15. do
  16. {
  17. if (c % attempt == 0 && a % attempt == 0)
  18. {
  19. gcd = attempt;
  20. return attempt;
  21. }
  22. }
  23. while (c % attempt != 0 || a % attempt == 0);
  24. }
  25. }
  26.  
And then I basically copied the code with an else statement if c > a.

I'm sure there are a lot of mistakes. Could someone just point them out and offer a simpler way of doing it (possibly without using the Euclidean Algorithm)?

Thanks.
Michael
May 24 '07 #4
JosAH
11,448 Recognized Expert MVP
Hint: for any two (positive) numbers a and c the gcd is the largest number in the
range [1 ... min(a, c) ]. Only a single for loop could do the job. There's no need
to duplicate code for a < c or c < a and there's also no need for two nested loops.

kind regards,

Jos
May 24 '07 #5
r035198x
13,262 MVP

....I think a switch case is the best method...
I'm afraid you're wrong there and that's where you missed it. Just an if else will do it.

big hint:
Expand|Select|Wrap|Line Numbers
  1.  if(str.equalsIgnoreCase("y")) ....
May 24 '07 #6
rsrinivasan
221 New Member
I am a beginner programmer in Java. Just started learning the past few weeks.

I'm taking a class and need to create a method that finds the greatest common divisor of two integers. I can assume that both are positive, but I cannot use the Euclidean Algorithm.

I'm sort of lost, but I think I'm on the right track, although this may look confusing:
Expand|Select|Wrap|Line Numbers
  1. public static int gcd(int a, int c)
  2. {
  3. int gcd;
  4. int attempt;
  5. if (a > c)
  6. {
  7.  if (a % c == 0)
  8. {
  9. gcd = c;
  10. return gcd;
  11. }
  12. else
  13. {
  14. for (attempt = c; attempt = 1; attempt--)
  15. do
  16. {
  17. if (c % attempt == 0 && a % attempt == 0)
  18. {
  19. gcd = attempt;
  20. return attempt;
  21. }
  22. }
  23. while (c % attempt != 0 || a % attempt == 0);
  24. }
  25. }
  26.  
And then I basically copied the code with an else statement if c > a.

I'm sure there are a lot of mistakes. Could someone just point them out and offer a simpler way of doing it (possibly without using the Euclidean Algorithm)?

Thanks.
Michael
Hi,
I modified ur function to find GCD of two numbers.
Try this function repl ur feedback

[edit] Don't supply full spoonfed code; it's not allowed in this forum. Thanks;

Thanks,

Srinivas r.
May 24 '07 #7
PvtBillPilgrim
19 New Member
OK. I think this is a lot better. It compiles and makes sense to me at least. However, it doesn't work properly for more difficult integers like 20, 30. Can anyone spot the problem (as I said nothing wrong with compiling, just doesn't work logically). As I said before, I can't use the Euclidean Algorithm, so I basically had to write the simplest program to find gcd.

Expand|Select|Wrap|Line Numbers
  1. public static int gcd(int a, int b)
  2. {
  3. int gcd;
  4. if (a > b && a % b == 0)
  5. {
  6. gcd = b;
  7. return gcd;
  8. }
  9. else if (b > a && b % a == 0)
  10. {
  11. gcd = a;
  12. return gcd;
  13. }
  14. else if (a > b && a % b != 0)
  15. {
  16. int count = b;
  17. do
  18. {
  19. count = count - 1;
  20. }
  21. while (b % count != 0 && a % count != 0);
  22. gcd = count;
  23. return gcd;
  24. }
  25. else if (b > a && b % a != 0)
  26. {
  27. int count = a;
  28. do
  29. {
  30. count = count - 1;
  31. }
  32. while (b % count != 0 && a % count != 0);
  33. gcd = count;
  34. return gcd;
  35. }
  36. else
  37. {
  38. gcd = a;
  39. return gcd;
  40. }
  41. }
  42.  
May 24 '07 #8
blazedaces
284 Contributor
I'm not 100% sure about the forum guidelines, but I'm pretty sure you should post this as a new thread/topic because it is indeed a ... new... topic. Anyways, may I ask why you're using subtraction and not mod? What do you mean you can't use the euclidean algorithm?

Ok, you're subtracting by one each time... why? Why not subtract by intervals of the smaller number (original euclidean algorithm) or use the mod method?

You realize there's a Math.max(int a, int b) method?

I don't know what is logically wrong in your code, but you don't have a good base of an idea, try rewriting and also tell us what exactly outputs when you have higher integers.

-blazed
May 24 '07 #9
astolpho
3 New Member
I'm afraid you're wrong there and that's where you missed it. Just an if else will do it.

big hint:
Expand|Select|Wrap|Line Numbers
  1.  if(str.equalsIgnoreCase("y")) ....
perhaps simply

return str.equalsIgnor eCase("y") || str.equalsIgnor eCase("n");
May 24 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

11
3609
by: Dave Rahardja | last post by:
OK, so I've gotten into a philosophical disagreement with my colleague at work. He is a proponent of the Template Method pattern, i.e.: class foo { public: void bar() { do_bar(); } protected: virtual void do_bar() {} };
5
15352
by: Chris | last post by:
Hi I have a scenario where I've created another AppDomain to dynamically load a DLL(s) into. In this newly loaded DLL I want to call a static method on a class. The problem arise is that I have the same class/static method definition statictly linked to my EXE and when I call InvokeMember(...), even though I got the Type from the new AppDomain,...
4
2895
by: daniel.w.gelder | last post by:
I wrote a template class that takes a function prototype and lets you store and call a C-level function, like this: inline string SampleFunction(int, bool) {..} functor<string (int, bool)> myFunctor = SampleFunction; string result = myFunctor(7, true); Works great thanks to the help from this group. Here's the guts so far for two-arity:
7
1740
by: greenflame | last post by:
I am trying to make a matrix object. I have given it some properites. I am trying to add a method. When I call the method by Test.showDims(...) I want to only enter one input, that is the method by which to do it. As you can see from the object definition that it corresponds to a function that takes two inputs. When I try to run the script it...
5
3410
by: Nick Flandry | last post by:
I'm running into an Invalid Cast Exception on an ASP.NET application that runs fine in my development environment (Win2K server running IIS 5) and a test environment (also Win2K server running IIS 5), but fails on IIS 6 running on a Win2003 server. The web uses Pages derived from a custom class I wrote (which itself derives from Page) to...
18
4724
by: JohnR | last post by:
From reading the documentation, this should be a relatively easy thing. I have an arraylist of custom class instances which I want to search with an"indexof" where I'm passing an instance if the class where only the "searched" property has a value. I expected to get the index into the arraylist where I could then get the entire class...
10
3361
by: Mihai Osian | last post by:
Hi everyone, Given the code below, can anyone tell me: a) Is this normal behaviour ? b) If it is, what is the reason behind it ? I would expect the A::method(int) to be inherited by B. Compiler: gcc 4.1, Linux Thanks,
9
5834
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to the static Parse method of the conversion class. if (InValue is string) return T.Parse((string)InValue); else return base.ConvertFrom(context,...
3
1346
by: allendowney | last post by:
Hi All. In a complex inheritance hierarchy, it is sometimes difficult to find where a method is defined. I thought it might be possible to get this info from the method object itself, but it looks like maybe not. Here is the test case I tried: class A(object):
9
1572
by: VK | last post by:
<OT>I am finishing TransModal 0.1 so planning to move it from alpha to beta stage.<OT> Besides that I am planning to write an introductory to inheritance schema currently used in Javascript programming. It will not be a manual of a "proper" way to use OOP inheritance but a compilation so a description of _all_ OOP paradigms that had been used...
0
7908
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7836
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7950
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5710
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5389
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3835
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3863
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2343
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1175
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.