Why are the quotes necessary in this code? [duplicate] - java

This question already has answers here:
this method must return a result of type boolean, java
(5 answers)
Closed 7 years ago.
Hi sorry if this is a dumb question, probably is... this is from codingbat (exercise: everNth)
why is it that this works?
public String everyNth(String str, int n) {
String characters = "";
for (int i = 0; i < str.length(); i = i + n) {
characters = characters + Character.toString(str.charAt(i));
}
return characters;
}
but this one doesn't?
public String everyNth(String str, int n) {
for (int i = 0; i < str.length(); i = i + n) {
return Character.toString(str.charAt(i));
}
}
^^ gives me the error: "This method must return a result of type String"
However, doesn't the Character.string() method already create a string?
Why do I have to add in additional quotation marks? Thanks guys!!~~ peace and love

It has nothing to do with the quotation marks. The problem is that you don't have a return statement after the for loop.
The compiler is warning you that if the for loop is never entered, then you will never return anything. You need to make sure your method returns a string value under all circumstances, not just when the loop is entered.
To better understand, walk through your method, and consider what would happen if str has a length of zero. What would your method return then?
EDIT
However, as pointed out by WalterM, keep in mind that, even if you fix the compiler error, your 2nd method's logic is different from your first one. The 2nd method only ever returns the 1st character of the string.

Related

Java 8, updating element in array [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have trouble with my code. I need to replace element in Array if condition is true.
Inputs are:
dashedCapital = "------";
input = "a";
capital = "Warsaw";
Code should check if capital contains input and if yes replace "-" in dashedCapital to character from input at specified position:
public static String changeDashedCapital(String dashedCapital, String input, String capital){
String[] capitalArray = capital.split("");
String[] dashedCapitalArray = dashedCapital.split("");
String[] character = input.split("");
for(int i = 0; i < capitalArray.length; i++){
//System.out.println(i);
//System.out.println(capitalArray[i] + character[0] + dashedCapitalArray[i]);
if(capitalArray[i] == character[0]){
dashedCapitalArray[i] = character[0];
}
}
String result = Arrays.toString(dashedCapitalArray);
System.out.println(result);
return result;
}
Result is "------" but should be "-a--a-". What's going wrong?
John, thanks for your reply, it was helpful.
I edited my method so it's look like this now:
public static String changeDashedCapital(String dashedCapital, String input, String capital){
for(int i = 0; i < capital.length(); i++){
if(capital.charAt(i).equals(input.charAt(0))) {
String new_dashed = dashedCapital.substring(0,i)+input.charAt(0)+dashedCapital.substring(i);
System.out.println(new_dashed);
}
}
return "OK:";
Now i get this error:
GetWord.java:69: error: char cannot be dereferenced
if(capital.charAt(i).equals(input.charAt(0))) {
^
1 error
I don't understand why it's wrong. I using a equals() function. I also tried "==" operator but then nothing happens. What does it mean "char cannot be dereferenced"? How I could compare single chars from string with another chars from another string?
The reason it is not working is because your if for character equality is never true. You’re comparing strings of length 1 and not characters. You can quickly fix by changing if be using the string comparing function .equals()
if(capitalArray[i].equals(character[0])){
...
}
However, you should change your code and not just use this fix. Don’t split your stings into arrays, just use the .charAt() method to get a character at a particular index.

How to add whichever character between every character of a premade String? [duplicate]

This question already has answers here:
Concatenating null strings in Java [duplicate]
(5 answers)
Closed 7 years ago.
How to add whichever character between every character of a premade String? (JAVA)
For example, I have the String "Hello world" and I have to add '_' between every character of the String.
Any function or useful code I can use to do it?
I have to do an algorithm that make me output "H_e_l_l_o_ _w_o_r_l_d"
This is what I have:
public String example(String s) {
String s2 = null;
for(int i = 0; i < s.length(); i++){
s2 += s.charAt(i) + (((i+1) == 0) ? " " : "-");
}
return s2;
}
My output in the main class is being:
nullH-e-l-l-o- -w-o-r-l-d-
Don't know why
This looks like a homework assignment. So, I won't directly write out all the code.
String = "hello world";
Say, there is a variable len = str.length() - 1. Instead of doing it from index 0, we will start our for loop from len - 1. The character 'd' is at index len, and the '_' will have to be inserted right before that. This can be done by setting the string to str = str.substring(0,i) + "_" + str.substring(i+1);
You will have to use a for loop that starts from len - 1 and goes on till the index reached is 0.
Now, on every single iteration, when you are inserting a character assigning str to str.substring(0,i) + "_" + str.substring(i+1); causes you to make a new string object, which is absolutely horrible style. This can be solved by using a StringBuilder.
Does that make it clear?
In the future, refrain from posting questions without having done any work. This community is there to help you with solving issues that you may have in your solutions, not write your solutions for you.

How to print an int array returned in a method in the main function , Java [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
First of all,I am newbie in Java and I came across this issue several times. I am trying to return the number of occurrences of a char in a string and I implemented a method called countcharacters which looks like this:
public static int[] countcharacters(String s)
{
String alphabet="abcdefghijklmnopqrstuvwxyz";
int[] sircounter=new int[alphabet.length()];
for(int i=0;i<sircounter.length;i++)
{
sircounter[i]=0;
}
for(int j=0;j<alphabet.length();j++)
{
for(int i=0;i<s.length();i++)
{
if(alphabet.charAt(j)==(s.charAt(i)))
{
sircounter[j]++;
}
}
}
return sircounter;
}
In other words, each time a character from alphabet is found in my string ,the argument of the method, the value zero from each position from sircounter is incremented with the number of occurrence.
I wanted to print the array position by position but it didn't work and if
I do something like this in the main method:
String text="hannah";
System.out.println(Class.countcharacters(text));
I get a hex code: [I#659e0bfd which I don't understand.
Could you help me?
Many thanks and have a nice day!
This is happening because array is treated as an object in java.And when you try to print an object in java you get its hash code(as long as that object hasn't have toString() defined!)
Try this rather-
String text="hannah";
int counter[]=Class.countcharacters(text);
for(int i=0;i<counter.length;i++){
System.out.print(counter[i]+" ");
}

Java, return formatted string of an int [duplicate]

This question already has answers here:
How can I pad an integer with zeros on the left?
(18 answers)
Closed 8 years ago.
I have just started studying Java and now I need to make an Java function that returns a formatted string representation of an int.
This function must return "001" instead of just 1 and "010" instead of just 10, and so on... my function looks like this:
int value = 1;
public String getcountervalue() {
String Return_string = Integer.toString(value);
return (Return_string);
}
This is just a small part of an bigger code. the count of the value is handled by an other part of the code. I guess that the Integer.toString part will convert the int to an string, or?, but how can i make it properly formated (as explained above)?
I'm sorry if this question have been asked before, I where not able to find it.
I'm using java 1.7
There is a handy format() method, provided by String. See Oracle documentation
In your case, something like this should do it:
public String getCounterValue(int value) {
return String.format("%03d", value);
}
String.format("%02d", i);
or
for (i=0; i<=9; i++){
System.out.println("00"+i)
}
for (i=10; i<=99; i++){
System.out.println("0"+i)
}
if(i=100){
System.out.println(i)
}
public String getcountervalue() {
String Return_string = Integer.toString(value);
while(Return_string.length < 3){
Return_string = '0'+Return_string;
}
return (Return_string);
}

Wrong output from a while loop using indexOf [duplicate]

This question already has answers here:
While loop doesn't run a indexOf search
(4 answers)
Closed 8 years ago.
I'm trying to find out how many times one string appears in another. For my testing, I'm using "ea" for wordOne and "Ilikedthebestontheeastbeachleast" for wordTwo. My output is returning 2 for my "appearance" variable, which should store how many times "ea" appears in wordTwo. It should return 3.
I've tried messing with variable initializations, and trying to think of the math differently, but I'm pretty much out of ideas.
Here's the relevant code section:
int wordTwoLength = wordTwo.length();
System.out.println(wordTwoLength);
while (wordTwoLength > 0)
{
positionCount = wordTwo.indexOf(wordOne, positionCount);
appearances++;
wordTwoLength = (wordTwoLength - positionCount);
}
System.out.println(appearances);
Thanks!
Edit: I forgot to add that I tried other test inputs and got crazy outputs. It would return numbers way higher than expected for some, and lower for others.
So now the problem is that .indexOf still returns the true index of "ea" in wordTwo - it doesn't take into account where you start from. Also, setting positionCount equal to where you find the word and then searching from that position again is just going to make you immediately find the same instance of that word, not the next one.
The index of the first instance of "ea" in wordTwo is 18, so wordTwoLength will be set to 32-18, or 14. Then you'll find the same instance of ea in wordTwo, and wordTwoLength will be set to 14-18, or -4. Then you'll exit the while loop, with appearances being 2.
for (int index = 0; (index = wordTwo.indexOf(wordOne, index)) > -1; index ++)
appearances ++;
Try this simpler code:
class Demo{
public static void main(String[] args){
String wordOne = "ea";
String wordTwo = "Ilikedthebestontheeastbeachleast";
String[] arr = wordTwo.split(wordOne);
int cnt = arr.length - 1;
System.out.printf("[%s] has occured for %s time(s) in [%s]", wordOne, cnt, wordTwo);
}
}
You can simplify your above work by "Converting String to Character array".Because it will be more Efficient(I think).I have provided a sample code here,
String wordOne="Ilikedthebestontheeastbeachleast";
String wordTwo="ea";
int count=0;
char[] arrayOne=wordOne.toCharArray();
char [] arrayTwo=wordTwo.toCharArray();
for(int i=0;i<=((arrayOne.length)-1);i++)
{
if(arrayTwo[0]==arrayOne[i]&&arrayTwo[1]==arrayOne[i+1])
count+=1;
}
System.out.println("Pattern found "+count+" times.");
This will suits your need but using For loop.

Categories