Is there an easier way to write this? [duplicate] - java

This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 4 years ago.
There are some assignments in Walter Savitch's Java book, where it asks you to write some code to reverse the order of a word that is entered. I came up with the following and am wondering if I could be able to optimize it as it seems a little heavy:
public static void main(String[] args) {
String statement;
System.out.print("Enter a statement to reverse: ");
statement = keyboard.nextLine();
int n;
String finalWord = "";
String letter;
for (n = statement.length(); n > 0; n--)
{
letter = statement.substring(0, 1);
finalWord = letter + finalWord;
statement = statement.substring(1);
System.out.println(finalWord);
}
System.out.println("Final work: " + finalWord);
Any insight would be appreciated.
}

import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter String To Reverse:- ");
String input = sc.next();
// convert String to character array
char[] arr = input.toCharArray();
for (int i = arr.length-1; i>=0; i--)
System.out.print(arr[i]);
}
}

You can use below given code to reverse string
public class ReversString
{
public static void main(String args[])
{
String name = "Vinayak Dwivedi";
String reverseStrinf = "";
for(int i = name.length() - 1;i >= 0 ;i--)
{
reverseStrinf = reverseStrinf + name.charAt(i);
}
System.out.println("reverseStrinf:-"+reverseStrinf);
}
}

Related

I'm trying to make the code scan for palindrome but I feel like something added in there that isn't needed. New to java so sorry if it make no sense

// I'm looking for any errors or mistakes I made in the code or another way to do it with if-then statements or usage of array. (very new to java)
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
String letter = input.nextLine();
int n = letter.length();
int numberOfLetters = 0;
for (int i = 0; i < letter.length(); i++) {
numberOfLetters++;
}
if(letter.charAt(0) != letter.charAt(n-1)){
String letter2 = letter.toLowerCase();
if (letter2.charAt(0) == letter2.charAt(n - 1)) {
System.out.println("This is a palindrome " + letter);
}
else {
System.out.println("This is not a palindrome " + letter);
}
}
}
}

to check whether a string is palindrome or not using java

import java.util.Scanner;
public class palindrome{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String rev;
for(int i=str.length()-1,k=0;i>=0 && k<str.length();i--,k++)
{
rev.charAt(k) = str.charAt(i);
}
if(rev==str)
System.out.println("string is palidrome");
else
System.out.println("string is not palindrome");
}
}
what is wrong with this code?
note: error is showing at the following line of code
rev.charAt(k)=str.charAt(i);
.charAt(k) doesn't return a location, it only tells you what character is there.
Sample code for palindrome program
import java.util.*;
class PalindromeExample2
{
public static void main(String args[])
{
String original, reverse = ""; // Objects of String class
Scanner in = new Scanner(System.in);
System.out.println("Enter a string/number to check if it is a palindrome");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string/number is a palindrome.");
else
System.out.println("Entered string/number isn't a palindrome.");
}
}

Method to check vowels in a string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
public static void main(String[] args) {
Scanner Input= new Scanner(System.in);
System.out.print("Enter String: ");
String s =Input.nextLine();
int index = s.length();
boolean isVowel= true;
isVowel = vowels(s,index);
if(isVowel==true)
System.out.println("Its Vowel");
}
public static boolean vowels(String s,int index){
String small=s.toLowerCase();
String large = s.toUpperCase();
char z=s.charAt(s.length()-1);
if (s==small) {
large = s.toUpperCase();
if(s==large){
}
for (int i = 0; i < s.length(); i++) {
if (z=='A'||z=='E'||z=='I'||z=='O'||z=='U') {
System.out.println("Character at " + s.charAt(s.length()-1) + " is a vowel");
return true;
} else if(z!='A'||z!='E'||z!='I'||z!='O'||z!='U'){
System.out.println("The String contains no Vowels");
return false;
}
}
}
return true;
}
}
It keeps returning the last printing statement, "The String contains no Vowels"
Any suggestions?
import java.util.*;
public class Solution{
public static void main(String[] args) {
Scanner Input= new Scanner(System.in);
System.out.print("Enter String: ");
String s =Input.nextLine();
if(vowels(s)) System.out.println("It contains a vowel!");
else System.out.println("It does not!");
}
public static boolean vowels(String s){
String word = s.toUpperCase();
char[] words = word.toCharArray();
for(int i = 0; i<words.length; i++){
char z = words[i];
if (z=='A'||z=='E'||z=='I'||z=='O'||z=='U') return true;
}
return false;
}
}
If I understood your question right, I think the above code should do it.

Creating a string array from random user input

I want to have a user input a random string of letters, put those in an array, then sort them alphabetically. Problem I have is putting the input into an array. What I have is:
import java.util.Scanner;
public class ArraySort {
public static void main(String[] args)
{
System.out.println("Enter letters");
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
int stringLength = input.length();
String[] stringArray = new String[stringLength];
for (int i = 0; i < stringLength; i++)
{
stringArray[i] = input;
}
System.out.println(stringArray);
}
}
This gives me [Ljava.lang.String;#55f96302 when I print.
You have two problems, you're not printing the Array correctly, and you're storing the entire input in each cell of the array. Try:
for (int i = 0; i < stringLength; i++)
{
stringArray[i] = input.charAt(i)+"";
System.out.println(stringArray[i]);
}
You are making 2 major mistakes:
1) You are assigning each string the whole input stringArray[i] = input;
2) You have to iterate over each element of your string array.
In Java8 this could be done easily with Arrays.stream().
A corrected Version of your code is:
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
System.out.println("Enter letters");
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
int stringLength = input.length();
String[] stringArray = new String[stringLength];
for (int i = 0; i < stringLength; i++)
{
stringArray[i] = Character.toString(input.charAt(i));
}
Arrays.stream(stringArray).forEach(System.out::print);
}
}
Btw. String[] stringArray=input.split(""); would be much shorter.
Additional:
If you want sorted output:
stringArray=Arrays.stream(stringArray).sorted().toArray(String[]::new);
Arrays.stream(stringArray).forEach(System.out::print);
And you are done.
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
System.out.println("Enter letters");
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
String[] stringArray=input.split("");
stringArray=Arrays.stream(stringArray).sorted().toArray(String[]::new);
Arrays.stream(stringArray).forEach(System.out::print);
}
}
To get the String form of an array, use the Arrays class toString method.
System.out.println(Arrays.toString(stringArray));
Also note the sort method of this class, although in the code's current state each item of your array will be equal to the input line.

Finding all uppercase letters of a string in java

So I'm trying to find all the uppercase letters in a string put in by the user but I keep getting this runtime error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 4
at java.lang.String.charAt(String.java:686)
at P43.main(P43.java:13)
I feel foolish but I just can't figure this out and oracle even talks about charAt on the page about java.lang.StringIndexOutOfBoundsException
Here is my code for finding the uppercase letters and printing them:
import java.io.*;
import java.util.*;
public class P43{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//Uppercase
String isUp = "";
System.out.print("Please give a string: ");
String x = in.next();
int z = x.length();
for(int y = 0; y <= z; y++){
if(Character.isUpperCase(x.charAt(y))){
char w = x.charAt(y);
isUp = isUp + w + " ";
}
}
System.out.println("The uppercase characters are " + isUp);
//Uppercase
}
}
I'd really appreciate any input and or help.
for(int y = 0; y <= z; y++){
should be
for(int y = 0; y < z; y++){
Remember array index starts from ZERO.
String length returns
the number of 16-bit Unicode characters in the string
Because loop started from ZERO, loop should terminate at length-1.
The array index out of bounds is due to the for loop not terminating on length - 1, it is terminating on length
Most iterating for loops should be in the form:
for (int i = 0; i < array.length; i++) {
// access array[i];
}
It's the same with a string.
Perhaps a cleaner way would be:
String inputString; // get user input
String outputString = "";
for (int i = 0; i < inputString.length; i++) {
c = inputString.charAt(i);
outputString += Character.isUpperCase(c) ? c + " " : "";
}
System.out.println(outputString);
Edit: Forgot String Doesn't implement Iterable<Character>, silly Java.
With Java 8 you can also use lambdas. Convert the String into a IntStream, use a filter to get the uppercase characters only and create a new String by appending the filtered characters to a StringBuilder:
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
//Uppercase
String isUp = in.next()
.chars()
.filter(Character::isUpperCase)
.collect(StringBuilder::new, // supplier
StringBuilder::appendCodePoint, // accumulator
StringBuilder::append) // combiner
.toString();
System.out.println("The uppercase characters are " + isUp);
//Uppercase
Inspired by:
Adam Bien - Streaming A String
Simplest way to print anIntStream as a String
Try this...
Method:
public int findUpperChar(String valitateStr) {
for (int i = valitateStr.length() - 1; i >= 0; i--) {
if (Character.isUpperCase(valitateStr.charAt(i))) {
return i;
}
}
return -1;
}
Usage:
String passwordStr = password.getText().toString();
.......
int len = findUpperChar(passwordStr);
if ( len != -1) {
capitals exist.
} else {
no capitals exist.
}
Hi one of the easy step to find uppercase char in a given string...
Program
import java.io.*;
public class testUpper
{
public static void main(String args[]) throws IOException
{
String data,answer="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any String : ");
data=br.readLine();
char[] findupper=data.toCharArray();
for(int i=0;i<findupper.length;i++)
{
if(findupper[i]>=65&&findupper[i]<=91) //ascii value in between 65 and 91 is A to Z
{
answer+=findupper[i]; //adding only uppercase
}
}
System.out.println("Answer : "+answer);
}
}
Output
Enter any String :
Welcome to THe String WoRlD
Answer : WTHSWRD
You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem. Also, I suggest importing the least number of libraries into your class. Please avoid using .* while importing.
import java.util.Scanner;
public class P43 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
String x = in.next();
x.chars().filter(c -> Character.isUpperCase(c))
.forEach(c -> System.out.print((char) c + " "));
}
}
Sample input:
saveChangesInTheEditor
Sample output:
C I T E
import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
StringBuilder s=new StringBuilder();
Scanner input = new Scanner(System.in);
System.out.println("Enter your String");
String str= input.nextLine();
for(int i=0; i<str.length(); i++)
{
if(Character.isUpperCase(str.charAt(i)))
{
System.out.print(str.charAt(i)+" ");
}
}
}
}
The simplest way I know is to use regex replacement.
isUp = x.replaceAll("[^A-Z]", "");
In simple terms, this uses a regular expression which matches any character which is not in the A-Z range, and replaces it with an empty string.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
String str= input.nextLine();
int ascii;
for(int i=0; i<str.length(); i++) {
ascii = str.charAt(i);
System.out.println(ascii);
if (ascii >= 65 && ascii <= 90) {
System.out.println("captal letter found ::: "+ascii);
}
}
}
public class Cama {
public static void main(String[] args) {
String camal = "getStudentByName";
String temp = "";
for (int i = 0; i < camal.length(); i++) {
if (Character.isUpperCase(camal.charAt(i))) {
System.out.print(" " + Character.toLowerCase(camal.charAt(i)));
} else if (i == 0) {
System.out.print(Character.toUpperCase(camal.charAt(i)));
}else{
System.out.print(camal.charAt(i));
}
}
}
}

Categories

Resources