I was getting this error while running the following code. I couldn't find out what was wrong with the code.
As far as I can see, there's some issue with my second character array. But couldn't find out what was wrong. First tried running the last loop before temp_count. Then also tried temp_count±1. Yet, I failed. I have also tried taking different array size. still no luck
import java.util.Scanner;
public class oop2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str = new String();
int temp_count = 0;
//New input of string
str=sc.nextLine();
char[] c = str.toCharArray();
char[] temp = new char[temp_count];
//Converting uppercase to lower case for convenience
for(int i=0; i<str.length(); i++)
{
if (Character.isUpperCase(c[i]))
{
c[i]=(char) (c[i]+32);
}
}
//verifying whether the alphabet exists
for(char x = 'a'; x<='z'; x++)
{
int count=0;
for(int i=0; c[i]!='\0'; i++)
{
if (c[i]==x)
{
count++;
}
}
//if the alphabet is not found, then putting the alphabet in
if (count==0)
{
temp[temp_count]=x;
temp_count++;
}
}
//Verifying whether it's a pangram or not
if (temp_count==0)
{
System.out.println("Pangram");
}
else
{
//if not pangram then this part will execute
System.out.println("Not Pangram");
System.out.printf("Missing Characters: ");
//printing out the missing character
for(int i=0; i<temp_count-1; i++)
{
System.out.print(temp[i]+", ");
}
}
sc.close();
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = new String();
int temp_count = 0;
//New input of string
str = sc.nextLine();
char[] c = str.toCharArray();
char[] temp = new char[0];
//Converting uppercase to lower case for convenience
for (int i = 0; i < str.length(); i++) {
if (Character.isUpperCase(c[i])) {
c[i] = (char)(c[i] + 32);
}
}
//verifying whether the alphabet exists
for (char x = 'a'; x <= 'z'; x++) {
int count = 0;
for (int i = 0; c[i] != '\0'; i++) {
if (c[i] == x) {
count++;
}
}
//if the alphabet is not found, then putting the alphabet in
if (count == 0) {
char [] copy = new char[temp.length+1];
for (int i = 0; i < temp.length; i++) {
copy[i]=temp[i];
}
copy[copy.length-1] = x;
temp=copy;
}
}
//Verifying whether it's a pangram or not
if (temp_count == 0) {
System.out.println("Pangram");
} else {
//if not pangram then this part will execute
System.out.println("Not Pangram");
System.out.printf("Missing Characters: ");
//printing out the missing character
for (int i = 0; i < temp_count - 1; i++) {
System.out.print(temp[i] + ", ");
}
}
sc.close();
}
}
Blockquote
I am trying to find all possible options of combining a string array with two elements. Let's say, the array has two elements {"we","are"}. The output should be:"we" "are" "we are" "are we"
I could manage, with some search, to put together this code:
public class Main {
public static void main(String[] args) {
String[] strings = {"we", "are"};
final int maxbit = 1 << strings.length;
for (int p = 0; p < maxbit; p++) {
String finalString = "";
for (int i = 0; i < strings.length; i++) {
if ((1 << i & p) > 0) {
finalString += strings[i] + " ";
}
}
System.out.println(finalString);
}
}
My problem is, that I am missing one solution, the output is following: "we" "are" "we are".
So I am missing the "are we" option, would I need to use recursion to solve this problem or can this code be modified to show the remaining option?
UPDATE: solution found with the help of answers
public static void main(String[] args) {
String[] test = { "are", "we"};
language(test.length, test, "");
}
private static void language(final int n, final String[] syllables, final String currentWord) { // example of N = 3
if (n == 0) {
System.out.println(currentWord);
} else {
for (int i = 0; i < syllables.length; i++) {
if (currentWord.equals(syllables[i])){
language(n - 1, syllables, "" + syllables[i]);
}else{
language(n - 1, syllables, currentWord + syllables[i]);
}
}
}
}
Another example
import java.util.Arrays;
public class HelloWorld{
public static void main(String[] args) {
String[] strings = {"we", "are"};
String str = Arrays.toString(strings);
System.out.println("Java String array to String = "+str.replace(",","").replace("[","").replace("]",""));
}
}
I looked over it for a while, and found 2 ways to make it based on your code:
this will print out every permutation once, and DOESN'T have to include all the words:
public static void recPerm(String... input) {
recHelper(input, input.length, "");
}
private static void recHelper(String[] input, int length, String currentWord) {
if (currentWord != "")
System.out.println(currentWord);
for (int i = 0; i < input.length; i++) {
if (!currentWord.contains(input[i]))
recHelper(input, length - 1, currentWord + input[i]);
}
}
this will print out every permutation once, and DOES have to include all the words:
public static void maxRecPerm(String... input) {
maxRecHelper(input, input.length, "");
}
private static void maxRecHelper(String[] input, int length, String currentWord) {
if (length == 0)
System.out.println(currentWord);
for (int i = 0; i < input.length; i++) {
if (!currentWord.contains(input[i]))
maxRecHelper(input, length - 1, currentWord + input[i]);
}
}
Is there a way to count capital letters in a string using the method compareTo()? This is my current code so far, I don't know what to add in the if statement.
import java.util.*;
public class countcapitalletters
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.print("enter a string");
String input = scan.nextLine();
int count = 0;
for(int i=0; i<=input.length()-1; i++)
{
if(input.substring(i,i+1)
{
count = count+1;
}
}
System.out.println(count);
}
}
i dont know what to add to my if statement.
You can write a method as follows:
public int countUpperCase(String input) {
int count = 0;
for (int i = 0; i < input.length(); i++) {
String currentChar = input.substring(i, i + 1);
if (currentChar.compareTo("A") >= 0 && currentChar.compareTo("Z") <= 0) {
count = count + 1;
}
}
return count;
}
I have to write a program that finds primes between two user inputted numbers. The only problem I'm having is that the output has one extra comma than it needs. How would I go about fixing this?
import java.util.Scanner;
public class Primes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int start = sc.nextInt();
int end = sc.nextInt();
for (int i =start; i <= end; i++) {
if (isPrime(i)) {
System.out.printf("%d,", i);
}
}
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i =2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
Input: 1 10
Output: 2,3,4,5,7,9,
try to use a StringJoiner is more apropriate in this case:
import java.util.Scanner;
public class Primes {
public static void main(String[] args) {
StringJoiner joiner = new StringJoiner(",");
Scanner sc = new Scanner(System.in);
int start = sc.nextInt();
int end = sc.nextInt();
for (int i =start; i <= end; i++) {
if (isPrime(i)) {
joiner.add(Integer.toString(i));
}
}
System.out.println(joiner.toString());
}
without StringJoiner :
public class Primes {
public static void main(String[] args) {
String separator = "";
Scanner sc = new Scanner(System.in);
int start = sc.nextInt();
int end = sc.nextInt();
for (int i =start; i <= end; i++) {
if (isPrime(i)) {
System.out.printf(separator + "%d", i);
separator = ",";
}
}
}
Here's a bit of a different approach, using streams:
String output = IntStream.rangeClosed(start, end)
.filter(Primes::isPrime)
.mapToObj(String::valueOf)
.collect(Collectors.joining(","));
System.out.println(output);
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
}