How to get rid of space at the end of output? - java

My code checks if a certain number of user inputted string have any repeated characters. For example, if I input the strings "google" "paper" and "water", the code returns "paper" and "water"; because "google" has two Os.
I have the code part down, but when printing, a space appears after the very last string that is output and I can't figure out how to get rid of it.
import java.util.Scanner;
import java.util.*;
class words{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number or words: ");
String[] words = new String[sc.nextInt()];
System.out.print("Enter the strings: ");
boolean truth = false;
for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
for(int i=0;i<words.length;i++){
int j;
for(j=1;j<words[i].length();j++) {
if(words[i].charAt(j) == words[i].charAt(j-1)){
break;
}
}
if(j==words[i].length()){
truth = true;
System.out.print(words[i]+" ");
}
}
if(!truth){
System.out.println("NONE");
}
}
}

Functions Make Logic Readable
Move the logic to check for repeating characters into a function; I would take advantage of String.toCharArray() and the shorter array syntax. Like,
private static boolean repeatedChars(String s) {
if (s == null) {
return false;
}
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length - 1; i++) {
if (chars[i] == chars[i + 1]) {
return true;
}
}
return false;
}
Then, you can use a lambda to filter your words based on them not having repeated characters and collect with Collectors.joining(CharSequence) like
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number or words: ");
String[] words = new String[sc.nextInt()];
System.out.print("Enter the strings: ");
for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
System.out.println(Arrays.stream(words).filter(s -> !repeatedChars(s))
.collect(Collectors.joining(" ")));
And, if you need to display the NONE message you might re-use the Predicate<String> like
Predicate<String> pred = s -> !repeatedChars(s);
if (Arrays.stream(words).anyMatch(pred)) {
System.out.println(Arrays.stream(words).filter(pred).collect(Collectors.joining(" ")));
} else {
System.out.println("NONE");
}

There is an easy workaround for your problem. Instead of printing every word immediately if it does not have any continuous repetition, add it to a String variable with space at the end so that each word is separated by a space. After you run through your loop, you check if your flag is false and print NONE if it is false. If it is true, however, print the result string where you added everything with a .trim() at the end.
for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
String result = ""; /*This is the string that holds all the strings that you need to print.*/
for(int i=0;i<words.length;i++){
int j;
for(j=1;j<words[i].length();j++) {
if(words[i].charAt(j) == words[i].charAt(j-1)){
break;
}
}
if(j==words[i].length()){
truth = true;
result = result + (words[i]+" ");
}
}
if(!truth){
System.out.println("NONE");
}
else{
System.out.println(result.trim()); /*The trim function removes any redundant space in the beginning and the end of the string.*/
}
Of-course doing it this way will waste a lot of Heap Memory but I guess this is for a small learning project. However, do look into StringBuilder on how to use it to avoid creating a lot of memory in the Heap!

Related

Reducing and printing a string Array

I am trying to reduce the string array by using a for a loop. This is an example I tried to do
User string input: Calculus
User input:5
output: CalcuCalcCalCaC
I have turned the string to a char array but the issue presents itself when trying to print them out multiple times. It only prints once and has the right starting output.
input string: Oregon
input number: 4
output: Oreg
I notice my for loop says that it is not looping when I hover over it on the IDE that I downloaded from JetBrains.
I tried different combinations of decrementing and incrementing but could not get that "for statement is not looping". Other than that I have tried different ways to do something in the for loop but I don't think anything needs to be done for now if the for loop is not looping then, right?
So my question is, how to reduce a string or char array and print the decrement value over and over again?
Here is my code so far for it.
public String wordDown(String userString, int userNum)
{
String stringModded = userString.substring(0, userNum);
char[] charArray = stringModded.toCharArray();
char repeat = ' ';
for(int i = 0; i<userNum; ++i)
{
repeat = (char) (repeat +charArray[i]);
charArray[i] = repeat;
for(int j = 1; i > charArray.length; ++j)
{
String modWord = String.valueOf(charArray[i + 1]);
return modWord;
}
}
return null;
}
public static void main(String[] args)
{
int userNumber;
String userString;
RandomArrayFunctionalities ranMethod = new RandomArrayFunctionalities();
Scanner in = new Scanner(System.in);
System.out.println("\nEnter a word:");
userString = in.next();
System.out.println("\nEnter a number within the word scope that you just enter:");
userNumber = in.nextInt();
System.out.println(ranMethod.wordDown(userString, userNumber));
}
You do not need to modify the original array. Use a StringBuilder to concatenate the successive parts of the word. Use the String.substring(int,int) method to pull out those parts. The example that follows uses a decrementing index to generate the successively smaller substrings.
public String wordDown(String word, int userNum) {
StringBuilder sb = new StringBuilder();
for (int length = userNum ; length > 0 ; --length) {
sb.append(word.substring(0, length));
}
return sb.toString();
}
I think you are over complicating things, you don't need a char array at all and you only need a single loop, and a single return statement:
public String wordDown(String userString, int userNum) {
String finalString = "";
for (int i = 0; i < userNum; ++i) {
finalString = finalString + userString.substring(0, userNum - i);
}
return finalString;
}
Simply loop up to the inputted number and substring from 0 to inputtedNumber - loopCounter and append the result to the previously held String value.
Example Run:
Enter a word:
Calculus
Enter a number within the word scope that you just enter:
5
CalcuCalcCalCaC
Sidenote:
Technically you would want to use StringBuilder instead of appending String in a loop, but that is probably out of the scope of this question. Here is that version just for reference:
public String wordDown(String userString, int userNum) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < userNum; ++i) {
sb.append(userString.substring(0, userNum - i));
}
return sb.toString();
}

How to reverse the word after getting a Capital letter at the end of the word in JAVA?

Suppose you have a String and a CAPITAL letter in that indicates ending of a word. For example, if you have wElovEcakE where E, E and K indicates end of the words wE, lovE and cakE respectively. You need to reverse each word (as you know where it ends). Don’t reverse the String as a whole. To illustrate, if we give wElovEcakE as input output should be EwEvolEkac. See wE became Ew, lovE became Evol and so on....
And the way i tried to approach with ..
import java.util.Scanner;
public class Alternative {
public static void main(String[]args) {
Scanner robo=new Scanner (System.in);
System.out.println("Enter a word ");
String word=robo.nextLine();
char[] array=word.toCharArray();
for(int i =0;i<array.length;i++){
int count =0;
for(int j=0;j<=("EMPTY");j++) // here i am trying to operate a loop where it will work up to the Capital letter.
count ++;
}
//Code incomplete
}
}
}
Above i have mentioned "EMPTY" in the condition part ... i want to operate a loop where my loop will work up to the capital letter , then i will count all the letter that i have counted up to capital letter then last step will be like i will make another loop where i will reverse all the letter where condition for the loop will <=count ;Example:lovE (counted 4 letters i will reverse four times back).
Can you guys help me to write the condition at "EMPTY" part if you think that my approach is correct ..
Can you guys help me to solve the problem in any other way ?
test if this works for you:
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
String textInvert = "";
int indexAnt = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
String wordSplit = word.substring(indexAnt, i + 1);
for (int j = wordSplit.length() - 1; j >= 0; j--)
textInvert += wordSplit.charAt(j);
indexAnt = i + 1;
}
}
System.out.println(textInvert);
Here is my solution with Regex pattern
String[] in = "wElovEcakE".replaceAll("([A-z]+?[A-Z])","$1,").replaceAll(",$","").split(",");
String out = "";
for(String current: in){
StringBuilder temp = new StringBuilder();
temp.append(current);
out+=temp.reverse();
}
System.out.println(out);
Result:
EwEvolEkac
Here is a solution that makes use of the StringBuilder class to hold and reverse each found word.
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word:");
String word = robo.nextLine();
robo.close();
String upperCase = word.toUpperCase(); //used to find uppercase letters
StringBuilder builder = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
char nextChar = word.charAt(i);
builder.append(nextChar);
if (nextChar == upperCase.charAt(i)) {
String subWord = builder.reverse().toString();
System.out.print(subWord); //It's not clear what to do with the found words
builder = new StringBuilder();
}
}
System.out.println();
Example
Enter a word:
makEmorEpiE
EkamEromEip
You can try this solution:
String textInvert = "wElovEcakE";
String revertText = textInvert
.chars().mapToObj(c -> (char) c)
.reduce(new LinkedList<>(Arrays.asList(new StringBuilder())), (a, v) -> {
a.getLast().append(v);
if (Character.isUpperCase(v)) {
a.add(new StringBuilder());
}
return a;
}, (a1, a2) -> a1)
.stream()
.map(s -> s.reverse())
.reduce(StringBuilder::append)
.map(StringBuilder::toString)
.get();
System.out.println(revertText);
public class Alternative {
public static void main(String[] args) {
Scanner robo = new Scanner(System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
char[] array = word.toCharArray();
int count = -1;
for (int i = 0; i < array.length; i++) {
if (Character.isUpperCase(array[i])) { //find the upper case letters in the word
for (int j = i; j > count; j--) //loop through the letters until the last count variable value is encountered
System.out.print(array[j]); //print the reversed values
count = i; //assign the last encountered uppercase letter's index value to count variable
}
}
}
}

Accepting string inputs into an array and checking the availability of the string in the array

So I am completely new to java, and I want to create a code to accept string inputs from a user, and store it into an array. After this in the next statement, I will type a value into the terminal, and I want the code to compare my string input to one of the strings in the array and print available on the terminal when the string is available and vice versa. The first part of my code was right (hopefully) but I had a problem in comparing the strings. I feel it doesn't check the strings with my input in the code. Here is my code, Could anyone please help me with this? Thank you so much.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a[] = new String[20] //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() //entering a string to search
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) //I feel the problem is here
System.out.println(search + "course is available");
break;
else
System.out.println(search + "course is not available");
}
}
}
}
I expect the output to be
<string> course is available
when my string matches a string in the array and
<string> course is not available
when my entered string doesn't match a string in the array
But there is no output :(
I have modified your code and commented on line where it need to be explained. check it carefully.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
String a[] = new String[no_of_courses]; // do not assume when you have proper data.
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); // accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); // entering a string to search
boolean flag = false;
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) // I feel the problem is here
{
flag = true;//do not print here. just decide whether course is available or not
break;
}
}
//at the end of for loop check your flag and print accordingly.
if(flag) {
System.out.println(search + "course is available");
}else {
System.out.println(search + "course is not available");
}
}
}
}
class Course {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String a[] = new String[20] ; //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if(no_of_courses <= 0)
System.out.println("Invalid Range");
else
{
System.out.println("Enter course names:");
for(int i=0 ; i < no_of_courses ; i++)
{
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() ; //entering a string to search
boolean found = false;
for(int i = 0 ; i < no_of_courses ; i++)
{
if(a[i].equalsIgnoreCase(search)) //I feel the problem is here
{
**found = true;**
break;
}
}
if(found) {
System.out.println(search+ "course is available");
}else {
System.out.println(search+ "course is not available");
}
}
}
}
This is really a good effort and you almost got it. So just a couple of things
Since you are inputting the number of courses, just use that value to initialise your array (it's just a good practice to get into to try not initialise things before you actually need them).
If you are doing String comparisons and case sensitivity does not matter, rather use .equalsIgnoreCase(String)
To solve your problem, you just needed a boolean variable to indicate whether or not you had found a match. Initially this would be FALSE (no match found) and you would run through your array until a match is found. Once found this would be flagged TRUE and you'd breakout your loop (which you correctly did).
Only once out your loop, you'd print out whether you found a match.
Have a look:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0) {
System.out.println("Invalid Range");
} else {
String a[] = new String[no_of_courses];
System.out.println("Enter course names:");
for (int i = 0; i < a.length; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); //entering a string to search
boolean courseFound = Boolean.FALSE;
for(int i = 0; i < a.length; i++) {
if (a[i].equalsIgnoreCase(search)) {
courseFound = Boolean.TRUE;
break;
}
}
if(courseFound) {
System.out.println(search + "course is available");
} else {
System.out.println(search + " course is not available");
}
}
}
Oh, just for interest (and when you start working with some more advanced constructs), you could always just use stream, which was introduced in Java 8. It'll trim down 12 lines to 5...
if(Arrays.stream(a).anyMatch(i -> i.equalsIgnoreCase(search))) {
System.out.println(search + " course is available");
} else {
System.out.println(search + " course is not available");
}
I noticed a few things - Does your program run to the end? When i copy/pasted into my ide i noticed a few missing semi-colons, and like Yhlas said, your last if/else statement syntax is incorrect.
And this doesn't have anything to do with whether or not your program will give you the right answer, but your last loop will print over and over again because it will check each element in a, and each time it loops and finds a mismatch it will print something out

Finding substring in a given string by changing into char array

i am working on the following program. but its not giving me the correct output for string "nameiskhan" and substring as"name".
i know this might be a duplicate question but i couldn't find the desired answer in those questions.
import java.util.*;
import java.lang.String;
public class CheckingSubstring2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a String: ");
String string1 = input.next();
System.out.println("Please enter a second String: ");
String substring = input.next();
if (isSubstring(string1, substring)) {
System.out.println("The second string is a substring of the first.");
} else {
System.out.println("The second string is NOT a substring of the first.");
}
}
public static boolean isSubstring(String string1, String substring) {
char c[]=string1.toCharArray();
char d[]=substring.toCharArray();
boolean match = true;
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
match = true;
} else {
match = false;
}
}
}
return match;
}
}
As you want to do it without contains, how about this?
What I do here is that going through the original string one pass and check if the substring can be found as consecutive characters in the main String.
public static boolean isSubstring(String string1, String substring) {
char c[]=string1.toCharArray();
char d[]=substring.toCharArray();
for (int i = 0; i < c.length; i++) {
if(c[i] == d[0]){
boolean match = false;
for(int j = 0; j < d.length; j++){
if(c[i+j] != d[j]){
match = false;
break;
} else{
match = true;
}
}
if(match) return true;
}
}
return false;
}
I would suggest becoming familiar with different debugging techniques. A very quick and easy one is a print statement. For example, you can print the values that you are comparing to make sure it looks reasonable. It will also give you an indication of how many times your loop is running. Stepping through the algorithm, the first two characters to be compared are c[0] = 'n' and d[0] = 'n'. That's good. The next two are c[0] = 'n' and d[1] = 'a'. That's not. Also, I assume you intend for the program to stop running if it finds a substring, but it doesn't appear that it would do so. Likewise, you might consider not comparing every element of the substring if a comparison has already been false.

Java program on name Initials

I am writing a program that will give the Initials of the name(String) user gives as input.
I want to use the Space function while writing the name as the basis of the algorithm.
For eg:
<Firstname><space><Lastname>
taking the char once in a for loop and checking if there is a space in between, if there is it will print the charecter that was just before.
Can someone tell me how to implement this?
I'm trying this but getting one error.
Any help is dearly appreaciated..
P.S- i am new to java and finding it a lot intresting. Sorry if there is a big blunder in the coding
public class Initials {
public static void main(String[] args) {
String name = new String();
System.out.println("Enter your name: ");
Scanner input = new Scanner(System.in);
name = input.nextLine();
System.out.println("You entered : " + name);
String temp = new String(name.toUpperCase());
System.out.println(temp);
char c = name.charAt(0);
System.out.println(c);
for (int i = 1; i < name.length(); i++) {
char c = name.charAt(i);
if (c == '') {
System.out.println(name.charAt(i - 1));
}
}
}
}
EDIT:
Ok Finally got it. The algorithm is a lot fuzzy but its working and will try to do it next time with Substring..
for (int i = 1; i < temp.length(); i++) {
char c1 = temp.charAt(i);
if (c1 == ' ') {
System.out.print(temp.charAt(i + 1));
System.out.print(".");
}
}
Thanks a lot guys :)
This works for me
public static void main(String[] args) {
Pattern p = Pattern.compile("((^| )[A-Za-z])");
Matcher m = p.matcher("Some Persons Name");
String initials = "";
while (m.find()) {
initials += m.group().trim();
}
System.out.println(initials.toUpperCase());
}
Output:
run:
SPN
BUILD SUCCESSFUL (total time: 0 seconds)
Simply use a regex:
keep only characters that are following a whitespace
remove all remaining whitespace and finally
make it upper case:
" Foo Bar moo ".replaceAll("([^\\s])[^\\s]+", "$1").replaceAll("\\s", "").toUpperCase();
=> FBM
I will do something like this:
Remember, you only need the inicial characters
public staticvoid main (String[] args){
String name;
System.out.println("Enter your complete name");
Scanner input = new Scanner(System.in);
name = input.nextLine();
System.out.println("Your name is: "+name);
name=" "+name;
//spacebar before string starts to check the initials
String ini;
// we use ini to return the output
for (int i=0; i<name.length(); i++){
// sorry about the 3x&&, dont remember the use of trim, but you
// can check " your name complete" if " y"==true y is what you want
if (name.charAt(i)==" " && i+1 < name.length() && name.charAt(i+1)!=" "){
//if i+1==name.length() you will have an indexboundofexception
//add the initials
ini+=name.charAt(i+1);
}
}
//after getting "ync" => return "YNC"
return ini.toUpperCase();
}
If you care about performance (will run this method many times), the extra charAt(i+1) isn't needed and is relatively costly.
Also, it'll break on texts with double spaces, and will crash on names that end with a space.
This is a safer and faster version:
public String getInitials(String name) {
StringBuilder initials = new StringBuilder();
boolean addNext = true;
if (name != null) {
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (c == ' ' || c == '-' || c == '.') {
addNext = true;
} else if (addNext) {
initials.append(c);
addNext = false;
}
}
}
return initials.toString();
}
public String getInitials() {
String initials="";
String[] parts = getFullName().split(" ");
char initial;
for (int i=0; i<parts.length; i++){
initial=parts[i].charAt(0);
initials+=initial;
}
return(initials.toUpperCase());
}

Categories