I'm writing a hangman program in Java, but the problem I have is, in the game i want to show the remaining letter from the letters guessed, for that I have created a String alpha, which contains the alphabet, and i put that to an ArrayList so i can choose the letters that's been guesses by the player. but i'm stuck in this bit the out put i want to get is as below : and i've attached the code i wrote for the function as well.
You have 6 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: a
Good guess: a_ _
You have 6 guesses left.
Available letters: bcdefghijklmnopqrstuvwxyz
code :
public String getRemainingLetters(String[] lettersGuessed) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
String [] alpha2 = alpha.split("");
ArrayList<String> list = new ArrayList<>(Arrays.asList(alpha2));
return null;
// TODO: Fill in your code here
}
List#removeAll & String#join
Use them as shown below to solve the problem:
static String getRemainingLetters(String[] lettersGuessed) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
String[] alpha2 = alpha.split("");
List<String> list = new ArrayList<>(Arrays.asList(alpha2));
List<String> toBeRemoved = new ArrayList<>(Arrays.asList(lettersGuessed));
list.removeAll(toBeRemoved);
return String.join("", list);
}
Demo:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(getRemainingLetters(new String[] { "a", "b", "c" }));
System.out.println(getRemainingLetters(new String[] { "d" }));
System.out.println(getRemainingLetters(new String[] { "x", "y", "z" }));
System.out.println(getRemainingLetters(new String[] { "x" }));
}
static String getRemainingLetters(String[] lettersGuessed) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
String[] alpha2 = alpha.split("");
List<String> list = new ArrayList<>(Arrays.asList(alpha2));
List<String> toBeRemoved = new ArrayList<>(Arrays.asList(lettersGuessed));
list.removeAll(toBeRemoved);
return String.join("", list);
}
}
Output:
defghijklmnopqrstuvwxyz
abcefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvw
abcdefghijklmnopqrstuvwyz
An interactive demo:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
StringBuilder consumed = new StringBuilder();
final int NO_OF_GUESSES = 6;
Scanner kb = new Scanner(System.in);
String guess;
for (int i = 1; i <= NO_OF_GUESSES; i++) {
System.out.println("Available letters: " + getRemainingLetters(consumed.toString().split("")));
System.out.print("Guess a letter: ");
guess = kb.nextLine();
consumed.append(guess.length() >= 1 ? guess.charAt(0) : "");
System.out.printf("You have %d chances left%n", NO_OF_GUESSES - i);
}
}
static String getRemainingLetters(String[] lettersGuessed) {
String alpha = "abcdefghijklmnopqrstuvwxyz";
String[] alpha2 = alpha.split("");
List<String> list = new ArrayList<>(Arrays.asList(alpha2));
List<String> toBeRemoved = new ArrayList<>(Arrays.asList(lettersGuessed));
list.removeAll(toBeRemoved);
return String.join("", list);
}
}
A sample run:
Available letters: abcdefghijklmnopqrstuvwxyz
Guess a letter: a
You have 5 chances left
Available letters: bcdefghijklmnopqrstuvwxyz
Guess a letter: x
You have 4 chances left
Available letters: bcdefghijklmnopqrstuvwyz
Guess a letter:
Here you can pretty it up and put error checking im out of time:)
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
public static List < String > getRemainingLetters (ArrayList < String >
lettersGuessed)
{
String alpha = "abcdefghijklmnopqrstuvwxyz";
String[] alpha1 = alpha.split ("");
ArrayList < String > alpha2 = new ArrayList <> (Arrays.asList (alpha1));
for (int i = 0; i < lettersGuessed.size (); i++)
{
for (int j = 0; j < alpha2.size (); j++)
{
if (alpha2.get (j).equals (lettersGuessed.get (i)))
{
alpha2.remove (j);
break;
}
}
}
return alpha2;
}
public static void main (String[]args)
{
int numGuesses = 10;
String w = "this";
String[]word = w.split ("");
ArrayList < String > wList = new ArrayList <> (Arrays.asList (word));
ArrayList < String > wAnswer = new ArrayList < String > (wList.size ());
for (int i = 0; i < wList.size (); i++)
{
wAnswer.add ("_ ");
}
int left = wList.size();
Scanner scanner = new Scanner (System.in);
boolean notDone = true;
ArrayList < String > lettersGuessed = new ArrayList < String > ();
while (notDone)
{
System.out.println ();
String sOut = "";
List < String > lettersLeft = getRemainingLetters (lettersGuessed);
for (String s:lettersLeft)
{
sOut += s + " ";
}
System.out.println ("Letters Left: " + sOut );
sOut = "";
for (int i = 0; i < wList.size (); i++)
{
sOut += wAnswer.get (i);
}
System.out.println (sOut + " Guesses left:" + numGuesses);
System.out.print ("Enter a letter(* exit): ");
String sIn = scanner.next ();
numGuesses--;
if (sIn.equals ("*")){
break;
}
lettersGuessed.add (sIn);
for (int i = 0; i < wList.size (); i++)
{
if (sIn.equals (wList.get (i)))
{
wAnswer.set (i, sIn);
left--;
}
}
if(left == 0){
System.out.println ("Congradulations you guessed it!");
break;
}
if(numGuesses == 0){
System.out.println ("You failed...:(");
break;
}
}
}
}
Related
I am trying to print user inputs in another class in Java. I have made a chessboard which asks the user to input strings on the board, and then, when these strings are printed on screen, I would like the output to be "You have placed piece [name] at coordinate [coordinate]". I am trying to do this in another class rather in the main method, but what I have tried so far doesn't seem to work. Here's my code.
import java.util.Arrays;
import java.util.Scanner;
public class ChessBoard
{
public static void main(String[] args)
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++)
{
for(int col = 0; col < grid[i].length; col++);
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while ( ! validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-h][1-8]");
};
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
System.out.println(Arrays.deepToString(grid));
}
}
So what I'd like to do is have a new class that uses that last print line to instead print the desired output that I mentioned earlier. Any help would be appreciated, thanks!
EDIT:
import java.util.Arrays;
import java.util.Scanner;
public class ChessBoard1
{
public static void main(String[] args)
{
userInputs input = new userInputs();
showInput show = new showInput();
String grid[][] = input.takeInput();
show.show(grid);
}
}
public class userInputs
{
public String[][] takeInput()
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++) {
for (int col = 0; col < grid[i].length; col++) ;
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while (!validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-h][1-8]");
}
;
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
return grid;
}
}
public class showInput {
public void show(String [][] inputs)
{
for(int i=0 ; i<inputs.length ; i++){
for(int j=0 ; j < inputs[0].length ; j++)
{
System.out.println(Arrays.deepToString(grid));
}
}
}
}
I have 2 separate files userInputs and showInput but they it says that they should still be declared in a separate file?
It's wrong to write main Function in every class, the program uses the main function to start from it, So you should write it only in the main project class and call inside it the other classes.
Your code should be:
package com.company;
public class ChessBoard
{
public static void main(String[] args)
{
userInputs input = new userInputs();
showInput show = new showInput();
String grid[][] = input.takeInput();
show.show(grid);
}
}
and other classes in separate files like:
package com.company;
import java.util.Scanner;
public class userInputs
{
public String[][] takeInput()
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++) {
for (int col = 0; col < grid[i].length; col++) ;
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while (!validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-h][1-8]");
}
;
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
return grid;
}
}
and another class to output:
package com.company;
public class showInput {
public void show(String [][] inputs)
{
for(int i=0 ; i<inputs.length ; i++){
for(int j=0 ; j < inputs[0].length ; j++)
{
//Print Your Data
}
}
}
}
Like #Atef Magdy said, You should have one class which holds all the data and functions
and a main class which executes the functions.
and the explanation for this error ( it states that using public int is an "illegal start" to the expression, and that it needs a ";" after it?) I have seen that you made the 2d Array of Type String?
String[] [] grid = new String [8][8];
and then returning it as a 1D Array of Type int?
public int[] getGrid(){
return grid.clone();
}
I should say that this is the source of this error. You should change the 'int[]' to 'string[][]'
if there is any error please reply to this answer!
I have to capitalize the first letter in every word passed into the string. My output is doing that capitalization, but it's not maintaining the format of the original output. For example, string input is "hello world", my output is "HelloWorld", and my desired output should be "Hello World."
I've tried to add spaces where I can throughout the code but nothing works. I think the problem is that when I use toCharArray, it gives me an output with no spaces? So my concatenation result is adding everything in one swoop, versus each word separately?
Or I thought that my code was using string concatenation with my result, and it's not being separated because I have both words going into the same variable.
import java.util.*;
import java.io.*;
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
String result = "";
for(int i = 0; i < word.length; i++) {
char[] charWord = word[i].toCharArray();
for(int j = 0; j < charWord.length; j++ ) {
String cap = word[i].charAt(0) + "";
cap = cap.toUpperCase();
//System.out.print(" ");
result += (j == 0 ? cap : word[i].charAt(j));
}
}
return result;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}
No errors. Just not getting desired output.
When you did String[] word = str.split(" ");, the space between each word is taken out and you are now left with only the words in an array. You should use String.join(" ", word) on the resultant words array to reverse the effects so you get the spaces back.
Instead of going through each word char by char, try this:
for(int i = 0; i < word.length; i++) {
word[i] = word[i].substring(0, 1).toUpperCase() + word[i].substring(1);
}
result = String.join(" ", word);
Try this:
import java.util.*;
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
String result = "";
for(int i = 0; i < word.length; i++) {
result += capitalize(word[i]) + (i != word.length - 1 ? " " : "");
}
return result;
}
private static String capitalize(String s){
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}
You can use the below code.
class Main {
public static String LetterCapitalize(String str) {
// code goes here
String[] word = str.split(" ");
StringBuilder result = new StringBuilder();
for (int i = 0; i < word.length; i++) {
char[] charWord = word[i].toCharArray();
for (int j = 0; j < charWord.length; j++) {
String cap = word[i].charAt(0) + "";
cap = cap.toUpperCase();
//System.out.print(" ");
result.append(j == 0 ? cap : word[i].charAt(j));
}
result.append(" ");
}
return result.toString();
}
public static void main(String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterCapitalize(s.nextLine()));
}
}
> Here I'm able to print the number repetitions of character but i'm not
able to get how to compare and remove.Here i had taken two maps for two strings and keys as charecters and value as repetitons
public class NoOfDeletionsTomakeStringAnagram {
#SuppressWarnings("resource")
public static void main(String[] args) {
System.out.println("string");
Scanner sc = new Scanner(System.in);
System.out.println("enter string 1");
String s1 = sc.next();
System.out.println("enter string 2");
String s2 = sc.next();
Map<Character, Integer> m1s1 = new HashMap<>();
Map<Character, Integer> m2s2 = new HashMap<>();
for (int i = 0; i < s1.length(); i++) {
if (m1s1.containsKey(s1.charAt(i))) {
m1s1.put((Character) s1.charAt(i), m1s1.get((Character)
s1.charAt(i)) + 1);
} else {
m1s1.put((Character) s1.charAt(i), 1);
}
}
for (int i = 0; i < s2.length(); i++) {
if (m2s2.containsKey(s2.charAt(i))) {
m2s2.put((Character) s2.charAt(i), m2s2.get((Character)
s2.charAt(i)) + 1);
} else {
m2s2.put((Character) s2.charAt(i), 1);
}
}
System.out.println("m1s1....." + m1s1);
System.out.println("m221...." + m2s2);
}
}
Samlie input:
s1=abc
s2=cde
Here we have to make anagram by deleting charecters from both the strings
output:
s1=c
s2=c
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("string");
Scanner sc = new Scanner(System.in);
System.out.println("enter string 1");
String s1 = sc.next();
System.out.println("enter string 2");
String s2 = sc.next();
Map<Character, Integer> m1s1 = new HashMap<>();
Map<Character, Integer> m2s2 = new HashMap<>();
for (int i = 0; i < s1.length(); i++) {
if (m1s1.containsKey(s1.charAt(i))) {
m1s1.put((Character) s1.charAt(i), m1s1.get((Character)
s1.charAt(i)) + 1);
} else {
m1s1.put((Character) s1.charAt(i), 1);
}
}
for (int i = 0; i < s2.length(); i++) {
if (m2s2.containsKey(s2.charAt(i))) {
m2s2.put((Character) s2.charAt(i), m2s2.get((Character)
s2.charAt(i)) + 1);
} else {
m2s2.put((Character) s2.charAt(i), 1);
}
}
System.out.println("m1s1....." + m1s1);
System.out.println("m221...." + m2s2);
// ADDED MY CODE FROM HERE
// TAKEN STRING 1 AND MAP OF STRING 2, CHECK CHARACTER BY CHARACTER OF STRING 1 IN MAP //OF STRING 2, IF THE CHARACTER EXISTS PRINT IT & DECREASE ITS VALUE IN MAP BY 1 , IF //AFTER DECREASING THE VALUE BECOMES 0, REMOVE IT FROM MAP, IF THE CHARACTER OF //STRING1 DOES NOT EXIST IN MAP2 DON'T DO ANYTHING, FOLLOW ABOVE RULES FOR EVERY //CHARACTER OF STRING 1
// NOW TAKE STRING2 AND MAP OF STRING1 AND FOLLOW THE EXACT PROCEDURE ABOVE
int i,x;
char c;
for(i=0;i<s1.length();i++)
{
c=s1.charAt(i);
if(m2s2.containsKey(c))
{
System.out.print(c);
x=m2s2.get((Character)c);
x=x-1;
if(x==0)
m2s2.remove(new Character(c));
else
m2s2.put((Character) c,x);
}
}
System.out.println();
for(i=0;i<s2.length();i++)
{
c=s2.charAt(i);
if(m1s1.containsKey(c))
{
System.out.print(c);
x=m1s1.get((Character)c);
x=x-1;
if(x==0)
m1s1.remove(new Character(c));
else
m1s1.put((Character) c,x);
}
}
}
}
In my program, the user enters a string, and it first finds the largest mode of characters in the string. Next, my program is supposed to remove all duplicates of a character in a string, (user input: aabc, program prints: abc) which I'm not entirely certain on how to do. I can get it to remove duplicates from some strings, but not all. For example, when the user puts "aabc" it will print "abc", but if the user puts "aabbhh", it will print "abbhh." Also, before I added the removeDup method to my program, it would only print the maxMode once, but after I added the removeDup method, it began to print the maxMode twice. How do I keep it from printing it twice?
Note: I cannot convert the strings to an array.
import java.util.Scanner;
public class JavaApplication3 {
static class MyStrings {
String s;
void setMyStrings(String str) {
s = str;
}
int getMode() {
int i;
int j;
int count = 0;
int maxMode = 0, maxCount = 1;
for (i = 0; i< s.length(); i++) {
maxCount = count;
count = 0;
for (j = s.length()-1; j >= 0; j--) {
if (s.charAt(j) == s.charAt(i))
count++;
if (count > maxCount){
maxCount = count;
maxMode = i;
}
}
}
System.out.println(s.charAt(maxMode)+" = largest mode");
return maxMode;
}
String removeDup() {
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = 0; j < rdup.length(); j++) {
if (s.charAt(i) == s.charAt(j)){
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
System.out.print(rdup);
System.out.println();
return rdup;
}
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
MyStrings setS = new MyStrings();
String s;
System.out.print("Enter string:");
s = in.nextLine();
setS.setMyStrings(s);
setS.getMode();
setS.removeDup();
}
}
Try this method...should work fine!
String removeDup()
{
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = i+1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
// System.out.print(rdup);
System.out.println();
return rdup;
}
Welcome to StackOverflow!
You're calling getMode() both outside and inside of removeDup(), which is why it's printing it twice.
In order to remove all duplicates, you'll have to call removeDup() over and over until all the duplicates are gone from your string. Right now you're only calling it once.
How might you do that? Think about how you're detecting duplicates, and use that as the end condition for a while loop or similar.
Happy coding!
Shouldn't this be an easier way? Also, i'm still learning.
import java.util.*;
public class First {
public static void main(String arg[])
{
Scanner sc= new Scanner(System.in);
StringBuilder s=new StringBuilder(sc.nextLine());
//String s=new String();
for(int i=0;i<s.length();i++){
String a=s.substring(i, i+1);
while(s.indexOf(a)!=s.lastIndexOf(a)){s.deleteCharAt(s.lastIndexOf(a));}
}
System.out.println(s.toString());
}
}
You can do this:
public static void main(String[] args) {
String str = new String("PINEAPPLE");
Set <Character> letters = new <Character>HashSet();
for (int i = 0; i < str.length(); i++) {
letters.add(str.charAt(i));
}
System.out.println(letters);
}
I think an optimized version which supports ASCII codes can be like this:
public static void main(String[] args) {
System.out.println(removeDups("*PqQpa abbBBaaAAzzK zUyz112235KKIIppP!!QpP^^*Www5W38".toCharArray()));
}
public static String removeDups(char []input){
long ocr1=0l,ocr2=0l,ocr3=0;
int index=0;
for(int i=0;i<input.length;i++){
int val=input[i]-(char)0;
long ocr=val<126?val<63?ocr1:ocr2:ocr3;
if((ocr& (1l<<val))==0){//not duplicate
input[index]=input[i];
index++;
}
if(val<63)
ocr1|=(1l<<val);
else if(val<126)
ocr2|=(1l<<val);
else
ocr3|=(1l<<val);
}
return new String(input,0,index);
}
please keep in mind that each of orc(s) represent a mapping of a range of ASCII characters and each java long variable can grow as big as (2^63) and since we have 128 characters in ASCII so we need three ocr(s) which basically maps the occurrences of the character to a long number.
ocr1: (char)0 to (char)62
ocr2: (char)63 to (char)125
ocr3: (char)126 to (char)128
Now if a duplicate was found the
(ocr& (1l<<val))
will be greater than zero and we skip that char and finally we can create a new string with the size of index which shows last non duplicate items index.
You can define more orc(s) and support other character-sets if you want.
Can use HashSet as well as normal for loops:
public class RemoveDupliBuffer
{
public static String checkDuplicateNoHash(String myStr)
{
if(myStr == null)
return null;
if(myStr.length() <= 1)
return myStr;
char[] myStrChar = myStr.toCharArray();
HashSet myHash = new HashSet(myStrChar.length);
myStr = "";
for(int i=0; i < myStrChar.length ; i++)
{
if(! myHash.add(myStrChar[i]))
{
}else{
myStr += myStrChar[i];
}
}
return myStr;
}
public static String checkDuplicateNo(String myStr)
{
// null check
if (myStr == null)
return null;
if (myStr.length() <= 1)
return myStr;
char[] myChar = myStr.toCharArray();
myStr = "";
int tail = 0;
int j = 0;
for (int i = 0; i < myChar.length; i++)
{
for (j = 0; j < tail; j++)
{
if (myChar[i] == myChar[j])
{
break;
}
}
if (j == tail)
{
myStr += myChar[i];
tail++;
}
}
return myStr;
}
public static void main(String[] args) {
String myStr = "This is your String";
myStr = checkDuplicateNo(myStr);
System.out.println(myStr);
}
Try this simple answer- works well for simple character string accepted as user input:
import java.util.Scanner;
public class string_duplicate_char {
String final_string = "";
public void inputString() {
//accept string input from user
Scanner user_input = new Scanner(System.in);
System.out.println("Enter a String to remove duplicate Characters : \t");
String input = user_input.next();
user_input.close();
//convert string to char array
char[] StringArray = input.toCharArray();
int StringArray_length = StringArray.length;
if (StringArray_length < 2) {
System.out.println("\nThe string with no duplicates is: "
+ StringArray[1] + "\n");
} else {
//iterate over all elements in the array
for (int i = 0; i < StringArray_length; i++) {
for (int j = i + 1; j < StringArray_length; j++) {
if (StringArray[i] == StringArray[j]) {
int temp = j;//set duplicate element index
//delete the duplicate element by copying the adjacent elements by one place
for (int k = temp; k < StringArray_length - 1; k++) {
StringArray[k] = StringArray[k + 1];
}
j++;
StringArray_length--;//reduce char array length
}
}
}
}
System.out.println("\nThe string with no duplicates is: \t");
//print the resultant string with no duplicates
for (int x = 0; x < StringArray_length; x++) {
String temp= new StringBuilder().append(StringArray[x]).toString();
final_string=final_string+temp;
}
System.out.println(final_string);
}
public static void main(String args[]) {
string_duplicate_char object = new string_duplicate_char();
object.inputString();
}
}
Another easy solution to clip the duplicate elements in a string using HashSet and ArrayList :
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
public class sample_work {
public static void main(String args[]) {
String input = "";
System.out.println("Enter string to remove duplicates: \t");
Scanner in = new Scanner(System.in);
input = in.next();
in.close();
ArrayList<Character> String_array = new ArrayList<Character>();
for (char element : input.toCharArray()) {
String_array.add(element);
}
HashSet<Character> charset = new HashSet<Character>();
int array_len = String_array.size();
System.out.println("\nLength of array = " + array_len);
if (String_array != null && array_len > 0) {
Iterator<Character> itr = String_array.iterator();
while (itr.hasNext()) {
Character c = (Character) itr.next();
if (charset.add(c)) {
} else {
itr.remove();
array_len--;
}
}
}
System.out.println("\nThe new string with no duplicates: \t");
for (int i = 0; i < array_len; i++) {
System.out.println(String_array.get(i).toString());
}
}
}
your can use this simple code and understand how to remove duplicates values from string.I think this is the simplest way to understand this problem.
class RemoveDup
{
static int l;
public String dup(String str)
{
l=str.length();
System.out.println("length"+l);
char[] c=str.toCharArray();
for(int i=0;i<l;i++)
{
for(int j=0;j<l;j++)
{
if(i!=j)
{
if(c[i]==c[j])
{
l--;
for(int k=j;k<l;k++)
{
c[k]=c[k+1];
}
j--;
}
}
}
}
System.out.println("after concatination lenght:"+l);
StringBuilder sd=new StringBuilder();
for(int i=0;i<l;i++)
{
sd.append(c[i]);
}
str=sd.toString();
return str;
}
public static void main(String[] ar)
{
RemoveDup obj=new RemoveDup();
Scanner sc=new Scanner(System.in);
String st,t;
System.out.println("enter name:");
st=sc.nextLine();
sc.close();
t=obj.dup(st);
System.out.println(t);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication26;
import java.util.*;
/**
*
* #author THENNARASU
*/
public class JavaApplication26 {
public static void main(String[] args) {
int i,j,k=0,count=0,m;
char a[]=new char[10];
char b[]=new char[10];
Scanner ob=new Scanner(System.in);
String str;
str=ob.next();
a=str.toCharArray();
int c=str.length();
for(j=0;j<c;j++)
{
for(i=0;i<j;i++)
{
if(a[i]==a[j])
{
count=1;
}
}
if(count==0)
{
b[k++]=a[i];
}
count=0;
}
for(m=0;b[m]!='\0';m++)
{
System.out.println(b[m]);
}
}
}
i wrote this program. Am using 2 char arrays instead. You can define the number of duplicate chars you want to eliminate from the original string and also shows the number of occurances of each character in the string.
public String removeMultipleOcuranceOfChar(String string, int numberOfChars){
char[] word1 = string.toCharArray();
char[] word2 = string.toCharArray();
int count=0;
StringBuilder builderNoDups = new StringBuilder();
StringBuilder builderDups = new StringBuilder();
for(char x: word1){
for(char y : word2){
if (x==y){
count++;
}//end if
}//end inner loop
System.out.println(x + " occurance: " + count );
if (count ==numberOfChars){
builderNoDups.append(x);
}else{
builderDups.append(x);
}//end if else
count = 0;
}//end outer loop
return String.format("Number of identical chars to be in or out of input string: "
+ "%d\nOriginal word: %s\nWith only %d identical chars: %s\n"
+ "without %d identical chars: %s",
numberOfChars,string,numberOfChars, builderNoDups.toString(),numberOfChars,builderDups.toString());
}
Try this simple solution for REMOVING DUPLICATE CHARACTERS/LETTERS FROM GIVEN STRING
import java.util.Scanner;
public class RemoveDuplicateLetters {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("enter a String:");
String s=scn.nextLine();
String ans="";
while(s.length()>0)
{
char ch = s.charAt(0);
ans+= ch;
s = s.replace(ch+"",""); //Replacing all occurrence of the current character by a spaces
}
System.out.println("after removing all duplicate letters:"+ans);
}
}
In Java 8 we can do that using
private void removeduplicatecharactersfromstring() {
String myString = "aabcd eeffff ghjkjkl";
StringBuilder builder = new StringBuilder();
Arrays.asList(myString.split(" "))
.forEach(s -> {
builder.append(Stream.of(s.split(""))
.distinct().collect(Collectors.joining()).concat(" "));
});
System.out.println(builder); // abcd ef ghjkl
}
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.
}