I have a lab that I have to do for my computer class and i have an error that I can't seem to figure out. I get the error on the first if statement, if(something.indexOf(x) = "a"). I want to change the other if statements to be of that form.
The error I get is:
unexpected type
required:variable: found; value
Scanner in = new Scanner(System.in);
String[] input = new String[1000];
String[] output = new String[1000];
int x = 0;// All purpose counter
int y = 0;//Second purpose counter
boolean ends = false;
boolean starts = false;
/**
* This method is supposed to take the dna array and create an rna array from it to return
* to the main method wherever this method is called.
*
* #param String[] input The array that contains the dna sequence
* #return String[] output The array that contains the mRNA we just created in this method
*/
public void makeRNA()
{
System.out.println("Enter a simple DNA Sequence, make sure the amount of variables are a multiple of 3.");
String something = in.nextLine();
while(x < 1000)
{
if(something.indexOf(x) = "a")
{
output[x] = "u";
}
else if(input[x] == "c")
{
output[x] = "g";
}
else if(input[x] == "g")
{
output[x] = "c";
}
else if(input[x] == "t")
{
output[x] = "a";
}
x++;
}
for(x = 0 ; x < 1000; x++)
{
System.out.println(output[x]);
}
}
The problem seems to be here: if(something.indexOf(x) = "a")
To get the character at index x you need to use charAt().
Instead of the assignment operator, you need to use == (comparison operator).
Compare it with a char and not a String, because charAt() returns a char. So change "a" to 'a'.
So your statement should finally look like:
if(something.charAt(x) == 'a')
if(something.indexOf(x) = "a") ,= is assignment operator. you need == operator in your if statement unless the assignment results in a boolean.
also, indexOf() returns an int ,so you can't use == with "a", use equals() for string comparison.
java if statement doesn't work like c or c++.
Ramanlfc is correct in saying use == instead of = because just a single equals sign is an assignment operator.
However, I'm not sure your IF statements are doing what you want them to do. The indexOf() method returns an integer and you're trying to compare it to a string, an object, using == (equals). If you want to compare two strings use the .Equals() method. You cannot use == on an object, which is what a string is. However, you can use == on chars because they are primitive types. To specify a char use single quotes not double quotes (double quotes specifies a string which is currently how you have your if statement set up). I'm assuming java will use the hex value of the char to compare it to a number. Once again, I'm not sure what you're trying to achieve, but just some helpful advice!
I'm assuming you want something like the following:
if(stringMsg.charAt(INDEXVALUE) == 'a')
This gets the character at the specified value in the string and checks to see if it is the same (equal to) the char a. Remember characters in a string are number 0 to (length - 1).
The problem is this line of code:
if(something.indexOf(x) = "a") // it should be "==" instead of "="
The correct code is:
if(something.indexOf(x) == "a")
Please note that if(something.indexOf(x) = "a") will always return true in java.
Related
A class words defines a recursive function to perform string related operations. The class details
are given below:
Class name : words
Data members/instance variables
text : to store string.
w : integer variable to store total words.
Member functions/methods
words( ) : constructor to store blank to string and 0 to integer data.
void Accept( ) : to read a sentence in text. Note that the sentence may contain more
than one blank space between words.
int FindWords(int) : to count total number of words present in text using Recursive
Technique and store in ‘w’ and return.
void Result( ) : to display the original string. Print total number of words stored in
‘w’ by invoking the recursive function.
I tried this code
public static int CountWords(String str) {
int c = 0;
int i = str.indexOf(" ");
if (str.isEmpty()) {
return 0;
}else
if (i == str.indexOf(" ")) {
return c++;
}
//str.substring(0,str.indexOf(" ")-1);
c++;
return c + CountWords(str.substring(i + 1));
}
but i need to return an integer value and i am confused with that..
In your code, the last return statement is inaccessible. Reason: you have put an if-else block and have put return in both the cases. So the function actually gets returned from the if-else block itself (within else, the condition of if is always true since you assigned the very value i.e. str.indexOf(" ")).
I have written down the code according to the question you gave above...
public int findWords(int i){
if(i > text.lastIndexOf(" "))
return 1;
i = text.substring(i).indexOf(" ") + i;
if(i < 0)
return 1;
if(text.substring(i).equals(null))
return 0;
return( findWords(i+1) + 1);
}
Hope you find it well working.
Your function already is returning a integer, it just happens to always be 0.
This is due to
else if (i == str.indexOf(" ")) {
return c++;
}
Always being true and c++ only updating after the return statement was passed.
This happens because you already set i to be the indexOf(" ") and due to the implementation of incrementation using int++. Also, keep in mind hat you need to increase the number of words by 2 here, since you're ending the function between two words.
Therefore, use this instead:
else if (i == str.lastIndexOf(" ")) {
return c+2;
}
You should see that now the function is returning the correct amount of words.
Whenever I run my code it returns this error message:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(Unknown Source)
at codes.Main.main(Main.java:10)
Here is my code:
package codes;
public class Main {
public static void main(String[] args) {
String cord1 = "Name: x=23 y=60 z= 600";
String cord2 = "Name: x=200 y=20 z= 300";
int c1 = cord1.length();
String mychar = String.valueOf("cord1".charAt(0));
for (int a = 0; a < c1; a++){
mychar = String.valueOf("cord1".charAt(a));
if (mychar == ":"){
break;
}else{
cord1.substring(a);
}
}
}
}
There are multiple things wrong in your code..
mychar == ":" should be mychar.equals(":") instead. Since Strings are immutable, we need to use the .equals to compare them instead of == (<- this checks if the references are equal instead of the String-values).
"cord1".charAt should be your variable cord1.charAt.. By using "cord1" you basically create a new String with the value cord1.
cord1.substring(a); doesn't change the cord1 value, but returns a new String. So you'll have to save this String result, or print it, and then stop the loop with a break.
Using cord1 = cord1.substring(a) would shorten the String itself. Since you still loop in the range [0, c1) where c1 was the original String, we would still get a StringIndexOutOfBoundsException. Instead, you don't need the else-case and need both the cord1 = cord1.substring(a) and break inside the if-case. (Also, I assume you want to remove the : itself as well, so you'll have to use .substring(a+1) instead.)
Also, why use String.valueOf( char ) instead of just using the char themselves? Not really a requirement, but the String.valueOf is kinda redundant here, and makes the code less readable.
Putting it all together:
public class Main {
public static void main(String[] args) {
String cord1 = "Name: x=23 y=60 z= 600";
System.out.println("cord1 before:\t" + cord1);
int c1 = cord1.length();
char mychar = cord1.charAt(0);
for (int a = 0; a < c1; a++){
mychar = cord1.charAt(a);
if (mychar == ':'){
cord1 = cord1.substring(a+1);
break;
}
}
System.out.println("cord1 after:\t" + cord1);
}
}
Which will result in cord1 having the value " x=23 y=60 z= 600" (note the leading space) in the end.
Try it online.
Here is a much simpler alternative with the same result:
String cord1 = "Name: x=23 y=60 z= 600";
String cord1ExcludingName = cord1.replaceFirst("^.*:","");
Try it online.
^ : Only look at the start of the String for:
.* : Zero or more of any character,
: : followed by a `:`
Which will be replaced with "" (an empty String), so they're basically removed.
Use equals instead of "=="
Like this
if (mychar.equals(":")){
break;
You need to use equals method because you are working with a string. Whenever you work with string u must compare them with the method equals.
If you used
char myChar = .....
Your code would work. You can compare chars with "=="
String.valueOf("cord1".charAt(0)) means you are looking into the 0th character of string "cord1" which has a highest index of 4, that is why it is giving out of bound exception at 5.
What you have to do is String.valueof(cord1.charAt(0)). This will consider the string in the variable cord1.
import java.util.*;
public class prac9
{
public static void main(String[] args){
Scanner scn=new Scanner(System.in);
int count=0;
String x,str=" ";
System.out.println("Regular Expression is (a+b)(ab+ba)*");
System.out.println("Enter a Word: ");
x=scn.nextLine(); //here simple x string type of varible
if(x[0]=="a"|| x[0]=="b") //here x array of string type of varible
{ //prac9.java:15: error: array
// required,but String found
for(int i=1; i<x.length(); i++)
{
str+=x[i];
if((i%2==0)==true)
{
if(str=="ab" || str=="ba")
{
count=count+2;
str=" ";
}
}
}
if((count+1)==(x.length())){
System.out.println("Acceptable");
}
else{
System.out.println("Not Acceptable");
}
}
else{
System.out.println("Not Acceptable..");
}
}
Please help me as simply as possible. It gives me an error as I mentioned in above comment. I know what it is saying, but I can't figure out how to convert a String into an array so I can check every single character given by a user.
Actually, this code was written in C++. I just converted it into Java language.
if(x[0]=="a"|| x[0]=="b")
can be changed to:
if(x.startsWith("a") || x.startsWith("b"))
and
str+=x[i];
can be changed to:
str+=x.charAt(i);
and lastly:
if(str=="ab" || str=="ba")
should be changed to
if(str.equals("ab") || str.equals("ba"))
You can access the first character of the string using charAt as follows -
x.charAt(0) == 'a'
since that would return the first character of the string (based of start index = 0)
x is a String, you'd need to convert it to an array of chars, then compare each char with 'a' and 'b'. To do that replace this line of code if(x[0]=="a"|| x[0]=="b") by
char[] x_chars = x.toCharArray();
if (x_chars[0] == 'a' || x_chars[0] == 'b') {
...
}
If one checks the documentation
https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
you can find the method
x.charAt(0)
which is used in java instead of x[0].
Your "x" variable is of String type, not an array. To declare "x" as string array, you should use
String x[] = new String[n]; //here 'n' is number of elements you store in your 'x' array
Also if you don't know how many elements can be are to be included in array, that can also grow and shrink based on your requirement you can use "ArrayList " like this;
ArrayList<String> al=new ArrayList<String>();
al.add("J"); //add 'J' as 1st element of 'al'
al.add("a");
al.add("v");
al.add("a");
System.out.println("element at 2nd position: "+al.get(2)); //get 'a'
al.remove(0) //to remove 'J'
.............
The problem is:
Client accounts are filed under a classification system using codes eg MA400. I need a method that will reset the original MA400 to an updated code such as MA400.4. If the new code has 5 characters to which the original is reset then the method returns true. Not the best wording but that is all I have right now.
It hasn't been specified if the characters need to be in the same order, eg.
String str = "abc123";
String newStr = "xyz123abc";
I am assuming they need to be in the same order. So the above strings would only have 3 like characters.
char[]array = str.toCharArray();
char[]array2 = newStr.toCharArray();
I am thinking now to use a compareTo method on the two arrays, but I am not sure how this would work exactly. Perhaps I could use a for loop to stop comparing after the final element in the shortest string but not entirely sure if I can do much with that.
I feel like I am going about this in the wrong way and there is a less complicated way to check for like characters in a string?
From what I understand something like this will work. Remember this will only count unique characters. Order does not matter
public static boolean matchingChar(final String st1, final String st2) {
if(st1 == null || st2 == null || st1.length() < 5 || st2.length() < 5) {
return false;
}
//This is if you wish unique characters to be counted only
//Otherwise you can use simple int count = 0
HashSet<Character> found = new HashSet<Character>();
//found.size() < 5 so the loop break as soon as the condition is met
for(int i = 0; i < st1.length() && found.size() < 5; i++) {
if(st2.indexOf(st1.charAt(i)) != -1) {
found.add(st1.charAt(i));
}
}
return found.size() >= 5;
}
I am completely stumped with this one . . .
If I call the function below with the following:
Search(SearchTextField.getText()); // (Fiberglass was entered)
Search("Fiberglass"); // hardcoded
I get the following results:
Fiberglass 10 Not Here
Fiberglass 10 String found!
Same String is passed with the same length, different results. How can this be?
Yes I've trimmed it on both sides of the == with no luck.
I am loosing my mind, any help would be appreciated.
Test[] array = new Test[3];
array[0] = new RowBoat("Wood", "Oars", 10);
array[1] = new PowerBoat("Fiberglass", "Outboard", 35);
array[2] = new SailBoat("Composite", "Sail", 40);
public void Search(String searchString) {
boolean found = false;
System.out.print(searchString + " " + searchString.length() + " ");
for (int i = 0; i < array.length; i++) {
if (searchString == array[i].getBoatMaterial()) {
found = true;
break;
}
}
if (found) {
System.out.println("String found!");
} else {
System.out.println("Not Here");
}
}
Use the .equals() method when you're comparing Strings. Do not use ==
equals() will compare the actual String content, no matter where the String resides in memory.
if (searchString.equals(array[i].getBoatMaterial())) {
Since String variables are references in Java, when you code
if (searchString == array[i].getBoatMaterial()) {
What you are actually doing is comparing two pointers. It just so happens that when you hardcode the same string in multiple places in your program the compiler reduces it to one instance (since Strings are immutable) and reuses it. This is why using a hardcoded value succeeds, since both pointers point to the same value. However, when the search string is not the same hardcoded "Fiberglass", the two strings are at different locations and the comparison fails. To compare two strings use the String.equals(String) method instead.
Use the String.equals(String other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal.