Separating output of integers with commas in java - java

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);

Related

I am new to coding. The input of the program is showing always 0 output while using input from console

when i run my code it is showing always 0 as output. this code is about binary search. and i am using buffer reader for input.
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Main mainclass= new Main();
int t =Integer.parseInt(in.readLine());
for(int i = 0;i<t;i++)
{ StringTokenizer tokenizer = new StringTokenizer(in.readLine());
int N = Integer.parseInt(tokenizer.nextToken());
int C = Integer.parseInt(tokenizer.nextToken());
int[] arr= new int[N];
for(int x=0;x<N;x++)
{ arr[i] =Integer.parseInt(in.readLine());}
int res= mainclass.bs(N,C,arr);
System.out.println(res);
}
}
it is bs() method inside Main class. I am actually solving problem on aggresive cows of SPOJ.
here is the link: https://www.spoj.com/problems/AGGRCOW/
public int bs(int N,int C,int[] arr)
{ Arrays.sort(arr);
int left = 0;int right = arr[N-1]-arr[0];int mid = arr[N-1]-arr[0];
int check = 0; int max= -1;
while(left<right){
int temp= checker(mid,arr);
if(temp>=C)
{ if(max<mid)
max=mid;
left = mid+1;
mid = (left+right)/2; }
else
{
right= mid;
mid=(left+right)/2;
}
}
return max;
}
public int checker(int mid,int[] arr)
{ int N = arr.length;int f=0;int cows=1;
for(int i=0;i<N-1;i++)
{
if((arr[i+1]-arr[f])>=mid)
{
f=i+1;
cows++;
}
}
return cows;
}
}
Located your problem, it's with filling the initial array.
I changed your code here myself a bit, to use Scanner and split (also removed some irrelevant code), but the issue is the same:
import java.util.Arrays;
import java.util.Scanner;
class Main
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int t =scan.nextInt(); scan.nextLine();
for(int i = 0;i<t;i++)
{
String[] input = scan.nextLine().split(" ");
int N = Integer.parseInt(input[0]);
int C = Integer.parseInt(input[1]);
int[] arr= new int[N];
for(int x=0;x<N;x++){
arr[i] = scan.nextInt();
scan.nextLine();
}
int res= bs(N,C,arr);
System.out.println("RES = " + res);
}
}
public static int bs(int N,int C,int[] arr) {
Arrays.sort(arr);
int left = 0;int right = arr[N-1]-arr[0];int mid = arr[N-1]-arr[0];
int max= -1;
while(left<right){
int temp= checker(mid,arr);
if(temp>=C){
if(max<mid)
max=mid;
left = mid+1;
mid = (left+right)/2; }
else {
right= mid;
mid=(left+right)/2;
}
}
return max;
}
public static int checker(int mid,int[] arr){
int f=0;int cows=1;
for(int i=0;i<arr.length-1;i++) {
if((arr[i+1]-arr[f])>=mid) {
f=i+1;
cows++;
}
}
return cows;
}
}
Your problem lies here:
for(int x=0;x<N;x++){
arr[i] = scan.nextInt();
scan.nextLine();
}
The value of i never changes, so you put all those ints on the same index of your array. Change that to this:
for(int x=0;x<N;x++){
arr[x] = scan.nextInt();
scan.nextLine();
}

How to count capital letters with compareTo() method?

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;
}

output the smallest integer in an array, and the index of it

I've been coding this program but I've got a little bit stuck and would like some advice. This is what I've got so far:
import java.util.Scanner;
public class SmallestInArray
{
public static void main(String[] args)
{
int[] array = new int[10];
input(array);
output(array);
}
public static void input(int[] array)
{
Scanner kybd = new Scanner(System.in);
System.out.println("Enter 10 integers: ");
for (int i = 0; i < array.length; i++) {
array[i] = kybd.nextInt();
}
}
public static int findSmallest(int[] array, int first)
{
int smallestPos = first;
for (int i = first + 1; i < array.length; i++) {
if (array[i] < array[smallestPos]) {
smallestPos = i;
}
}
return smallestPos;
}
public static void output(int[] array)
{
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
Everything is fine other than the findSmallest method, as I'd like to output the smallest value and the index of it, but I'm not quite sure what to pass as the parameters in the main method?
Please find the refactored code which gets you both the value and index of smallest element in the array.
import java.util.Scanner;
public class SmallestInArray
{
int index_of_smallest_element;
public static void main(String[] args)
{
int[] array = new int[10];
input(array);
SmallestInArray smallestInArray = new SmallestInArray();
System.out.printf("Smallest Value:%d corresponding Index:%d\n",smallestInArray.findSmallest(array), smallestInArray.index_of_smallest_element);
output(array);
}
public static void input(int[] array)
{
System.out.println("Enter 10 integers: ");
try (Scanner kybd = new Scanner(System.in))
{
for (int i = 0; i < array.length; i++)
{
array[i] = kybd.nextInt();
}
}
}
public int findSmallest(int[] array)
{
int smallestValue = array[0];
index_of_smallest_element = 0;
for (int i = 1; i < array.length; i++) {
if (smallestValue > array[i]) // it doesn't accounts for duplicate values
{
smallestValue = array[i];
index_of_smallest_element = i;
}
}
return smallestValue;
}
public static void output(int[] array)
{
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}}
Hope this helps
Try this
public static void main(String[] args)
{
int[] array = new int[10];
input(array);
output(array);
int smallestPos = findSmallest(array, 0 /* P.S. this parameter seem to be useless */);
int smallestVal = array[smallestPos];
// output the two
}

Optimizing Palindrome substring identification

I'm currently trying to find a way to get my program to run more efficiently. If anyone has any ideas on how to optimize my program, i would appreciate it a lot.
Also, the output has to display in alphabetic order without any duplicates.
package Palindrome;
import java.io.*;
import java.util.*;
public class Palindrome {
public static void main(String[] args)throws IOException{
Scanner scan;
scan = new Scanner(System.in);
while (scan.hasNext()) {
subPal(scan.next());
}
if (scan != null) {
scan.close();
}}
private static void subPal(String str) {
String s1 = "";
int N = str.length();
ArrayList<String> palindromeArray = new ArrayList<String>();
for (int i = 2; i <= N; i++) {
for (int j = 0; j <= N; j++) {
int k = i + j - 1;
if (k >= N)
continue;
s1 = str.substring(j, i + j);
if (s1.equals(new StringBuilder(s1).reverse().toString())&& !palindromeArray.contains(s1)) {
palindromeArray.add(s1);
}
}
}
Collections.sort(palindromeArray);
for (String s : palindromeArray)
System.out.println(s );
}
}

How to remove duplicate character from a string in java?

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
}

Categories