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'
.............
Related
I am writing a hangman program and one of the requirements to a hangman game is preventing the user from entering the same letter twice.
I have written the code for that, but the problem is every time I enter a letter it says it is already entered. I need to only say it when it is entered the second time. You guys have any suggestions? I've been trying to fix this for the past few hours, I figured I could ask on here to find some help. I already looked at another Stackoverflow question regarding something similar to this but all those solutions have the same result.
In Java, how can I determine if a char array contains a particular character?
I've tried something like this but it won't work either:
boolean contains = false;
for (char c : store) {
if (c == character) {
System.out.println("Already Entered");
contains = true;
break;
}
}
if (contains) {
// loop to top
continue;
}
SECOND CLASS-
public void hangman(String word, int life) {
KeyboardReader reader = new KeyboardReader();
char[] letter = new char[word.length()];
char[] store = new char[word.length()];
String guess;
int i = 0, tries = 0, incorrect = 0, count = 1, v = 0;
while (i < word.length()) {
letter[i] = '-';
I would just use the String.contains() method:
String aString = "abc";
char aChar = 'a';
return aString.contains(aChar + "");
To keep track of guessed letters you can use a StringBuffer, appending them using a StringBuffer.append() to append new letters (maintaining state) and use the StringBuffer.toString() method to get the String representation when you need to do the comparison above.
Since Java 1.5 the class String contains the method contains(). My idea is to collect all entered letters into a string variable and using above method:
// My code line
String letterAlreadyEntered = "";
// Your code line
char character = reader.readLine().charAt(0);
// My code line
if (letterAlreadyEntered.contains("" + character) == true) {
//Put code here what ever you want to do with existing letter
} else {
letterAlreadyEntered += character;
}
In my opinion, this is an easier way to check for occurrences than in arrays, where you have to write your own check method.
for(int i = 0; i <= gameWord.length()-1; i++)
{
if(guessLetter.charAt(0) == (gameWord.charAt(i)))
{
hideword[i] = guessLetter.charAt(0);
}
else if(guessLetter.charAt(0) != (gameWord.charAt(i)))
{
System.out.print("_" + " ");
}
}
I am making a hangman game and I have created an array list called hideword. Hideword prints an underscore for each letter that is in the word used for the game. I am trying to right a method that will swap the underscore with a letter the user guesses. However this code
hideword[i] = guessLetter.charAt(0);
Doesn't work. It gives me "array required, but java.util.ArrayList found
Anyone help?
Then, hideword must be an arraylist. Use hideword.set(index, character) for assignment instead of accessing it like an array.
An ArrayList is not an array, it's a List implementation (however, its implementation is backed by an array - hence the name).
Declare hideword as an array of char:
private char[] hideword;
and initialize it before use:
hideword = new char[gameword.length];
You code, without changing its basic intention, can be simplified greatly:
There's no need to subtract 1 from the length, just change the comparison operator
There's no need to have your if in the else - we already know it's not equal because we're in the else block
Rather than do useless print, assign an underscore to the array slot
Do one print at the end
Like this:
for (int i = 0; i < gameWord.length(); i++) {
if (guessLetter.charAt(0) == (gameWord.charAt(i))) {
hideword[i] = guessLetter.charAt(0);
} else {
hideword[i] = '_';
}
}
// print hideword
You code would be simpler still if hideword didn't exist and you simply System.out.print() each character as you test it instead.
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.
I have to be able to input any two words as a string. Invoke a method that takes that string and returns the first word. Lastly display that word.
The method has to be a for loop method. I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
How can I make it so that no matter what phrase I use for the string, it will always return the first word? And please explain what you do, because this is my first year in a CS class. Thank you!
I have to be able to input any two words as a string
The zero, one, infinity design rule says there is no such thing as two. Lets design it to work with any number of words.
String words = "One two many lots"; // This will be our input
and then invoke and display the first word returned from the method,
So we need a method that takes a String and returns a String.
// Method that returns the first word
public static String firstWord(String input) {
return input.split(" ")[0]; // Create array of words and return the 0th word
}
static lets us call it from main without needing to create instances of anything. public lets us call it from another class if we want.
.split(" ") creates an array of Strings delimited at every space.
[0] indexes into that array and gives the first word since arrays in java are zero indexed (they start counting at 0).
and the method has to be a for loop method
Ah crap, then we have to do it the hard way.
// Method that returns the first word
public static String firstWord(String input) {
String result = ""; // Return empty string if no space found
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break; // because we're done
}
}
return result;
}
I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
There it is, using those methods you mentioned and the for loop. What more could you want?
But how can I make it so that no matter what phrase I use for the string, it will always return the first word?
Man you're picky :) OK fine:
// Method that returns the first word
public static String firstWord(String input) {
String result = input; // if no space found later, input is the first word
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break;
}
}
return result;
}
Put it all together it looks like this:
public class FirstWord {
public static void main(String[] args) throws Exception
{
String words = "One two many lots"; // This will be our input
System.out.println(firstWord(words));
}
// Method that returns the first word
public static String firstWord(String input) {
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
return input.substring(0, i);
}
}
return input;
}
}
And it prints this:
One
Hey wait, you changed the firstWord method there.
Yeah I did. This style avoids the need for a result string. Multiple returns are frowned on by old programmers that never got used to garbage collected languages or using finally. They want one place to clean up their resources but this is java so we don't care. Which style you should use depends on your instructor.
And please explain what you do, because this is my first year in a CS class. Thank you!
What do I do? I post awesome! :)
Hope it helps.
String line = "Hello my name is...";
int spaceIndex = line.indexOf(" ");
String firstWord = line.subString(0, spaceIndex);
So, you can think of line as an array of chars. Therefore, line.indexOf(" ") gets the index of the space in the line variable. Then, the substring part uses that information to get all of the characters leading up to spaceIndex. So, if space index is 5, it will the substring method will return the indexes of 0,1,2,3,4. This is therefore going to return your first word.
The first word is probably the substring that comes before the first space. So write:
int x = input.indexOf(" ");
But what if there is no space? x will be equal to -1, so you'll need to adjust it to the very end of the input:
if (x==-1) { x = input.length(); }
Then use that in your substring method, just as you were planning. Now you just have to handle the case where input is the blank string "", since there is no first word in that case.
Since you did not specify the order and what you consider as a word, I'll assume that you want to check in given sentence, until the first space.
Simply do
int indexOfSpace = sentence.indexOf(" ");
firstWord = indexOfSpace == -1 ? sentence : sentence.substring(0, indexOfSpace);
Note that this will give an IndexOutOfBoundException if there is no space in the sentence.
An alternative would be
String sentences[] = sentence.split(" ");
String firstWord = sentence[0];
Of if you really need a loop,
String firstWord = sentence;
for(int i = 0; i < sentence.length(); i++)
{
if(sentence.charAt(i) == ' ')
{
sentence = firstWord.substring(0, i);
break;
}
}
You may get the position of the 'space' character in the input string using String.indexOf(String str) which returns the index of the first occurrence of the string in passed to the method.
E.g.:
int spaceIndex = input.indexOf(" ");
String firstWord = input.substring(0, spaceIndex);
Maybe this can help you figure out the solution to your problem. Most users on this site don't like doing homework for students, before you ask a question, make sure to go over your ISC book examples. They're really helpful.
String Str = new String("Welcome to Stackoverflow");
System.out.print("Return Value :" );
System.out.println(Str.substring(5) );
System.out.print("Return Value :" );
System.out.println(Str.substring(5, 10) );
I created a method to output a String. Using the split method and a for loop, I added each word in my sentence into a String array, replacxing the last two letters of each word with "ed". Now, my return statement should return each of the words. When I used System.out.print, it worked. When I use a return and call it in my main method, I get this output: "[Ljava.lang.String;#1b6235b"
The error seems so simple but I just don't know where I'm going worng. Any help would be appreciated.
Here is my method:
public String[] processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
// System.out.print(words[i]);
}
}
return words;
}
You are printing arrays but arrays don't have a proper implementation of toString() method by default.
What you see is
"[Ljava.lang.String;#1b6235b"
This is [Ljava.lang.String; is the name for String[].class, the java.lang.Class representing the class of array of String followed by its hashCode.
In order to print the array you should use Arrays.toString(..)
System.out.println(Arrays.toString(myArray));
A good idea however, it returns my Strings in an Array format. My aim
is to return them back into sentence format. So for example, if my
input is, "Hey my name is Fred", it would output as, "Hed ed naed ed
Fred". Sorry, I forgot to add that it also seperates it with commas
when using Arrays.toString
Then you should modify your processInfo() returning a String or creating a new method that convert your String[] to a String.
Example :
//you use like this
String [] processInfoArray = processInfo();
System.out.println(myToString(processInfoArray));
// and in another part you code something like this
public static String myToString(String[] array){
if(array == null || array.length == 0)
return "";
StringBuilder sb = new StringBuilder();
for(int i=0;i<array.length-1;i++){
sb.append(array[i]).append(" ");
}
return sb.append(array[array.length -1]).toString();
}
As much as I can get from your question and comment is that your aim is to return them back into sentence format. So for example, if your input is, "Hey my name is Fred", it would output as, "Hed ed naed ed Fred".
In that case you should return a String, and not an array. I have modified your method a bit to do so. Let me know if you wanted something else.
public String processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
sentence = "";
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
sentence += " " + words[i];
// System.out.print(words[i]);
}
}
return sentence.trim();
}
Your commented out call to System.out.print is printing each element of the array from inside the loop. Your method is returning a String[]. When you try to print an array, you will get the java representation of the array as you are seeing. You either need to change your method to build and return a string with all the array entries concatenated together, or your calling code needs to loop through the returned array and print each entry.