System.out.println("type something to get it back reversed...");
Scanner sc1 = new Scanner(System.in);
String x = sc1.nextLine();//user input
for(int i = x.length(); i > 0; i--)
{
System.out.print(x.substring(i));
}
In this code, I want to take user-inputted text and output it in reverse order (i.e. dog = god) with a for-loop and the substring method. The above code is non-functional.
For example...
-when I input "dog", I get "gog".
-when I input "computer", I get "rerteruterputermputeromputer"
It never outputs the first letter of the text. I'd be very grateful if somebody could help me out and explain this to me :)
See the API for the String class. The String.substring(int index) method creates a substring from the parameter index to the end of the String (so if x is dog, the x.substring(0) results in 'dog'. Perhaps you wish to use the two parameter substring method. Also note the indexes of the loop, starting at length - 1 and ending at 0
for ( int i = x.length()-1; i >= 0; i-- ){
System.out.print(x.substring(i, i+1));
}
substring(i) returns everything in your string from i to the end. To get the character at position i in a string, use charAt(i).
Also, the last index of the string is x.length()-1. The first is zero. So your loop should be something like:
for (int i = x.length()-1; i>=0; --i) {
System.out.print(x.charAt(i));
}
As copeg explained, substring() returns all characters after the character i. An easier solution would be to use charAt():
for(int i = x.length()-1; i >= 0; i--) {
System.out.print(x.charAt(i));
}
Related
I'm new to java and I wrote this method to input a string word and output the word spelled backwards. The intent is to create a method and not use an already existing method such as the simple reverse. Please help point me in the direction of how to do this to reverse a word. I'm also trying to determine/count if there are palindromes. Please help! I've read other questions and I can't find anything specific enough to my case. I know that my code doesn't run, though I'm unsure how to fix it to get the correct output.
An example would be the word "backwards" to go to "sdrawkcab".
public static int reverseWord(String word) {
int palindromes = 0;
for (int i = word.length(); i >= 0; i--) {
System.out.print(i);
word.equalsIgnoreCase();
if (word.charAt(i)) == index(word.charAt(0 && 1))) {
palindromes++
System.out.println(palindromes)
}
return i;
}
}
There are multiple problems with your code.
1.The prototype of equalsIgnoreCase is
public boolean equalsIgnoreCase(String str);
So this method expect a String to be passed,but your not not passing anything here.To fix this,pass another string with whom you want to match your word like this..
word.equalsIgnoreCase("myAnotherString");
2.word.charAt(i);
Suppose word="qwerty",so indexing of each character will be like this
/* q w e r t y
0 1 2 3 4 5 */
So when you use i = word.length();i will 6 since word is of length 6.So
word.charAt(i) will search for character at index 6,but since there is not index 6,it will return an exception ArrayIndexOutOfBound.To fix this,start i from word.length()-1.
3.if (word.charAt(i));
This extra " ) ".Remove it.
Is Index() your own method?.If Yes,then check that also.
the below code prints the reverse of the input string and checks if it is a palindrome
public static void main(String[] args) {
String input = "dad";
char temp[] = input.toCharArray();//converting it to a array so that each character can be compared to the original string
char output[] = new char[temp.length];//taking another array of the same size as the input string
for (int i = temp.length - 1, j = 0; i >= 0; i--, j++) {//i variable for iterating through the input string and j variable for inserting data into output string.
System.out.print(temp[i]);//printing each variable of the input string in reverse order.
output[j] = temp[i];//inserting data into output string
}
System.out.println(String.valueOf(output));
if (String.valueOf(output).equalsIgnoreCase(input)) {//comparing the output string with the input string for palindrome check
System.out.println("palindrome");
}
}
Because your question about what is wrong with your code was already answered here is another way you could do it by using some concepts which are somewhat less low level than directly working with character arrays
public static boolean printWordAndCheckIfPalindrome(final String word) {
// Create a StringBuilder which helps when building a string
final StringBuilder reversedWordBuilder = new StringBuilder("");
// Get a stream of the character values of the word
word.chars()
// Add each character to the beginning of the reversed word,
// example for "backwards": "b", "ab", "cab", "kcab", ...
.forEach(characterOfString -> reversedWordBuilder.insert(0, (char) characterOfString));
// Generate a String out of the contents of the StringBuilder
final String reversedWord = reversedWordBuilder.toString();
// print the reversed word
System.out.println(reversedWord);
// if the reversed word equals the given word it is a palindrome
return word.equals(reversedWord);
}
I want to search for words in a Word Puzzle in Java.
The search,as stated is in horizontal,vertical and Diagonal.
I created an Array, but I just don't know how to create a String, and search for words in my String. I need to know how can I have a String that keeps all the values of the table, and how can I be able to type a word, and search for it here.
I know that the search of the words is done with indexOf Function,but I don't know how to perform it.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
int IntegerPosition;
int IntegerPosition2;
String position="";
String word="";
Scanner s = new Scanner(System.in);
String content="";
String[][] sopa = {
{"X","F","E","K","J","U","I","R","S","H"},
{"Z","H","S","W","E","R","T","G","O","T"},
{"B","R","A","B","F","B","P","M","V","U"},
{"D","W","E","R","O","O","J","L","L","W"},
{"U","T","O","N","I","R","O","B","C","R"},
{"O","P","R","O","V","I","I","K","V","B"},
{"N","I","Q","U","E","N","T","N","S","A"},
{"O","V","U","L","R","O","S","S","O","T"},
{"A","S","A","X","J","T","R","R","I","T"},
{"R","K","M","E","P","U","B","O","T","A"}
};
for (int i = 0; i < sopa[0].length; i++){
for(int j = 0; j < sopa[i].length; j++){
content += sopa[i][j];
}
System.out.println(content);
content = "";
}
System.out.println("Type the word you are looking for");
word = s.next();
for (int i = 0; i < sopa[0].length-1; i++){//t1.length
for(int j = 0; j < sopa[i].length-1; j++){
}
}
System.out.println(content);
content = "";
}
}
First, you should declare what "finding a word" means. I guess you want to find the sequence of letters in each row and column. What about diagonal? Backwards? Wrapping around?
Two solutions come to mind:
Use a String index:
Build a String of all characters. This needs to be done for each direction (horizontal, vertical, diagonal), but only in the forward order if you reverse the search term for backwards search. For an efficient implementation StringBuilder is your friend.
Use String.indexOf to find occurences of the term in your index. Finally you have to calculate row and column from the String position and, if wrapping is not allowed, check if the word crosses any row/column boundary.
I'd use this if I had to look for many terms.
Use the array
Also for each direction (horizontal, vertical, diagonal)
Look for occurences of the search term's first letter in your array (by simple iteration). Note that you can stop when the term would not fit the row/column, so for a 6-letter word, you can skip the 5 last rows/columns.
If you found an anchor (i.e. matching letter), check the subsequent letters of the word. Cancel on mismatch, otherwise you have found an occurence.
For a more sophisticated matching implementation, the Boyer-Moore algorithm may be of interest.
I need your help. I have a string with value "1,2,3,4,5,6,7,8,9,10".
What I want to do is take once first value ("1") only (substring (0, 1) for example) and then do a loop with the rest of values except the first value that I already take.
Maybe I have to create another String variable and set the values without first value to the second String variable and then create a loop? How to do that?
The easiest way would probably be to use String#split(String):
String str = "1,2,3,4,5,6,7,8,9,10";
String[] parts = str.split(",");
// Save the first part
String firstPart = parts[0];
// Iterate over the others:
for (int i = 1; i < parts.length; ++i) {
System.out.println (parts[i]); // Or do something useful with it
}
You can use split function.
String numbers = "1,2,3,4,5,6,7,8,9,10"; //Here your String
String[] array = numbers.split(","); //Here you divide the String taking as reference the ,
String number = array[0] //You will get the number 1
If you want to take the rest of the elements:
for(i = 1; i < array.length; i++)
System.out.println(array[i]);
I expect it will be helpful for you!
first of all I want to say that I am kinda new to Java. So please be easy on me :)
I made this code, but I cannot find a way to change a character at a certain substring in my progress bar. What I want to do is this:
My progressbar is made out of 62 characters (including |). I want the 50th character to be changed into the letter B (uppercase).It should look something like this: |#########----B--|
I tried several things, but I dont know where to put the line of code to make this work. I tried using the substring and the replace code, but I can't find a way to make this work. Maybe I need to write my code in a different way to make this work? I hope someone can help me.
Thanks in advance!
int ecttotal = ectcourse1+ectcourse2+ectcourse3+ectcourse4+ectcourse5+ectcourse6+ectcourse7;
int ectmax = 60;
int ectavg = ectmax - ecttotal;
//Progressbar
int MAX_ROWS = 1;
for (int row = 1; row == MAX_ROWS; row++)
{
System.out.print("|");
for (int hash = 1; hash <= ecttotal; hash++)
System.out.print ("#");
for (int hyphen = 1; hyphen <= ectavg; hyphen++)
System.out.print ("-");
System.out.print("|");
}
System.out.println("");
System.out.println("");
}
Can you tell a little more what you want. Because what i sea it that, that you write some string into console. And is not way to change that what you already print to console.
Substring you can use only at String varibles.
If you want to change lettir with substring method in string varible try smth. like this:
String a="thi is long string try it";
if(a.length()>50){
a=a.substring(0,49)+"B"+a.substring(51);
}
Other way to change charater in string is to use string builder like this:
StringBuilder a= new StringBuilder("thi is long string try it");
a.setCharAt(50, 'B');
Sure you must first check the length of string to avoid the exceptions.
I hope that I helped you :)
Java StringBuilder has method setCharAt which can replace character at position with new character.
StringBuilder myName = new StringBuilder(<original string>);
myName.setCharAt(<position>, <character to replace>);
<position> starts with index 0
In your case:
StringBuilder myName = new StringBuilder("big longgggg string");
myName.setCharAt(50, 'B');
You can replace a certain index in a string by concatenating a new string around the intended index. For example the following code replaces the letter c with the letter X. Where 2 is the intended index to replace.
In other words, this code replaces the 3rd character in the string.
String s = "abcde";
s = s.substring(0, 2) + "X" + s.substring(3);
System.out.println(s);
So I am reading in a line from a file, that looks like:
Snowman:286:355:10
And this is the first part of the code I wrote to separate the data and place it into arrays.
for (int i = 0 ; i<manyItems; i++)
{
a = 0;
temp = scan.nextLine();
System.out.println(temp);
b = temp.indexOf(':');
System.out.println(b);
items[i] = temp.substring(a,b);
System.out.println(items[i]);
System.out.println(temp);
a = b;
System.out.println(temp);
b = temp.indexOf(a+1,':');
System.out.println(b);
rawX[i] = temp.substring(a+1,b);
System.out.println(rawX[i]);
}
It separates "Snowman" places it into the array, however, when I try to find the second colon, indexOf() keeps returning -1. Does anyone know why it is not finding the second colon?
You could save all that code and use String#split to split the line:
String[] parts = temp.split(":");
I think you have the arguments backwards:
b = temp.indexOf(a+1,':');
Should be...
b = temp.indexOf(':', a+1);
From docs.oracle.com:
public int indexOf(int ch,
int fromIndex)
The first argument is the character, the second if the fromIndex.
Because you swapped the arguments of the indexOf call. It expects the character, then the index to start looking at. Remember that chars are ints, you're looking for the char 7 starting at the int value of ':'.
There's a method under String class that will handle the job for you. Split(regEx pattern) is what you may want to use. The following code will do the job you're trying to perform:
String input = "Snowman:286:355:10";
String tokens [] = input.split(":");
for (int i = 0; i < tokens.length; i++)
System.out.println(tokens[i]);