Using while loop to determine amount of chars to be created - java

I am trying to make an application that will reverse a string using a while loop. Just wondering if I am on the right path or not.
So I thought I would make a while loop to determine how many chars i should make. Then I would just print them in reverse in the console.
Here is my code so far. Any help would be appreciated.
// Get the text from the input from the user
// Outputs it to the Text area
// Uses while loop to calculate how many chars to create
String Startword = txfInput.getText();
int LengthOfWord = Startword.length();
int Counter = 1;
while (Counter <= LengthOfWord)
{
// Creates amounts of chars based off the counter
Counter = Counter +1 ;
}
Any suggestions?

Just use a for loop..
String reverse = "";
for (int i = word.length()-1; i>=0; i--)
{
reverse += word.charAt(i);
}
if you want a while... then
while(i >= 0)
{
reverse += word.charAt(i);
i--;
}

You just need to add a character to the reverse String after every iteration, like this:
String Startword = txfInput.getText();
String rev="";
int LengthOfWord = Startword.length();
int Counter = 1;
while (Counter <= LengthOfWord)
{
rev=Startword.charAt(Counter-1)+rev; // Add a character to rev.
Counter = Counter +1 ;
}
System.out.println(rev);

Might be easier to do with a char array:
char[] output = new char[Startword.length];
for(int i = 0; i < Startword.length; i++){
output[i] = Startword.charAt(Startword.length - i - 1);
}
String rev = new String(output);

Scanner input = new Scanner(System.in);
String s=input.nextLine();
char[] stringArray;
stringArray = s.toCharArray();
int temp;
int low=0;
int high=stringArray.length-1;
while(low<high){
temp= stringArray[low];
stringArray[low] = stringArray[high];
System.out.print(stringArray[low]);
low ++;
high--;
}
check this out

Related

I have to capitalize the first letter of a String in Java.(I cant use the method in string class to do so). but i keep getting out of bounds error

here is the code. I keep getting the error: String index out of range:5, I don't know what I'm doing wrong so any help will be appreciated. Also, I'm not allowed to use any Scanner class methods other than length.
import java.util.*;
public class capitalLetter
{
public static void main(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a non capitalized word");
String word = sc.next();
int length = word.length();
char ch[] = new char[length];
for(int i = 0;i<length-1;i++){
ch[length] = word.charAt(length);
}
ch[0]+=32;
for(int i = 0;i<length-1;i++){
System.out.print(ch[length]);
}
}
}
Firstly, within the for loop you need to use the loop variable i, rather than length. Also, i should go to the last element of the array.
This
for(int i = 0; i < length-1; i++){
ch[length] = word.charAt(length);
}
should be
for(int i = 0; i < length; i++){
ch[i] = word.charAt(i);
}
Secondly, you're adding 32 when you should be subtracting.
Putting this together you get:
String word = "hello";
int length = word.length();
char ch[] = new char[length];
for(int i = 0; i < length; i++) {
ch[i] = word.charAt(i);
}
ch[0] -= 32;
for(int i = 0; i < length; i++) {
System.out.print(ch[i]);
}
Output:
Hello
In both of your loops, you are indexing by length instead of by i.
e.g this line
ch[length] = word.charAt(length);
should be like this
ch[i] = word.charAt(i);

Java program to find the letter that appears in the most words?

I have a sentence, and I want to find the char that appears in the most words, and how many words it appears in.
For example: "I like visiting my friend Will, who lives in Orlando, Florida."
Which should output I 8.
This is my code:
char maxChar2 = '\0';
int maxCount2 = 1;
for (int j=0; j<strs2.length; j++) {
int charCount = 1;
char localChar = '\0';
for (int k=0; k<strs2[j].length(); k++) {
if (strs2[j].charAt(k) != ' ' && strs2[j].charAt(k) != maxChar2) {
for (int l=k+1; l<strs2[j].length(); l++) {
if (strs2[j].charAt(k)==strs2[j].charAt(l)) {
localChar = strs2[j].charAt(k);
charCount++;
}
}
}
}
if (charCount > maxCount2) {
maxCount2 = charCount;
maxChar2 = localChar;
}
}
, where strs2 is a String array.
My program is giving me O 79. Also, uppercase and lowercase do not matter and avoid all punctuation.
As a tip, try using more meaningful variable names and proper indentation. This will help a lot especially when your program is not doing what you thought it should do. Also starting smaller and writing some tests for it will help a bunch. Instead of a full sentence, get it working for 2 words, then 3 words, then a more elaborate sentence.
Rewriting your code to be a bit more readable:
// Where sentence is: "I like".split(" ");
private static void getMostFrequentLetter(String[] sentence) {
char mostFrequentLetter = '\0';
int mostFrequentLetterCount = 1;
for (String word : sentence) {
int charCount = 1;
char localChar = '\0';
for (int wordIndex = 0; wordIndex < word.length(); wordIndex++) {
char currentLetter = word.charAt(wordIndex);
if (currentLetter != ' ' && currentLetter != mostFrequentLetter) {
for (int l = wordIndex + 1; l < word.length(); l++) {
char nextLetter = word.charAt(l);
if (currentLetter == nextLetter) {
localChar = currentLetter;
charCount++;
}
}
}
}
if (charCount > mostFrequentLetterCount) {
mostFrequentLetterCount = charCount;
mostFrequentLetter = localChar;
}
}
}
Now all I did was rename your variables and change your for loop to a for-each loop. By doing this you can see more clearly your algorithm and what you're trying to do. Basically you're going through each word and comparing the current letter with the next letter to check for duplicates. If I run this with "I like" i should get i 2 but instead I get null char 1. You aren't properly comparing and saving common letters. This isn't giving you the answer, but I hope this makes it more clear what your code is doing so you can fix it.
Here is a somewhat more elegant solution
public static void FindMostPopularCharacter(String input)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
input = input.toUpperCase();
HashMap<Character, Integer> charData = new HashMap<>();
char occursTheMost = 'A'; //start with default most popular char
int maxCount = 0;
//create the map to store counts of all the chars seen
for(int i = 0; i < alphabet.length(); i++)
charData.put(alphabet.charAt(i), 0);
//first find the character to look for
for(int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
//if contained in our map increment its count
if(charData.containsKey(c))
charData.put(c, charData.get(c) + 1);
//check for a max count and set the values accordingly
if(charData.containsKey(c) && charData.get(c) > maxCount)
{
occursTheMost = c;
maxCount = charData.get(c);
}
}
//final step
//now split it up into words and search which contain our most popular character
String[] words = input.split(" ");
int wordCount = 0;
CharSequence charSequence;
for(Character character : charData.keySet())
{
int tempCount = 0;
charSequence = "" + character;
for(int i = 0; i < words.length; i++)
{
if(words[i].contains(charSequence))
tempCount++;
}
if(tempCount > wordCount)
{
occursTheMost = character;
wordCount = tempCount;
}
}
System.out.println(occursTheMost + " " + wordCount);
}
Output of
String input = "I like visiting my friend Will, who lives in Orlando, Florida.";
FindMostPopularCharacter(input);
is
I 8
Note: If there are ties this will only output the character that first reaches the maximum number of occurrences.
FindMostPopularCharacter("aabb aabb aabb bbaa");
Outputs
B 4
because B reaches the max first before A due to the last word in the input.
FindMostPopularCharacter("aab aab b")
B 3

how to deal with integers and flip them

haw can i flip an integer at a certain index
for example i have this number 1001 and i need to flip it starting from index 2
the result is going to be 1010
here is what i tried any easier ways?
public class TEST {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int code = scan.nextInt();
int index = scan.nextInt();
String s = code + "";
String f = "";
for (int i = s.length() - 1; i >= index; i--) {
f += s.charAt(i);
}
for (int i = 0; i < index; i++) {
f += s.charAt(i);
}
System.out.println(f);
}
}
Another question is that haw i shift every digit to the left for example if i have 1001 it will become 1100
You could use the reverse() method of the StringBuilder class to reverse the number and then parse it back as an integer. Use the StringBuilder as follows:
StringBuilder num = new StringBuilder("1234");
num.reverse(); // is now "4321"
To parse the integer:
int i = Integer.parseInt(num.toString());
I believe this is what you are looking for. This assumes you are using a 0-indexed system for choosing where the reversal starts.
Scanner scan = new Scanner(System.in);
int code = scan.nextInt();
int index = scan.nextInt();
String s = code + "";
String f = s.substring(0, index);
for(int i = index; i < s.length(); i++)
f += s.charAt(s.length() - (i - index) - 1);
System.out.println(f);
Your flip operation if I assume that you mean that a string such as 12345 consists of indices [1,2,3,4,5] rather than [0,1,2,3,4]˙ and starting from index of 1 is inclusive flip from 1 to 5, and your operation goes from left to right, then you can do the following
int index = 1;
String number = "12345";
String subnumber = number.substring(index - 1); //first index, 0th character
String reversedNumber = new StringBuilder(subnumber).reverse().toString();
String result = number.substring(0, index - 1) + reversedNumber;
System.out.println(result); //54321
Of course, if it was supposed to from right to left, then you need to mess with the length of the String and mirror the operations...

Reverse a string then swap every nth letter

I've been stuck on this problem for two hours now. Basically I need to reverse a string (which I've done no problem), then swap every nth letter (which is where im stuck).
Here is what I have so far:
public class StringMethods {
public static void main(String[] args) {
String s = "Hey there";
int n = 2;
System.out.println(reverseString(s));
System.out.println(reverseStringChallenge(s, n));
}
private static String reverseString(String s) {
String reversed = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i);
}
return reversed;
}
private static String reverseStringChallenge(String s, int n) {
String reversed = "";
String swapped = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i); // normal reverse
}
char [] charArray = reversed.toCharArray(); //Strings are immutable, convert string to char array
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0) {
//this is where im stuck
}
}
return swapped;
}
}
I know that strings are immutable in java so I need to convert the reversed string into a char array, and then loop through the array but not sure what to do here.
Any advice would be really appreciated. its doing my head in.
Edit: sorry what I mean by swap every nth letter is that say n = 2. then every second letter gets swapped with its previous one.
You didn't clarify the swap logic, but how about something like this:
for(int i = n; i < charArray.length; i += n) {
char a = charArray[i-n];
char b = charArray[n];
charArray[i-n] = b;
charArray[n] = a;
}
Here's a basic swap
int n = 1;
int n1 = 2;
int temp = n; // variable to hold n value
n = n2; // make n = n2
n2 = temp; // make n2 = n
// now n = 2
// and n2 = 1
Not really sure from your question what it is you're trying to do, so I can't really give a definite answer
If you are swapping the current char with the next char you could do something like:
private static String reverseStringChallenge(String s, int n)
{
String reversed = StringUitls.reverse(s);
StringBuilder sb = new StringBuilder();
char [] charArray = reversed.toCharArray();
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0)
{
sb.append(charArray[i+1]).append(charArray[i]);
i++;
}else{
sb.append(charArray[i]);
}
}
return sb.toString();
}
I'm excuse null and out of bound checks =) good luck

How do you reverse a string character by character in java?

Let's say I have a string with the phrase "Bank of America". I want to reverse it so the output results in "aciremA fo knaB"
This is the code I have been trying to use but the output is only the last letter of the last word, which would be "a"
int position = phraseLength;
for(int index = position-1; index >= 0; index--);
System.out.println(p1.charAt(position-1));
I am not sure what is wrong here so any help would be appericated.
StringBuffer sb=new StringBuffer("Bank of America");
System.out.println(sb.reverse());
If you want to do it your way. use
int position = phraseLength;
for(int index = position-1; index >= 0; index--)
System.out.println(p1.charAt(index));
You have added an extra semicolon after for loop here
for(int index = position-1; index >= 0; index--);
^
Also you are always accessing the postion-i. You should access the index
System.out.println(p1.charAt(position-1));
^^^^^^^^^^^
here
You can use this
int position = phraseLength;
for(int index = position-1; index >= 0; index--)
System.out.print(p1.charAt(index));
or this
String output = "";
int position = phraseLength;
for(int index = position-1; index >= 0; index--)
output+=p1.charAt(index);
System.out.println(output);
public String reverse(String str) {
char [] buffer = str.toCharArray();
for (int i = 0, j = buffer.length - 1; i < j; i++, j--) {
char temp = buffer[i];
buffer[i] = buffer[j];
buffer[j] = temp;
}
return new String(buffer);
}
I guess by mistake you have added the semicolon after for loop. Practically this will not give any compile time error. But the content of the loop will be executed only once. So remove the semicolon and get it done !!
StringBuffer stringBuffer=new StringBuffer("Bank of America");
System.out.println(stringBuffer.reverse());
Declare a string.
Take out the length of that string.
Loop through the characters of the string.
Add the characters in reverse order in the new string.
String str = "hello";
String reverse = "";
int length = str.length();
for (int i = 0; i < length; i++) {
reverse = str.charAt(i) + reverse;
}
System.out.println(reverse);

Categories