How to reverse a String converting int to String? - java

import java.util.Scanner;
public class Lab7 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Type the integer you'd like to be reversed:");
int num = s.nextInt();
String strNum = ""+num;
reverse(s1);
System.out.println(reverse(s1));
}
public static int reverse(int strNum) {
String s1 = Integer.toString(strNum);
for(int i=s1.length()-1;i>=0;i--){
System.out.print(s1.charAt(i));
}
return 0;
}
}
Pretty straight forward - I want to reverse my input of numbers, but I am unable to.
There are errors at 'reverse(s1);' and 'System.out.println(reverse(s1));' , as s1 is not recognized. I cannot figure out the cause.

Your code will not compile as is. s1 is not in main method and reverse method is accepting an int not String.
Also, if you need to return an int from your method why not the reversed int which is the answer.
Few edits to your code which will solve your issue.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Type the integer you'd like to be reversed:");
int num = s.nextInt();
System.out.println(reverse(num));
}
public static int reverse(int num) {
String strNum = String.valueOf(num);
StringBuffer sb = new StringBuffer();
for(int i=strNum.length()-1;i>=0;i--)
sb.append(strNum.charAt(i));
return Integer.parseInt(sb.toString());
}

import java.util.Scanner;
public class Lab7 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Type the integer you'd like to be reversed:");
int num = s.nextInt();
String strNum = ""+num;
reverse(strNum);
}
public static int reverse(String strNum) {
String s1 =strNum;
for(int i=s1.length()-1;i>=0;i--){
System.out.print(s1.charAt(i));
}
return 0;
}
}

You don't have any variable s1
you assigned value of string number to 'strNum', So use it instead
Also you have to use string as argument type in definition of reverse()
import java.util.Scanner;
public class Lab7 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Type the integer you'd like to be reversed:");
int num = s.nextInt();
String strNum = ""+num;
reverse(s1);
System.out.println(reverse(s1));
}
public static int reverse(String strNum) {
for(int i=strNum.length()-1;i>=0;i--){
System.out.print(strNum.charAt(i));
}
return 0;
}
}

StringBuilder sb = new StringBuilder("your string");
String result = sb.reverse().toString();

// ===============try the below code===============================
public static void main(String sr[])
{
Scanner s = new Scanner(System.in);
System.out.println("Type the integer you'd like to be reversed:");
int num = s.nextInt();
String strNum = ""+num;
String inputString = String.valueOf(num);
StringBuilder builder = new StringBuilder(inputString);
System.out.println(builder.reverse());
}

You can easily use stack , below is a simple implementation of reversing a string by using stack. You can easily change the code for Integer, The complexity is O(n) which is good i think.
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
String retVal = "";
Scanner s = new Scanner(System.in);
try {
String nextStr = String.valueOf(s.nextInt());
for (int i = 0; i < nextStr.length(); i++) {
stack.push(String.valueOf(nextStr.charAt(i)));
}
for (int i = 0; i < nextStr.length(); i++) {
retVal+=stack.pop();
}
System.out.println(retVal);
} finally {
s.close();
}
}

import java.util.Scanner;
public class Lab7 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Type the integer you'd like to be reversed:");
int num = s.nextInt();
System.out.println(new StringBuilder(String.valueOf(num)).reverse().toString());
}
}
we can use stringBuffer or StringBuilder for reversing

Related

Methods - Convert Integer to Binary

Prompt: I need to create code using 2 methods to convert an Integer to binary. This is on zybooks and it has run successfully but it is saying some some of the output is wrong.
My code:
public static String intToReverseBinary(int integerValue) {
String reverseBinary = "";
int x = integerValue;
while (x != 0) {
int remainder = x % 2;
x = x /2;
reverseBinary = reverseBinary + Integer.toString(remainder);
}
return stringReverse(reverseBinary);
}
public static String stringReverse(String inputString) {
String reversed = "";
for (int i = inputString.length() - 1; i >= 0; i--) {
reversed = reversed + inputString.charAt(i);
}
return reversed;
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int userInput = scnr.nextInt();
System.out.println(intToReverseBinary(userInput));
}
It says: Convert 19 to binary using intToReverseBinary() and stringReverse()
Your output
intToReverseBinary(19) incorrectly returned 10011. But isn't that correct?
import java.util.Scanner;
public class LabProgram {
/* Define your methods here */
public static String intToReverseBinary(int integerValue){
String reverseBinary="";
while (integerValue>0){
int remainder = integerValue % 2;
integerValue = integerValue /2;
reverseBinary = reverseBinary + Integer.toString(remainder);
}
return reverseBinary;
}
public static String stringReverse(String inputString){
String reversed = "";
for (int i = inputString.length() - 1; i >= 0; i--) {
reversed = reversed + inputString.charAt(i);
}
return reversed;
}
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int userint;
userint=s.nextInt();
System.out.println(stringReverse((intToReverseBinary(userint))));
}
}

What is wrong with this code-(I have to find the no. of letters in longest word)

I print out st and it gives the last word.But on printing int lon,which is to count the highest no. of letters in a particular word,it returns 0....
import java.util.Scanner;
class Scn
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int i,a;
int len=0;int lon =0;
String st="";
char b;
a = s.length();
for(i =0;i<a;i++)
{
b = s.charAt(i);
if(b ==' ')
{
if(len>lon)
len=lon;
st="";/makes st empty
}
else
{
st=st+b;
len=st.length();/Count no. of letters
}
}
System.out.println(lon);
}
}
Change len = lon; to lon = len;
That should do the trick.

Java: loop doesn't work, errors with variables initialization

Could you please explain why this loop doesn't work in case if user types "yes" and why there are errors with variables initialisations.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner src;
String amount;
String counterparty;
String dt;
String ct;
System.out.println("Create new transaction:yes/no");
Scanner abc = new Scanner(System.in);
String g = abc.nextLine();
if (g=="yes") {
System.out.println("Amount of transaction:");
src = new Scanner(System.in);
amount = src.nextLine();
System.out.println("Counterparty:");
counterparty = src.nextLine();
System.out.println("Dt:");
dt = src.nextLine();
System.out.println("Ct:");
ct = src.nextLine();
}
else if (g=="no") {
amount="0";
}
System.out.println("Transaction:");
ArrayList <String> Provodka = new ArrayList();
Provodka.add(amount);
Provodka.add(counterparty);
Provodka.add(dt);
Provodka.add(ct);
for (int i = 0; i < Provodka.size(); i++) {
String value = Provodka.get(i);
System.out.println("Element: " + value);
}
}
}
Just initialize the local variables and use equals() method instead of "=="
public static void main(String args[]) {
Scanner src;
String amount = null;
String counterparty = null;
String dt = null;
String ct = null;
System.out.println("Create new transaction:yes/no");
Scanner abc = new Scanner(System.in);
String g = abc.nextLine();
if (g.equals("yes"))
{
System.out.println("Amount of transaction:");
src = new Scanner(System.in);
amount = src.nextLine();
System.out.println("Counterparty:");
counterparty = src.nextLine();
System.out.println("Dt:");
dt = src.nextLine();
System.out.println("Ct:");
ct = src.nextLine();
}
else if (g.equals("no")){
amount="0";
}
System.out.println("Transaction:");
ArrayList <String> Provodka = new ArrayList();
Provodka.add(amount);
Provodka.add(counterparty);
Provodka.add(dt);
Provodka.add(ct);
for (int i = 0; i < Provodka.size(); i++) {
String value = Provodka.get(i);
System.out.println("Element: " + value);
}
}
In your string comparison you are comparing strings with '==' .
Use equals() method to compare strings.
eg:-
if ("yes".equals(g)){
}
Firstly, there is a lot of unnecessary declaration of Scanner. Using one variable for scanner will work for all inputs. Secondly, declare your variables above the main method and make them static, here you will not always need to initialise them. Finally, use g.equalsIgnoreCase("yes") instead of g == "yes", this way if you type yes in CAPS or not it will still register. Try what was done below
public static String g;
public static String amount;
public static String counterparty;
public static String dt;
public static String ct;
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Create new transaction:yes/no");
g= s.nextLine();
if (g.equalsIgnoreCase("yes")) {
System.out.println("Amount of transaction: ");
amount = s.nextLine();
System.out.println("Counterparty: ");
counterparty = s.nextLine();
System.out.println("Dt: ");
dt = s.nextLine();
System.out.println("Ct: ");
ct = s.nextLine();
}
else if (g.equalsIgnoreCase("no")) {
amount = "0";
}
System.out.println("Transaction:");
ArrayList <String> Provodka = new ArrayList();
Provodka.add(amount);
Provodka.add(counterparty);
Provodka.add(dt);
Provodka.add(ct);
for (int i = 0; i < Provodka.size(); i++) {
String value = Provodka.get(i);
System.out.println("Element: " + value);
}
}
}

Capitalize every word using Scanner(System.in) Java

This code should allow the user to input a sentence, change it to lower case, and then capitalize the first letter of each word. But I can't get the scanner to work, it just prints nothing. Any suggestions?
public class Capitalize
{
public static void capCase(String theString)
{
String source = theString;
StringBuffer res = new StringBuffer();
char[] chars = theString.toLowerCase().toCharArray();
boolean found = false;
for(int i = 0; i<chars.length; i++)
{
if(!found&& Character.isLetter(chars[i])){
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i])){
found = true;
}
}
}
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
System.out.println(scanner.next());
}
}
Problems as I see them:
The code as it stands will only print the first word typed in once the user presses enter
The method doesn't return anything, so effectively it does all that work and discards it.
So here is what I might do:
I'm going to put everything in main for the sake of concision
public class Capitalize {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String sentence = Scanner.nextLine();
StringBuilder ans = new StringBuilder(); // result
for(String s : sentence.split(" ")) { // splits the string at spaces and iterates through the words.
char[] str = s.toLowerCase().toCharArray(); // same as in OPs code
if(str.Length>0) // can happen if there are two spaces in a row I believe
str[0]=Character.toUpperCase(str[0]); // make the first character uppercase
ans.Append(str); // add modified word to the result buffer
ans.Append(' '); // add a space
}
System.out.println(ans);
}
}
You forgot to call the capCase() method, your code only asks for input from stdin and prints it out straight
I tried running the program in main method it runs fine for me. But if you want to get the whole sentence you will have to call scanner like an iterator and then get each next token bu calling scanner.next() method Scanner deliminates words in a sentence on the basis of white spaces. my example implementation is as follows. The you can pass each word in the your function to process it.
`public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
while (scanner.hasNext())
System.out.println(scanner.next());
}`
I would probably do this
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) { // While there is input.
String line = scanner.nextLine(); // read a line.
int i = 0;
for (String s : line.split(" ")) { // split on space... word(s).
if (i != 0) {
System.out.print(" "); // add a space, except for the first word on a line.
}
System.out.print(capCase(s)); // capCase the word.
i++; // increment our word count.
}
System.out.println(); // add a line.
System.out.flush(); // flush!
}
}
public static String capCase(String theString) {
if (theString == null) {
return ""; // Better safe.
}
StringBuilder sb = new StringBuilder(theString
.trim().toLowerCase()); // lowercase the string.
if (sb.length() > 0) {
char c = sb.charAt(0);
sb.setCharAt(0, Character.toUpperCase(c)); // uppercase the first character.
}
return sb.toString(); // return the word.
}
Problem :
1.you need to send the complete Line and send the String to the function capCase()
2.You are not returning the char array back to the caller.
Solution
1.use the below statement to read complete Line
String str=scanner.nextLine();
2.Change return type of capCase() from void to char[] as below:
public static char[] capCase(String theString)
you should return the char[] variable chars from capCase() function as below:
return chars;
Complete Code:
public static char[] capCase(String theString)
{
String source = theString;
StringBuffer res = new StringBuffer();
char[] chars = theString.toLowerCase().toCharArray();
boolean found = false;
for(int i = 0; i<chars.length; i++)
{
if(!found&& Character.isLetter(chars[i])){
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i])){
found = true;
}
}
return chars;
}
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
String str=scanner.nextLine();
System.out.println(capCase(str));
}
Try,
public static void main(String[] args) {
System.out.println(capCase("hello world"));
}
public static String capCase(String theString) {
StringBuilder res = new StringBuilder();
String[] words=theString.split(" +");
for (String word : words) {
char ch=Character.toUpperCase(word.charAt(0));
word=ch+word.substring(1);
res.append(word).append(" ");
}
return res.toString();
}
Try this code it worked for me:
import java.util.Scanner;
public class Capitalize {
/**
* This code should allow the user to input a sentence, change it to lower
* case, and then capitalize the first letter of each word. But I can't get
* the scanner to work, it just prints nothing. Any suggestions?
*
* #param theString
*/
public static void capCase(String theString) {
String source = theString.trim();
StringBuffer res = new StringBuffer();
String lower = theString.toLowerCase();
String[] split = lower.split(" ");
for (int i = 0; i < split.length; i++) {
String temp = split[i].trim();
if (temp.matches("^[a-zA-Z]+")) {
split[i] = temp.substring(0, 1).toUpperCase()
+ temp.substring(1);
}
res.append(split[i] + " ");
}
System.out.println(res.toString());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
capCase(scanner.nextLine());
// System.out.println(scanner.next());
}
}
I've tested it. It works.
import java.util.Scanner;
import org.apache.commons.lang3.text.WordUtils;
public class Capitalize {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(s.hasNextLine()) {
System.out.println(WordUtils.capitalize(s.nextLine()));
}
}
}

How to reverse words of a Java String

Im trying to make a program to take input for a string from the scanner, but i want to break up the string that was inputed and reverse the order of words. This is what i have so far.
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
StringBuilder welcome = new StringBuilder(input.next());
int i;
for( i = 0; i < welcome.length(); i++ ){
// Will recognize a space in words
if(Character.isWhitespace(welcome.charAt(i))) {
Character a = welcome.charAt(i);
}
}
What I want to do is after it recognizes the space, capture everything before it and so on for every space, then rearrange the string.
Edit after questions.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main( String[] args ) {
final String welcome = "How should we get words in string form a List?";
final List< String > words = Arrays.asList( welcome.split( "\\s" ));
Collections.reverse( words );
final String rev = words.stream().collect( Collectors.joining( ", " ));
System.out.println( "Your sentence, reversed: " + rev );
}
}
Execution:
Your sentence, reversed: List?, a, form, string, in, words, get, we, should, How
I did suggest first reverse the whole string.
Then reverse the substring between two spaces.
public class ReverseByWord {
public static String reversePart (String in){
// Reverses the complete string
String reversed = "";
for (int i=0; i<in.length(); i++){
reversed=in.charAt(i)+reversed;
}
return reversed;
}
public static String reverseByWord (String in){
// First reverses the complete string
// "I am going there" becomes "ereht gniog ma I"
// After that we just need to reverse each word.
String reversed = reversePart(in);
String word_reversal="";
int last_space=-1;
int j=0;
while (j<in.length()){
if (reversed.charAt(j)==' '){
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, j));
word_reversal=word_reversal+" ";
last_space=j;
}
j++;
}
word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, in.length()));
return word_reversal;
}
public static void main(String[] args) {
// TODO code application logic here
System.out.println(reverseByWord("I am going there"));
}
}
Here is the way you can reversed the word in entered string:
Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
String s = input.next();
if(!s.trim().contains(' ')) {
return s;
}
else {
StringBuilder reversedString = new StringBuilder();
String[] sa = s.trim().split(' ');
for(int i = sa.length() - 1; i >= 0: i - 1 ) {
reversedString.append(sa[i]);
reversedString.append(' ');
}
return reversedString.toString().trim();
}
Hope this helps.
If you wanted to reduce the number of line of code, I think you can look into my code :
package com.sujit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class StatementReverse {
public static void main(String[] args) throws IOException {
String str;
String arr[];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string:");
str = br.readLine();
arr = str.split("\\s+");
for (int i = arr.length - 1;; i--) {
if (i >= 0) {
System.out.print(arr[i] + " ");
} else {
break;
}
}
}
}
public class StringReverse {
public static void main(String[] args) {
String str="This is anil thakur";
String[] arr=str.split(" ");
StringBuilder builder=new StringBuilder("");
for(int i=arr.length-1; i>=0;i--){
builder.append(arr[i]+" ");
}
System.out.println(builder.toString());
}
}
Output: thakur anil is This
public class ReverseWordTest {
public static String charRev(String str) {
String revString = "";
String[] wordSplit = str.split(" ");
for (int i = 0; i < wordSplit.length; i++) {
String revWord = "";
String s2 = wordSplit[i];
for (int j = s2.length() - 1; j >= 0; j--) {
revWord = revWord + s2.charAt(j);
}
revString = revString + revWord + " ";
}
return revString;
}
public static void main(String[] args) {
System.out.println("Enter Your String: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(charRev(str));
}
public static void main(String[]args)
{
String one="Hello my friend, another way here";
String[]x=one.split(" ");
one="";
int count=0;
for(String s:x){
if(count==0||count==x.length) //that's for two edges.
one=s+one;
else
one=s+" "+one;
count++;
}
System.out.println(one); //reverse.
}

Categories