Simple Substring Issue - java

My teacher wants us to make a letter 'o' move around the console. The letter 'o' has been coded to appear in the center of the console screen. I have already created the movingRight and movingDown methods but I'm having difficulty creating the movingLeft and movingUp methods. Here is my code:
import java.util.Scanner;
public class Main {
static String letter = "\n\n\n\n O";
String whenmovingup = letter.substring(0, 1);
char whenmovingleft = letter.charAt(letter.length() - 2);
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(letter);
input.nextLine();
if (input.equals("left")) {
movingLeft();
}
if (input.equals("right")) {
movingRight();
}
if (input.equals("up")) {
movingUp();
}
if (input.equals("down")) {
movingDown();
}
}
public static void movingRight(){
letter = " " + letter;
}
public static void movingDown(){
letter = "\n" + letter;
}
public static void movingLeft(){
letter.remove(whenmovingleft);
}
public static void movingUp(){
letter.remove(whenmovingup);
}
}
I'm having an issue with removing the whenmovingfeft and whenmovingup substrings from my original string letter. It's giving an error ('The method remove(char) is undefined for the type String'), and I'm not sure what needs to be done.
Does anyone know how this can be resolved?
Thanks in advance for all responses.

There is no remove method for a string. However, there is a replace method that may do what you want. Note that it does not modify the string object, but it returns a new string. So you would do:
letter = letter.replace(whenmovingup, "");
Note that there are two slightly different overloads of replace which do different things depending on whether you ask it to remove a String or char. The replace(String, String) method replaces one occurrence, while the replace(char, char) replaces all occurrences. You want just one, so declare whenmovingleft as a String and initialise it appropriately.

Related

How can I randomly display a single character from a given word

Here is an update as to where I am at and what I am stuck on based on what #camickr suggested. The issue that I am coming across now is that since I have to have a return statement at the end I can only return the ArrayList letters.
Also every time the hint button is pressed only one character appears in the solution location and it is [], yet no actual letters that make up the solution appear.
public String generateLetterHint(int count, String word) {
String[] answerArray = word.split("");
ArrayList<String> letters = new ArrayList<String>(Arrays.asList(answerArray));
//StringBuilder string = new StringBuilder();
Collections.shuffle(letters);
while (!letters.isEmpty()) {
String letter = letters.remove(0);
System.out.println(letter);
}
return letters.toString();
}
Any help is appreciated!
One way it to add each (unique) letter of the String to an ArrayList.
Then you can use the Collections.shuffle(...) method to randomize the letters.
Each time the "Hint" button is pressed you:
get the letter at index 0
"remove" the letter from position 0
give the hint.
Now the next time the "Hint" button is clicked there will be a different letter at index 0.
Of course each time the user guesses a correct letter you would need to "remove" that letter from the ArrayList as well.
Edit:
Simple example showing proof of concept:
import java.util.*;
public class Main
{
public static void main(String[] args) throws Exception
{
String answer = "answer";
String[] answerArray = answer.split("");
ArrayList<String> letters = new ArrayList<String>(Arrays.asList(answerArray));
Collections.shuffle( letters );
while (!letters.isEmpty())
{
String letter = letters.remove(0);
System.out.println(letter);
}
}
}
In you real code you would only create the ArrayList once and do the shuffle once when you determine what the "answer" word is.
Then every time you need a hint you can simply invoke a method that does:
public String getHint(ArrayList letters)
{
return (letters.isEmpty() ? "" : letters.remove(0);
}
This will simply return an empty string if there are no more hints. Although a better solution would be to disable the hint button once the hints are finished.
Its working for only one answer. You can modify then work with multiple answer at the same time. When you you send a string to function, it gives you a letter that is unique inside from the string.
package com.Stackoverflow;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RandomlyString {
private static List<Character> selectableLetters; // it store randomly selectable letters
private static boolean isFirst = true;
private static char letterHint(String answer) {
Random rnd = new Random();
// when function starts in first time, split the string letter by letter
if (isFirst) {
selectableLetters = splitString(answer);
}
isFirst = false;
if(!selectableLetters.isEmpty()) {
int hintIndex = rnd.nextInt(selectableLetters.size()); // select a letter randomly
char hint = selectableLetters.get(hintIndex); // put this letter to hint
selectableLetters.remove(hintIndex); // then remove this letter from selectableLetters, this is for don't select the same letter twice
return hint;
} else {
System.out.println("There is no hint!");
return ' ';
}
}
private static List<Character> splitString(String string) {
List<Character> chars = new ArrayList<>();
// split the string to letters and add to chars
for (char c: string.toCharArray()) {
chars.add(c);
}
return chars;
}
public static void main(String[] args) {
String answer = "Monkey";
for(int i=0; i<7; i++) {
System.out.println("Hints: " + letterHint(answer)); // it writes hint to screen
System.out.println("Other letters: " + selectableLetters); // currently selectable letters for hint
}
}
}

Recursive Palindrome Checker

This method only works for small inputs such as xox but not with a more complex input like taco cat. I have read this code repeatedly and have not been able to fix the problem. I assume there is a tiny error as I have changed the code structurally trying to tweak my approach and have not been able to fix it.
import java.util.Scanner;
public class Palindromes
{
static Scanner scan = new Scanner(System.in);
public static void main (String[] args)
{
System.out.println("Enter a string, human:");
String s=scan.nextLine();
if(palindrome(s)){
System.out.print("This is a palindrome, I am amused Earthling.");
}else{
System.out.print("Don't you know to speak only in palindromes to your alien Overlord?");
}
}
public static boolean palindrome(String s){
s.replace(" ","");
if(s.length()<2){
return true;
}else if(s.charAt(0)==s.charAt(s.length()-1)){
return palindrome(s.substring(1,s.length()-2));
}else{
return false;
}
}
}
Two things to fix:
You forgot to assign the result of replace back to s, resulting in you ignoring the result with spaces removed. Try:
s = s.replace(" ","");
You have an off-by-one error when taking the substring to pass to the recursive call. The ending index of substring is exclusive, so you are trimming one too many characters off the end of the substring. Try:
return palindrome(s.substring(1,s.length()-1));

Java Error - array required, but java.lang.String found

I've been working on this problem for a while and managed to get rid of almost all the errors on this program. Every time I compile I seem to get this error saying "array required, but java.lang.String found." I'm really confused on what this means. Can someone help me please? I've been struggling a lot.
import java.util.Scanner;
public class Period
{
private static String phrase;
private static String alphabet;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
public void Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1; // This is here the error occurs.
}
else
{
alphabet[placement] = alphabet[placement] + 1; // This is where the error occurs.
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]); //this is where the error occurs.
}
}
}
replace
private static String alphabet;
with
private static char[] alphabet = new char [27];//to keep it in sync with letter
it should work.
You can't use a String as an array. There are two options here to fix this:
1) Make alphabet char[] instead of String.
or
2) Don't treat alphabet like an array. Instead of trying to reference a character as if it was stored in an array, use alphabet.charAt(placement). You can't use charAt() to replace one character with another, though, so instead of:
alphabet[placement] = alphabet[placement] + 1;
use this:
alphabet = alphabet.substring(0, placement+1) + "1" + alphabet.substring(placement+1);
That's assuming you want to insert "1" after the specified character in alphabet (it isn't entirely clear to me what you're trying to achieve here). If you meant instead to have that line of code replace the character you've referred to as alphabet[placement] with the one that follows it, you would want to do this instead:
alphabet = alphabet.substring(0, placement+1) + alphabet.charAt(placement+1) + alphabet.substring(placement+1);
Alternatively, you could set alphabet to be a StringBuilder rather than a String to make it easier to modify. If alphabet is a StringBuilder, then the first alternative to the line in question (inserting "1") could be written like this:
alphabet = alphabet.insert(placement, 1);
The second alternative (changing alphabet.charAt(placement) to match the following character could be written like this:
alphabet.setCharAt(placement, alphabet.charAt(placement+1));
Well, the problem is that you cannot threat String in java like an array (e.g., alphabet[i]).
String are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');
System.out.println(myName);
If I were you, I would have used the second method.

Censored Words Condition

I need this program to print "Censored" if userInput contains the word "darn", else print userInput, ending with newline.
I have:
import java.util.Scanner;
public class CensoredWords {
public static void main (String [] args) {
String userInput = "";
Scanner scan = new Scanner(System.in);
userInput = scan.nextLine;
if(){
System.out.print("Censored");
}
else{
System.out.print(userInput);
}
return;
}
}
Not sure what the condition for the if can be, I don't think there is a "contains" method in the string class.
The best solution would be to use a regex with word boundary.
if(myString.matches(".*?\\bdarn\\b.*?"))
This prevents you from matching sdarnsas a rude word. :)
demo here
Try this:
if(userInput.contains("darn"))
{
System.out.print("Censored");
}
Yes that's right, String class has a method called contains, which checks whether a substring is a part of the whole string or not
Java String Class does have a contains method. It accepts a CharSequence object. Check the documentation.
Another beginner method would be to use the indexOf function. Try this:
if (userInput.indexOf("darn") > 0) {
System.out.println("Censored");
}
else {
System.out.println(userInput);

How can I have a user search a character array for a letter?

gets a single letter from the user. This method validates that it’s either a valid letter or the quit character, ‘!’. It'll eventually keep asking for characters, then once the user is done, they'll type ‘!’ to make the loop end and move on to printing their list of chars
public static String isValidLetter(){
char[] charArray;
charArray = new char[11];
charArray[0] ='C';
charArray[1] ='E';
charArray[2] ='F';
charArray[3] ='H';
charArray[4] ='I';
charArray[5] ='J';
charArray[6] ='L';
charArray[7] ='O';
charArray[8] ='P';
charArray[9] ='S';
charArray[10] ='T';
charArray[11] ='U';
String input;
char letter;
Scanner kb = new Scanner(System.in);
System.out.println("Enter a single character: ");
input=kb.nextLine();
letter = input.charAt(0);
Reading the strings from console.. type "a", enter, "b", enter, "!", enter
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scann = new Scanner(System.in);
List<String> letterWords = new LinkedList<String>();
String str = null;
while (!"!".equals(str)) {
str = scann.next();
letterWords.add(str);
}
for (String word : letterWords) {
System.out.println(word);
}
scann.close();
}
}
If you just want to have a "collection" of valid characters, then you also could use a String instead of an array. It would be much easier to search in it and it avoids errors like in your example (you've initialized your array with size of 11, but you're inserting 12 elements):
public static boolean isValidLetter(final char character) {
final String validCharacters = "CEFHIJLOPSTU";
return validCharacters.contains(String.valueOf(character));
}
This method expects a single char and returns true if it is valid, false otherwise. Please mind, that this check is case sensitive.
You could use that method like this:
final Scanner scan = new Scanner(System.in);
String input;
while (!(input = scan.nextLine()).equals("!")) {
if (!input.isEmpty() && isValidLetter(input.charAt(0))) {
// ... store valid input
System.out.println("valid");
}
}
This loop requests user input until he enters !. I've omitted the storing part. It is up to you to do this last part.
Modify your isValidLetter method to return boolean.
Modify your isValidLetter method to get a char as a parameter.
In isValidLetter, try to find a letter by using a helper function, something like:
static boolean contains(char c, char[] array) {
for (char x : array) {
if (x == c) {
return true;
}
}
return false;
}
Somewhere in your code where you need the input (or in main for testing), ask for user input (as you already did in isValidLetter). Perform a loop, asking for input, until it is right, or until it is your ending character.
I am not posting the complete solution code on purpose, as it is better for you to play with the code and learn. I only gave directions on how to try; of course it is not the only way, but it fits with what you've already started.

Categories