How to reverse integers using while or for loop - java

Sorry, I am new to java. I want to create a program that displays reversed integers using any kind of loop. For example I would ask user to enter a positive integer and then I would return reversed input to the user. So far this is the closest I got, but I get the count of the string in reverse and not the values that were captured.
String number;
for (int c = number.length(); c >= 0; c--) {
System.out.print(c);
}

String number;
for (int c = number.length() - 1; c >= 0; c--){
System.out.print(number.charAt(c));
}
This should do the trick. c is the position in your string, use it to print the char at that position.
(Also, remember it's String, not string. Same for System)
Edit: Oops, forgot to add the "-1" in number.length()

You can try something likewise(either of way),
public static void main(String[] args) {
String number = "hello";
for (int c = number.length()-1; c >= 0; c--)
{
System.out.print(number.charAt(c));
}
// At the end output is : olleh
System.out.println();
// Or another way is, using StringBuffer
StringBuffer sb = new StringBuffer("Hello String");
System.out.println(sb.reverse()); //Output :- gnirtS olleH
}

Related

Reversing strings in Java (loops) until "done"

this is a lab for class I'm trying to do. Here's the instructions:
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
"Hello there
Hey
done"
the output is:
"ereht olleH
yeH"
And here's what I have right now:
public class LabProgram {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
String[] inputs = new String[100];
String input;
int i = 0;
while (true) {
input = scnr.nextLine();
if(input.equals("Done") || input.equals("done") || input.equals("d"))
break;
inputs[i] = input;
i++;
}
for (int j = 0; j < i; j++) {
int length = inputs[j].length();
String reverse = "";
for (int k = length - i; k >= 0; k--) {
reverse = reverse + inputs[j].charAt(k);
}
System.out.print("\n" + reverse);
}
}
}
Current output
What am I doing wrong??
Iterate through the array, and reverse elements at every index.
This solution is time consuming but does your job
for (int j = 0; j < inputs.lenght; j++) {
int length = inputs[j].length();
char a;
String rev = "";
for(int i =0; i< length; i++){
a = inputs[j].charAt(i);
rev = a + rev;
}
System.out.println(rev);
}
*Try to use StringBuilder And use method reverse -- #Artur Todeschini
To add to what Artur said, an ArrayList of StringBuilders could do the trick quite well:
for(StringBuilder nextEntry : stringBuilderList)
{
nextEntry.reverse();
}
The enhanced for-loop will go through each entry in the ArrayList, and the StringBuilder's reverse will change the order of the letters.
EDIT TO SHOW FORMATTING
ArrayList<StringBuilder> stringBuilderList= new ArrayList<>();
*note. given that this is for a lab, its probably for learning purposes and using built-in classes that does all the work for you are usually not the intended solution. -- #experiment unit 1998X
Try to use StringBuilder
And use method reverse
This is another "ArrayList and StringBuilder-less" version.
Create two Strings, one filled and one empty:
String nextString = stringArray[i],
template = new String();
Loop through the length of the String, adding the next character in from the end each time through.
int length = nextString.length() - 1;
for(int j = 0; j < length; j++)
{
template += nextString.charAt(length - j);
}
Add the whole String to the String array's index
stringArray[i] = template;
NOTE
This is an inner loop for a String array and is NOT complete code

Print a string backwards and shifted once ex: cat = ubd

I have successfully printed my String backwards, but I'm having a hard time getting it to shift forward a letter. My outputs have been numbers instead of letters, so I have tried to convert those numbers back to letters unsuccessfully. There is other code in this as well, but I only need help with this one bit.
package inlämningsuppgift4;
import java.util.Scanner;
public class Inlämningsuppgift4 {
public static void word(String w1){
//char a[]= w1.toCharArray();
for (int i=w1.length()-1; i>=0; i--)
//char c = 'a';
//c = (char) (((c - 'a' - 1) % 26) + 'a');
{System.out.print(w1.charAt(i));
}
System.out.println();
}
public static void word2(String w2){
for (int j=0;j<w2.length(); j++)
{System.out.print("*"+w2.charAt(j));
}
System.out.println("*");
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Ange ett ord: ");
String ord = input.nextLine();
word2(ord);
word(ord);
}
}
It seems like I was on the right path trying to set up "//char c" but I couldn't get it to function as written. I got that code from a questions search, but can't wrap my head around it. How do I make it fit with my code already written? Or should I find a different way?
You have two different problems:
reversing a string. There are a lot of ways to do it.
String s1 = "cat";
String s2 = "";
for (int i =0 ; i < s1.length(); i++) {
s2 = s1.charAt(i) + s2;
}
System.out.println(s2);
So just create a new string by adding strings backwards.
"Shifting" a character, which presumably means taking the code-point and modifying it, and possibly wrapping it (eg: Z wraps to A, instead of moving forward to [)
String s1 = "cat";
String s2 = "";
for (int i =0 ; i < s1.length(); i++) {
char c = s1.charAt(i);
c += 1;
// reverse string implementation omitted
}
System.out.println(s2);
Java seems to let you add directly to char so whatever works. Note that this does not care about wrapping, so z would not wrap to a. That's up to you to figure out.
Now you just need to combine that with the string building.

Counting the number of specific occurrences in a java String

I am attempting to solve a problem where I create a method that counts the number of occurrences of capital and lowercase ("A" or "a") in a certain string. I have been working on this problem for a week now, and the main error that I am receiving is that "char cannot be dereferenced". Can anyone point me in the correct direction on this Java problem? Thank you.
class Main{
public static int countA (String s)
{
String s1 = "a";
String s2 = "A";
int count = 0;
for (int i = 0; i < s.length; i++){
String s3 = s.charAt(i);
if (s3.equals(s1) || s3.equals(s2)){
count += 1;
}
else{
System.out.print("");
}
}
}
//test case below (dont change):
public static void main(String[] args){
System.out.println(countA("aaA")); //3
System.out.println(countA("aaBBdf8k3AAadnklA")); //6
}
}
try a simpler solution
String in = "aaBBdf8k3AAadnklA";
String out = in.replace ("A", "").replace ("a", "");
int lenDiff = in.length () - out.length ();
Also as #chris mentions in his answer, the String could be converted to lowercase first and then only do a single check
the main error that I am receiving is that "char cannot be
dereferenced"
change this:
s.length // this syntax is incorrect
to this:
s.length() // this is how you invoke the length method on a string
also, change this:
String s3 = s.charAt(i); // you cannot assign a char type to string type
to this:
String s3 = Character.toString(s.charAt(i)); // convert the char to string
another solution to accomplishing your task in a simpler manner is by using the Stream#filter method. Then convert each String within the Stream to lowercase prior to comparison, if any Strings match "a" we keep it, if not we ignore it and at the end, we simply return the count.
public static int countA(String input)
{
return (int)Arrays.stream(input.split("")).filter(s -> s.toLowerCase().equals("a")).count();
}
For counting the number of time 'a' or 'A' appears in a String:
public int numberOfA(String s) {
s = s.toLowerCase();
int sum = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == 'a')
sum++;
}
return sum;
}
Or just replace everything else and see how long your string is:
int numberOfA = string.replaceAll("[^aA]", "").length();
To find the number of times character a and A appear in string.
int numA = string.replaceAll("[^aA]","").length();

how to revearse a string?

Cant seem to get this to work. trying to get it to read backwards like a mirror without using the buffer class.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System. in);
System.out.println("Enter a phrase:");
String phrase = keyboard.nextLine();
String Rphrase;
int n = phrase.length();
int r = 0;
do{
n--; r++;
Rphrase[r] = phrase[n];
}while(n >= 0);
System.out.println(Rphrase);
I have provided 4 ways of getting the output of the String reversed.
Option 1:
Just iterate the String backwards.
for (int i=phrase.length()-1; i>-1; i--) {
System.out.print(foo.charAt(i));
}
Option 2:
If you would like to put it in the other buffer you can do:
char[] buffer = new char[phrase.length()];
index = 0;
for (int i=phrase.length()-1; i>-1; i--) {
buffer[index++] = foo.charAt(i);
}
Option 3:
You said you didnt want to use the buffer class (which I think you're referring to StringBuffer so I'm assuming you dont want to use StringBuilder either) so here is how you can do it strictly with Strings (which is rather inefficient, because a new String is constructed each iteration):
String foo = "";
for (int i=phrase.length()-1; i>-1; i--) {
foo += foo.charAt(i);
}
Option 4:
A most likely more efficient way of doing this though, is by using StringBuilder:
StringBuilder sb = new StringBuilder(foo.length());
for (int i=foo.length()-1; i>-1; i--) {
sb.append(foo.charAt(i));
}
String reverse = sb.toString();
OR
Refer to this for very simple String reversal with a StringBuilder:
Reverse a string in Java
Try:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System. in);
System.out.println("Enter a phrase:");
String phrase = keyboard.nextLine();
String rPhrase = "";
for (int i = phrase.length() - 1; i >= 0; i--)
rPhrase += phrase.charAt(i);
System.out.println(rPhrase);
}
This is what you need.
String reverse = "";
String toReverse = "hello";
for(int i = 0; i<toReverse.length();i++){
reverse += toReverse.substring(i,i+1);
}
System.out.println(reverse);
Some hints, rather than a complete solution...
Your loop will run for one more iteration when n = 0, which will lead to trying to access index -1. So perhaps try n > 0 as your condition.
And what would happen if the string is empty? It would also try to access index -1, before ever getting to the loop. Perhaps you should put the condition at the beginning.
String doesn't support the [] operator - try:
Rphrase += phrase.charAt(n);
In which case you may as well get rid of r.
you have to make a decrement so it can read its value back to front
for (int i = name.length() - 1, j = 0; i >= 0; i--, j++) {
newName[j] = name.charAt(i); enter code here
}
System.out.println(newName);
}
Simply use StringBuilder.reverse
str = new StringBuilder(str).reverse().toString();

Help testing two words, then printing the cross of where the same chars are

i'm trying to make a program that reads two English words from the command line, then outputs all possible ways the words can cross eachother. and print an error message if they do not cross. i want to use the charAt and length methods.. not sure where to even start..
here's what i got so far:
public class Cross2
{
public static void main(String[] args)
{
// create two dimentional array that stores input
private String[][] cross = new String[w1pos][w2pos];
// get input from user
Scanner input = new Scanner(System.in);
System.out.println("Enter two words: ");
String word1 = input.next();
String word2 = input.next();
// loop through length of words
for(int w1pos = 0; w1pos < word1.length(); w1pos++) {
for(int w2pos = 0; w2pos < word2.length(); w2pos++) {
// if characters are equal, print the array
if (word1.charAt(w1pos) == word2.charAt(w2pos))
System.out.println(cross[w1pos][w2pos]);
}
}
i think so. i would need to loop through the length of the string, then use charAt(i) to print each character.
That's a good start.
and yes crossing as in letter matching.. so i need to compare each character using charAt for each position in each of the two words
That's good. Hint: So how many loops?
and print an error message if they do not cross
Hint: ... and how will you do that?
Don't answer my questions. They are hints. Write some code based one them.
So for the words "abra" and "cadabra", would the output look like this?
c
abra
d
a
b
r
a
c
a
d
abra
b
r
a
c
a
d
a
b
r
abra
c
a
d
a
abra
r
a
c
a
d
a
b
abra
a
c
abra
d
a
b
r
a
c
a
d
abra
b
r
a
c
a
d
a
b
r
abra
If so, I would recommend that you use a two-dimensional array of characters filled with spaces that you write the words into before displaying. Printing each character one at a time might be significantly more difficult.
[edit:]
I don't know Java so I couldn't use functions and I couldn't write much more than what you had, but I hope this helps.
// This is a comment explaining what the code does.
.
/* This is a comment explaining what you need to add to make the code work. */
.
public class Cross2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter two words: ");
String word1 = input.next();
String word2 = input.next();
String[][] cross = new String[word1.length()][word2.length()];
/* Fill 'cross' with spaces */
for(int w1pos = 0; w1pos < word1.length(); w1pos++) {
for(int w2pos = 0; w2pos < word2.length(); w2pos++) {
if (word1.charAt(w1pos) == word2.charAt(w2pos)) {
// Store 'word1' horizontally into 'cross'.
for(int w1posAgain = 0; w1posAgain < word1.length(); w1posAgain++) {
/* Store 'word1.charAt(w1posAgain)' horizontally into 'cross'
at row 'w2pos' and column 'w1posAgain'. */
}
// Store 'word2' vertically into 'cross'.
for(int w2posAgain = 0; w2posAgain < word2.length(); w2posAgain++) {
/* Store 'word2.charAt(w2posAgain)' vertically into 'cross'
at row 'w2posAgain' and column 'w1pos'. */
}
for(int w1posAgain = 0; w1posAgain < word1.length(); w1posAgain++) {
for(int w2posAgain = 0; w2posAgain < word2.length(); w2posAgain++) {
System.out.print(cross[w1posAgain][w2posAgain]);
}
System.out.println();
}
/* Fill 'cross' with spaces.
Yes, really.*/
}
}
}
}
}

Categories

Resources