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.
Related
I'm trying to make a program where a user can post a comment and it'll be able to extract the words, e.g.
I love to #program in #java
would show the output
#program
#java
What I have currently is not running, although there is no errors detected.
class userInput {
public static Scanner input = new Scanner(System.in);
public static String readString(String message){
System.out.println(message);
String readValue = input.nextLine();
return readValue;
}
public static int readInt(String message){
System.out.println(message);
int readValue = input.nextInt();
input.nextLine();
return readValue;
}
public static double readDouble(String message){
System.out.println(message);
double readValue = input.nextDouble();
input.nextLine();
return readValue;
}
public static void close(){
input.close();
}
public static void main(String[] args) {
String post [] = new String [5];
String userPost = "";
userPost = userInput.readString("Type your post");
post[0] = userPost;
String hashtags ="";
for (int i = 0; i<post.length && post[i]!=null;i++){
String[]words = post[i].split(" ");
for(int j=0;j<words.length;j++){
if(words[j].trim().startsWith("#")){
hashtags+=words[j].trim() + " ";
}
}
}
if(hashtags.trim().isEmpty())
System.out.println("No hashtags were typed");
else
System.out.println("Hashtags found:" + hashtags);
}
}
I would use regular expressions.
In the below code, the pattern that I search for is a # character followed by one or more lowercase letters which is what I understood from the example in your question. If that is not the case, then you will need to change the pattern. Refer to the documentation and there are also many questions here about regular expressions in Java.
Also note that the below code uses the stream API. Method results was added in JDK 9, so you need at least that version in order to run the below code.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Comments {
public static void main(String[] strings) {
String sentence = "I love to #program in #java.";
Pattern regex = Pattern.compile("#[a-z]+");
Matcher mtchr = regex.matcher(sentence);
mtchr.results()
.forEach(mr -> System.out.println(mr.group()));
}
}
The above code produces the following output:
#program
#java
You can use split(" ") to split a sentence into words. You can then iterate over all the words and only find those that start with a #. Last but not least you should remove any punctuation marks at the end of words. The most concise and readable way to do this in my opinion is to use Java 8 Streams and the filter() and map() methods. Instead of returning a List using toList() you could of course also return an array using toArray().
import java.util.*;
public class Application {
public static void main(String[] args) {
var sentence = "I love to #program in #java.";
System.out.printf("Hashtags in sentence: %s\n", findHashtags(sentence));
}
public static List<String> findHashtags(String sentence){
var punctuationMarksAtEndOfWordRegex = "[.?,:!]$";
return Arrays.stream(sentence.split(" "))
.filter(word -> word.startsWith("#"))
.map(hashtag -> hashtag.replaceAll(punctuationMarksAtEndOfWordRegex, "")).toList();
}
}
A really naive way is to loop over the comment and check if we encountered a hashtag then once we find a hashtag we start another loop where we add to a our result string the characters starting from the current index until the end of the comment and making sure we don't encounter a space character.
public static String extract(String comment)
{
String result = "";
for(int i=0; i<comment.length(); i++)
{
char current = comment.charAt(i);
if(current == '#')
{
for(int j=i; j<comment.length() && comment.charAt(j) != ' '; j++)
result += comment.charAt(j);
}
}
return result;
}
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
}
}
}
This is outputting 'nullsd87xc8' or some other random password but it keeps putting out null before the random letters as well.
import java.util.*;
public class PassGen {
public static String randomPassword;
private static Scanner kb;
public static void main(String[] args) {
System.out.println("This program will generate a random password");
System.out.println("Enter desired password length");
kb = new Scanner(System.in);
int passLeng = kb.nextInt();
char[] passData = "abcdefghijklmnopqrstuvwxyz1234567890!##$%^&*".toCharArray();
Random rand = new Random();
for (int i=1;i<=passLeng;i++) {
int random = rand.nextInt(passData.length-1);
randomPassword = randomPassword + Character.toString(passData[random]);
}
System.out.println(randomPassword);
}
}
The problem is you are not initializing the string randomPassword before you use it. Line 3 declares the string, giving it memory space but no value. The output that you are getting is not actually random characters appended to the word null, it's telling you the memory address containing that string, i.e. null # 0x3333333. This is Java's way of saying it is null, but because of Java's methods for storing string objects you still have a memory address displayed. Change line 3 to read public static String randomPassword = ""; and you should be in business.
randomPassword is null to begin with. Then you add characters to it. Change
public static String randomPassword;
to
public static String randomPassword = "";
Just add "" to randomPassword
public static String randomPassword="";
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.
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.