I was asked for my homework to make a program wherein the user inputs a Roman numerals between 1-10 and outputs the decimal equivalent. Since I'll be getting a string in the input and an integer in the output, I parsed it, but it won't work. Any ideas why?
import java.util.Scanner ;
class Romans {
static Scanner s = new Scanner(System.in) ;
static String val = null ;
public static void main (String [] args)
{
System.out.print ("Enter a roman numeral between I to X: ");
String val = s.nextLine();
int e = Integer.parseInt(val);
}
static int getRoman (int e)
{
if (val = "I"){
System.out.print ("1") ;
}else if (val = "II" ){
System.out.print ("2") ;
}else if (val = "III") {
System.out.print ("3") ;
} else if (val = "IV") {
System.out.print ("4") ;
} else if (val = "V"){
System.out.print ("5");
} else if (val = "VI") {
System.out.print ("6");
} else if (val = "VII") {
System.out.print ("7");
} else if (val = "VIII") {
System.out.print ("8");
} else if (val = "IX") {
System.out.print ("9");
} else if (val = "X") {
System.out.print ("10") ;
}
return val ;
}
}
Two points:
= is the assignment operator, not the equality-testing operator (==)
You shouldn't use == to test for string equality anyway, as it will only test for reference equality; use equals to test whether two string references refer to equal (but potentially distinct) string objects.
Additionally, you're trying to return a String variable as an int, and you're not even calling getRoman...
I think we can tell you that the correct way to compare Strings is using equals().
You're doing assignments, to compare primitive types you've to use ==, to compare String the equals method.
Example:
if (val.equals("I"))
But also val is not present in the method getRoman().
You are trying to parse val as an int, but its not, its a character.
For such a small sample of chars, its probably easiest to simply create a lookup table, index it on the char.
Are you getting any errors?
In your code, you never call the getRoman function. Also, you're using the assignment operator = instead of the comparison operator "I".equals(val) for example.
String comparsion should be done with equals(String str) method instead of == comparison.
PS. You have = instead of == anyway.
The following statement is an assignment:
val = "I"
That is definitely not what you want to do here.
A comparison is done with the double equals, but double equals (==) compares references but you do not want to do that here either.
You want to use the equals method.
if (val.equals("I")) ...
Make those change everywhere and see how it works for you.
ACtually your main trouble comes from string comparison. In java, = is meant to assign values to variables, == is meant to compare values of primitive types and equals is the way to compare objects, especially for strings.
An alternative to using equals can be to use the JDK internal pool of strings, in this case, you could use == as a comparator.
In your case of parsing roman language numbers, you could also consider using a hashmap to store and retrieve effectively the parsed values of numbers. If you have thousands of comparisons like this to make, then go for identityhashmap.
And last, if you want to do real parsing for all roman numbers, not only the first ones, then you should considering using an automata, i.e. a state machine to parse numbers in a somewhat recursive way, that would be the more efficient model to apply to your problem.
The last 2 remarks are more oriented towards software algorithms, the first two ones are more oriented towards java syntax. You should start to know the syntax before going higher level optimizations.
Regards,
Stéphane
Aside from what was said above about how your String comparison should use the equals( ... ) function - for example,
if ( val.equals("VII") )
you also need to provide a return value for your function called getRoman. This function was declared as a function that returns an integer value to the caller, but in the implementation that you have provided, there are no return values (only System.out.println( ... )).
Also, you aren't inputting the correct parameter type - from what it looks like, your function is checking a String to see if it is a certain Roman numeral. So the correct function header would look like this:
public static int getRoman(String val)
Also, make sure you are actually calling this function in your main() - from what it looks like right now, you aren't even using the getRoman() function.
Hope this helps!
Related
I am getting the "Must be an array type but it resolved to string" error in my code. It also says that i (in the code below) cannot be resolved to a variable which I don't get.
public class DNAcgcount{
public double ratio(String dna){
int count=0;
for (int i=0;i<dna.length();i++);
if (dna[i]== "c"){
count+= 1;
if (dna[i]=="g"){
count+=1;
double answer = count/dna.length();
return answer;
}
}
}
}
Could you guys please help me figure out where the problem lies? I'm new to coding in Java so I am not entirely comfortable with the format yet.
Thanks a lot,
Junaid
You cannot access a String's character using subscript (dna[i]). Use charAt instead:
dna.charAt(i) == 'c'
Also, "c" is a String, 'c' is a char.
One more thing - integer division ( e.g. int_a / int_b ) results in an int, and so you lose accuracy, instead - cast one of the ints to double:
double answer = count/(double)dna.length();
Use {} to define the scope of the loop. Also, as others already pointed out, use charAt instead of [] and use ' for characters, and use floating point division for the ratio.
for (int i = 0; i < dna.length(); i++) {
if (dna.charAt(i) == 'c') {
count += 1;
}
if (dna.charAt(i) == 'g') {
count += 1;
}
}
Or a bit shorter, use || to or the two clauses together
if (dna.charAt(i) == 'c' || dna.charAt(i) == 'g') {
count += 1;
}
I think you are currently a bit weak at brackets , this is what i understood from your code and corrected it;
public class DNAcgcount{
public double ratio(String dna){
int count=0;
for (int i=0;i<dna.length();i++){
if (dna.charAt(i)== 'c')
count+= 1;
if (dna.charAt(i)=='g')
count+=1;
}
double answer = count/(double)dna.length();
return answer;
}
}
After if we have to close the brackets when what you want in if is finished . I think you wanted count to be the number of time c or g is present in the dna.
You also did some other mistakes like you have to use 'c' and 'g' instead of "c" and "g" if you are using .charAt(i) because it will be treated like a character and then only you can compare .
You may view this link
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
and you may also have a look at works you can do with string like charAt.
It seems like that you have a few problems with the main syntax of basic java functions like loops or if-else statement. Click here for a good tutorial on these.
You must correct your for-loop and your if-statement:
for(int i=0;i<dna.length();i++){
if(...){
...;
}
if(...){
...;
}
}
Now you wont get the Cant be resolved to a variable... exception.
Second thing is the usage of your string. You have to use it like this:
for(int i=0;i<dna.length();i++){
if(dna.charAt(i) == 'c'){
count += 1;
}
if(dna.charAt(i) == 'g'){
count += 1;
}
}
Now all your exceptions should be eleminated.
Your problem is with syntax dna[i], dna is a string and you access it as it would be an array by []. Use dna.charAt(i); instead.
You using String incorrectly. Instead of accessing via [] use dna.charAt(i).
Altough logically a string is an array of characters in Java a String type is a class (which means it has attributes and methods) and not a typical array.
And if you want to compare a single character to another enclose it with '' instead of "":
if (dna.charAt(i) == 'c')
.
.
There are two errors:
count should be double or should be casted do double answer = (double)count / dna.length();
and as mentioned above you should replace dna[i] with dna.charAt(i)
I've got this code:
Scanner inputScanner = new Scanner(System.in);
String word;
do
{
word = inputScanner.next();
System.out.println(word + ": " + dict.contains(word));
}
while (word != "#");
It's pretty straight-forward, but the loop is NOT terminating after receiving a # input from the user. I've seen other people complaining that Scanner is error-prone and can give unexpected results, but that doesn't explain why dict.contains(word) functions perfectly while the while (word != "#") condition is not doing a thing...
What gives?
You are using == to compare strings; use String#equals instead.
...
while (!word.equals("#"));
You need to use the .equals() method rather than the == operation. "==" operations are used to compare primitives like boolean, int, long, ect and references.
A String is an object so Java assumes you want to compare the reference value rather than the value contained in the string. Also remember that you cannot compare Long, Integer, Double ect with the == operator either.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String is not equal to string?
I'm new to java and I can't figure out what's wrong with this code block.
I know the array isn't null I'm testing it elsewhere. Maybe there is a syntax problem I'm used to program in c#.
Scanner input = new Scanner(System.in);
System.out.println("Enter ID :");
String employeeId = input.nextLine();
int index = -1;
for(int i = 0 ; i < employeeCounter ; i++)
{
if(employeeId == employeeNumber[i])
{
index = i;
}
}
if(index == -1)
{
System.out.println("Invalid");
return;
}
I always get to the 'Invalid' part. Any idea why ?
Thanks in advance
employeeNumber[0] is "12345"
employeeId is "12345"
but I can,t get into the first if statement although employeeId IS equal to employeeNumber[0].
Don't compare strings with ==.
Use
if (string1.equals("other")) {
// they match
}
Compare strings like that
if(employeeId.equals(employeeNumber[i]) {
}
As others have pointed - full code will be helpful, but my guess would be this line of the code:
if(employeeId == employeeNumber[i])
You don't compare 2 strings by using ==. Use equals() or equalsIgnoreCase() instead. == only checks for object equality i.e. are employeeId and employeeNumber referencing to the same object in memory. So, for objects always use the equals() method..for Strings you can also use equalsIgnoreCase() for a case insensitive match. == should be used on primitive types like int, long etc.
When you use == with two string, it compares pointer addresses
You should use firststring.equals(secondstring) in order to compare two strings
Use equals() method to compare Strings
if(employeeId.equals(employeeNumber[i])){}
When you compare strings, use
String1.equals(String2);
This should give you the result
"==" checks whether the reference for two objects are same. But equals() method checks whether the content is same or different.
public static int seqSearch(int numRecords, String[] stuName,
double[] stuGpa, String nameKey, double gpaKey)
for(int i = 0; i < numRecords; i++)
if(stuName[i] == nameKey && stuGpa[i] == gpaKey)
return i;
return -1;
So, how would I used an if statement to control this? I'm doing sequential search to find if the name is found in the array and if the gpa is in the array, then it should return the position it was found in (i). But, all it does do is return -1 and print out that none were found.
You have two separate problems here:
You should be comparing strings using the equals() method (or one of it's kin) - otherwise you are comparing whether two strings are the same reference (instance) rather than equivalent sequences of characters.
You should avoid comparing doubles using == as equality for doubles is more nuanced. Check out this paper for more information about why.
See this question about why using == for floating point comparison is a bad idea in java.
Aside from that, I would also mention that your implementation makes the assumption that both stuName and stuGpa are arrays of the same length. This could easily not be the case ... and is probably something worth asserting before you begin iterating over the arrays.
Strings must be compared with .equals in Java, not ==.
if(stuName[i].equals (nameKey) && stuGpa[i] == gpaKey)
You probably want
if (stuName[i].equals(nameKey) && stuGpa[i].equals(gpaKey))
if(stuName[i] == nameKey is unlikely to be right, you are comparing object identities not string content. Try if(stuName[i].equals(nameKey)
You are comparing two Strings.
Strings are immutable.
Please use "equalsIgnoreCase()" or "equals()" to compare Strings
See examples here
http://www.java-samples.com/showtutorial.php?tutorialid=224
An essential problem is that
stuName[i] == nameKey
Is only comparing whether the objects are the same String Object in memory.
You actually want to use nameKey.equals(stuName[i]), to compare the actual string values.
And you might want to use .equalsIgnoreCase for case insensitivity.
The following is correct for the if statement. stuName[i] is a string so compare with .equals. stuGpa[i] is a double so use ==.
if(stuName[i].equals(nameKey_ && stuGpa[i] == gpaKey)
Your problem is not the conditional if statement, but the conditional operator ==. == refers to the pointer value of the object where as the .equals method returns something computed by the object.
Like everyone has said before, switch your == to .equals in this next line:
public static int seqSearch(int numRecords, String[] stuName,
double[] stuGpa, String nameKey, double gpaKey)
for(int i = 0; i < numRecords; i++)
if(stuName[i].equals(nameKey) && stuGpa[i] == gpaKey)
return i;
return -1;
To actually answer the question about the control of the if statement...
I believe what you're doing is fine with the the multiple return statements, BUT...
I personally prefer one entry point and only one exit point for my methods. It always feels dirty to me having multiple exit points.
So, I would consider the following code instead:
public static int seqSearch(int numRecords, String[] stuName, double[] stuGpa, String nameKey, double gpaKey)
int value = -1;
for(int i = 0; i < numRecords; i++) { // Don't forget your braces, they aren't required, but wait until you add a newline and forget to add them...
if(some.boolean().equals(comparison.here())) {
value = i;
break;
}
}
return value;
}
Best of Luck.
I have an array in containing numbers that represent cable sizes (1, 1.5, 2.5, etc), stored as strings.
In my program, the array is loaded into a spinner, which is working fine.
However, when the item is selected and stored in a variable, I want to check what string was selected, and set another numerical variable to 2.5 so I can do a calculation later in the program.
I tried the following:
if (conductorSize = "1" ) {conCsa = 1;}
else if (conductorSize = "1.5") {conCsa = 1.5;}
conductorSize being the variable holding the selected string, and conCsa being the variable
set to a numerical variable for calculation.
The compiler says that I cannot convert a string to boolean. What's happening?
If you are doing string comparisons, use .equals()
Example taken from here:
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT <<<<<<<<<<<<< Use this.
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
As Ed S. points out you are using the assignment operator. However since you are comparing a String you need to use the equals method.
if ("1".equals(conductorSize)) {conCsa = 1;}
else if ("1.5".equals(conductorSize)) {conCsa = 1.5;}
Alternatively, you could just create a new float from your String:
float conCsa;
try {
conCsa = Float.parseFloat(conductorSize);
}catch(NumberFormatException e){
conCsa = 0.0f; //set to a default value
}
It looks like what you're trying to do might better be expressed in this way:
conCsa = Double.parseDouble(conductorSize);
In general you need to use the .equals() method.
If performance is extremely important and you are comparing against string literals, take a look at String.intern(). It'll allow you to do super-fast == comparisons and avoid a full character-by-character scan as in .equals().
Performance would have to be really, really important though, to justify such a non-standard approach.
When you have cable sizes which are constants, you need to use Enums , which will help you in reducing no of if condition comparisons.