Storing numbers that are odd and even - java

I am able to get the numbers from a String but it seems it only reads one digit of number example is if I input Test24 XXX23, it only reads 4 and 3 instead of 24 and 23, also I need help in storing all numbers that are odd/even in an array and display them later like: Odd (3 5 7), Even(2 4 6)
public class acc2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter something with numbers:");
String s = input.nextLine();
System.out.print("\n");
String digits = s.replaceAll("[^0-9.]", "");
int x = Integer.parseInt(digits);
int len = s.length();
for (int i = 0; i < len; i++) {
if (Character.isDigit(s.charAt(i))) {
System.out.print(s.charAt(i));
i++;
while (i < len && Character.isDigit(s.charAt(i))) {
System.out.print(s.charAt(i));
if (s.charAt(i) % 2 == 0) {
System.out.println("is even");
} else {
System.out.println("is odd");
}
i++;
}
System.out.print(" ");
}
}
if (x <= 100) {
if (x >= 50) {
System.out.print(x + " passed");
} else {
System.out.print(x + " failed");
}
} else {
System.out.print("Value is to high ");
}
}
}

I'm not entirely sure what the goal is, but I have a few suggestions. First, if you want to read 24 and 23 as two separate numbers instead of one (e.g., 2423 as done currently), then adjust digits to read String[] digits = s.replaceAll("[^0-9.\\s+]", "").split("\\s+"); - this will create a string array of each number group defined as being separated by one or more spaces (i.e., 24 and 23 instead of 2423). Second, you can create two Integer lists, one for even and one for odd (for general consumption, it's impossible to know the length of each array (you could always use a huge number, but that's inefficient), which is why I suggest a list). You have the right idea in terms of a %2 test for even/odd, just change the current iterators to iterate over each digit in each digit grouping:
for(int i=0; i<digits.length; i++){
for(int j=0; j<digits[i].length(); j++){
// do stuff
}
}

String inp="Test24 XXX23";
Pattern p=Pattern.compile("[0-9]+");
Matcher m=p.matcher(inp);
System.out.println(m.matches());
int i=0,j=0,k=0;
int[] even=new int[10];
int[] odd=new int[10];
while (m.find()) {
System.out.println(inp.substring(m.start(), m.end()));
i=Integer.parseInt(inp.substring(m.start(), m.end()));
if(i%2==0){
even[j]=i;j++;
}
else{
odd[k]=i;k++;
}
}
System.out.println(even[0]+" "+odd[0]);
>> Extend this program to print all odd and even numbers with for loop

the following code extracts digits and also generate the array of odd and even numbers.This is what are you looking for.
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;
public class StackSolution {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter something with numbers:");
String s = input.nextLine();
String digits = s.replaceAll("[^0-9.]", "");
int len = digits.length();
Set<Integer>odd,even;
odd=new LinkedHashSet<Integer>();
even=new LinkedHashSet<Integer>();
for (int i = 0; i < len; i++) {
int no=Integer.parseInt(""+digits.charAt(i) );
Integer dig=new Integer(no);
if ( no%2==0) {
even.add(dig);
} else {
odd.add(dig);
}
}
int[] oddArray,evenArray;
oddArray=new int[odd.size()];
evenArray=new int[even.size()];
oddArray=toIntArray(odd);
evenArray=toIntArray(even);
System.out.print("Odd: (");
for(int no:oddArray){
System.out.print(" "+no);
}
System.out.println(" )");
System.out.print("Even: (");
for(int no:evenArray){
System.out.print(" "+no);
}
System.out.print(" )");
}
static int[] toIntArray(Set<Integer> list){
int[] ret = new int[list.size()];
Iterator<Integer> itr=list.iterator();
int i=0;
while (itr.hasNext()) {
Integer integer = (Integer) itr.next();
ret[i]=integer.intValue();
i++;
}
return ret;
}
}

Related

Prevent trailing character when printing values in a loop [duplicate]

This question already has answers here:
Printing with delimiter only between values
(3 answers)
Closed 2 years ago.
I was tasked to do a looping problem for Java, but I'm currently having a problem on how to display a factorial of a number. For example, 1x2x3x4x5 = 120.
I'm almost there, but I can't seem to figure out how to, or is there any possible way to display the factorial of a number because there is always an additional "x" at the end of the 5.
Here is my code:
import java.util.*;
public class trylangpo2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int fctr;
System.out.println ("number");
fctr = input.nextInt();
for (int i = 1; i <=fctr; i++){
System.out.print(i);
int j;
for (j =1; j <=1 ; j++){
System.out.print("*");
}
}
}
}
Example output:
1x2x3x4x5x
Your loop for (j =1; j <=1 ; j++) can be removed. It only loops once so, just write System.out.print("*"). No loop required
Then if you think about it, you want to print the number and the * all the time, except when it is the last number (fctr)
So write it that way:
Scanner input = new Scanner (System.in);
int fctr;
System.out.println ("number");
fctr = input.nextInt();
for (int i = 1; i <=fctr; i++){
System.out.print(i);
if(i<fctr) {
System.out.print("*");
}
}
Try to add a condition if it’s not at the end of the loop. Then add start and if it’s the end, then just print the number:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int fctr;
System.out.println("number");
fctr = input.nextInt();
for (int i = 1; i <= fctr; i++) {
if (i < fctr) {
System.out.print(i + " * ");
} else {
System.out.print(i);
}
}
}
I always use a construct like
String sep="";
for (...) {
System.out.print(sep);
System.out.print(payload);
sep="x";
}
You need to make the printing of ***** condition. Don't print ***** if i == fctr. And you don't need that additional loop of j. As below :
public static void main(final String[] args) {
final Scanner input = new Scanner(System.in);
int fctr;
System.out.println("number");
fctr = input.nextInt();
// IntStream.range(1, fctr).
long factorial = 1;
for (int i = 1; i <= fctr; i++) {
factorial = factorial * i;
if (i == fctr) {
System.out.print(i);
} else {
System.out.print(i + "*");
}
}
System.out.print("=" + factorial);
}

Print how many pairs of characters in the input line where the first character is less than the second

Im not sure how to compare the characters char < Char and add the count
it should print
Enter a line:
antidisestablishmentarianism\(whatever the user wants to input)
Your Answer 15
import java.util.Scanner;
public class CountRisingPairs {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
System.out.println(" Enter a string");
String S=in.next();
int count;
int value;
for (int i=65; i<91; i++) {
count=0;
for (int j=0; j<in.length(); j++) {
value=(int)in[j];
if (value == i) {
count++;
}
}
if (count>0)
System.out.println((char)i+" -- "+count);
}
}
}
i cant use hash map or any other type of loop.
The loop should iterate over all characters from the first to the next but last so you can compare adjacent characters. They can be compared just like integer values.
String s = "antidisestablishmentarianism";
int count = 0;
for( int i = 0; i < s.length() - 1; ++i ){
if( s.charAt(i) < s.charAt(i+1) ) count++;
}
System.out.println( "count = " + count );
For comparing chars in the input, you should probably keep a variable with the previous char to compare to. I don't think comparing to the index variable i is what you want. Then your if statement would be something like
if (value > previous) {
count++;
}
Also, when iterating over the input of a Scanner, you should probably do it with a while loop like this:
while (in.hasNext()) {
// Your counting here
}
You need a way to terminate that while loop - you can do that by checking for '\n' or something else. And of course, the while loop can be rewritten as a for loop if you want to.
String element = "antidisestablishmentarianism";
int count = 0;
for (int j=0; j<element.length(); j++)
{
if(j+1 < element.length()){
int x = Character.getNumericValue(element.charAt(j));
int y = Character.getNumericValue(element.charAt(j+1));
if(x>y){
count++;
System.out.println("Pair: "+element.charAt(j)+""+element.charAt(j+1));
}
}
}
System.out.println(count+" pairs found");
Based on your code, also closing the scanner using try-with-resources:
import java.util.Scanner;
public class CountRisingPairs {
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.println(" Enter a string");
String inputString = in.next();
int count = 0;
char previousChar = 100;
for (char currentChar : inputString.toCharArray()) {
if (currentChar > previousChar) {
count++;
}
previousChar = currentChar;
}
System.out.println(count);
}
}
}

Counting dashes in sample data

I'm doing a task in which I am told to check for the '-'s in sample data, when a - is found in the data and there are adjacent dashes within the hashes, this only counts for 1 occurrence, e.g. in this sample data the answer would be 4.
I started by creating a 2D array to populate it then I was going to check for the dashes in the array but I am a bit puzzled as to how I would go about actually counting the occurrences, Any help would be appreciated.
Here's what I have so far;
Scanner input = new Scanner(System.in);
int a = input.nextInt(); //no. of rows
int b = input.nextInt(); //no. of columns
String arr[][] = new String[a][b]; //array of strings of 10 x 20
for(int i = 0; i<a; i++){
for(int j = 0; j<b; j++){
arr[i][j] = input.next();
}
}
//for test purposes
for(String[] s : arr){
for(String e : s){
System.out.print(e);
}
}
Here's the sample input:
10 20
#################---
##-###############--
#---################
##-#################
########---#########
#######-----########
########---#########
##################--
#################---
##################-#
Simplest way to use regex. Consider each row as string, trim string and then allow only 20 characters in string(based on your column count).
Other approaches could be to use DSL algos.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test {
public static void main(String... args) throws Exception {
Scanner input = new Scanner(System.in);
int a = input.nextInt(); // no. of rows
int b = input.nextInt(); // no. of columns
Pattern pattern = Pattern.compile("#(--+)#");
int count = 0;
for (int i = 0; i < a; i++) {
String temp = input.next().trim();
if (temp.length() > b) {
temp.substring(0, b);
}
Matcher matcher = pattern.matcher(temp);
if (matcher.find()) {
count++;
}
}
System.out.println(count);
}
}

Using arrays to store primes

Here is my program which is supposed to create an array and initialize prime numbers to it. The prime numbers should then be printed but the program just keeps running.
import java.util.*;
public class primes
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
int[] prime = new int[x];
int div=2,hold=2;
int c=0;
while (prime[x-1]==0)
{
for(int a=2; div>a;a++)
{
if(div>a && div%a==0)
a=div;
else if(div==(a-1))
hold=div;
}
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
div++;
}
for(int f =0; f<x;f++)
System.out.print(" "+prime[f]+" ");
}
}
I tried changing my loops but I just don't know whats wrong
Like the others mentioned your logic is not right, try something like:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
List<Integer> primes = getPrimes(x);
Integer[] primeArray = primes.toArray(new Integer[primes.size()]);
for(int i :primes.toArray(primeArray)){ // you could just use for(int i :primes){ if you don't need array
System.out.print(i + " ");
}
}
private static List<Integer> getPrimes(int upperLimit) {
ArrayList primes = new ArrayList();
for (int i = 2; i < upperLimit; i++) {
boolean isPrime = true;
// Is it prime?
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
primes.add(i);
}
return primes;
}
The above will print out up to the numbers entered so if you type 5 it will print out 2 3 but not 5.
The following is an other example with Java 8, this one will print as many prime numbers based on the input, if you input 5 you will get 2 3 5 7 11
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
long[] prime = primes(x).toArray();
Arrays.stream(prime).forEach(value -> System.out.print(value + " " ));
}
private static LongStream primes(long max) {
return LongStream.iterate(2, i -> i + 1)
.filter(PrimeNumber::isPrime)
.limit(max);
}
private static boolean isPrime(long x) {
return LongStream.rangeClosed(2, (long)(Math.sqrt(x)))
.allMatch(n -> x % n != 0);
}
Your code is wrong. First correct it, And i think you want to store prime numbers coming in range of 1 to N where N is user provided number. Use arrayList (growable) to store it.
It will keep on running because you have this: while (prime[x-1]==0). Where x is an input from the user. Say 5 for instance, then prime[5-1] initially is going to contain a 0 always, and you are running your while loop on this condition which is always going to turn true, thus never ending. Also, your prime number generation logic is not right!
I ran your code in debugger mode and I found the problem.
I tested your program with x=5.
At the end of the first while loop iteration you have :
prime[0] = 2
div = 3
hold = 2
c = 1
And here's the problem :
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
This part won't ever be reached anymore because :
div is never decrement, so it will always be superior to 2.
hold is
equal to prime[c-1], and never change value.
So prime will always stick to be : 2 0 0 0 0, and your while loop will never end.
I found what was wrong and rewrote the code, it works now. The program asks the user for the number primes they want to see and it prints them after storing them in a basic integer array.
import java.util.*;
public class Prime
{
public static void main(String [] args)
{
Scanner scan= new Scanner(System.in);
int i=0, hold=2, d=2;
boolean flag = true;
System.out.println("Enter the number of primes.");
int[] prime= new int[scan.nextInt()];
for(;flag;){
for(int a=2;d>a;a++){
if(d==(a)||d%a==0){
break;
}
if((d-1)==a){
hold = d;
}
}
d++;
if(hold==2 || hold!=prime[i-1]){
prime[i] = hold;
i++;
}
if(i==prime.length)
flag= false;
}
for(int x=0;x<prime.length;x++)
System.out.print(prime[x]+" ");
System.out.println("");
}
}

Digit Frequency In A String

I am supposed to do this :
For an input number print frequency of each number in the order of its occurrence.For eg :
Input:56464
Output:
Number-Frequency
5 -1
6 -2
4 -2
I cannot use any other libraries except java.lang and Scanner to input
So I tried this :
package practice2;
import java.util.Scanner;
public class DigitFrequency2
{
private static Scanner sc;
public static void main(String[] args)
{
sc = new Scanner(System.in);
System.out.println("Enter an integer number");
String sb = sc.nextLine();
System.out.println("Number\tFrequency");
int i,x,c = 0;
for(i=0;i<sb.length();i++)
{
c = 0;
for(x = i+1;x<sb.length();x++)
{
if(sb.charAt(i) == sb.charAt(x) && sb.charAt(i) != '*' && sb.charAt(x) != '*')
{
c++;
sb.replace(sb.charAt(x),'*');
}
}
if(c>0)
{
System.out.println(sb.charAt(i)+" \t"+c);
}
}
}
}
Number Frequency
6 1
4 1
Where am I going wrong please help.
Simple way is this. Won't bother commenting as it is clear whats going on.
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Input String: ");
String line = in.nextLine();
while (!line.isEmpty()) {
char c = line.charAt(0);
int length = line.length();
line = line.replace(String.valueOf(c), "");
System.out.println(c + " " + (length - line.length()));
}
}
There are few problems with sb.replace(sb.charAt(x),'*');:
replace replaces all characters, not just first one which is why your c can't be grater than 1.
Strings are immutable so since replace can't edit original string, it returns new one with replaced characters which you can store back in sb reference.
Anyway if you would be able to use other Java resources beside java.lang.* or java.util.Scanner simple approach would be using Map which will map character with number of its occurrences. Very helpful here is merge method added in Java 8 allows us to pass key initialValue combination of old and new value
So your code can look like:
String sb = ...
Map<Character, Integer> map = new TreeMap<>();
for (char ch : sb.toCharArray()) {
map.merge(ch, 1, Integer::sum);
}
map.forEach((k, v) -> System.out.println(k + "\t" + v));
Problem is that as mentioned, String is immutable, so String.replace() just returns a new string and it does not (cannot) modify the original. Either you should use StringBuilder, or store the returned value (e.g. sb = sb.replace(sb.charAt(x),'*');).
Going further, since you initialize c with 0, it will stay 0 if there is no other occurrence of the character in question (sb.charAt(i)), so your algorithm won't detect and print digits that occur only once (because later you only print if c > 0).
Counting occurrences (frequency) of characters or digits in a string is a simple operation, it does not require to create new strings and it can be done by looping over the characters only once.
Here is a more efficient solution (one of the fastest). Since digits are in the range '0'..'9', you can create an array in which you count the occurrences, and by looping over the characters only once. No need to replace anything. Order of occurrence is "remembered" in another order char array.
char[] order = new char[10];
int[] counts = new int[10];
for (int i = 0, j = 0; i < sb.length(); i++)
if (counts[sb.charAt(i) - '0']++ == 0)
order[j++] = sb.charAt(i); // First occurrence of the digit
And print in order, until the order array is filled:
System.out.println("Number\tFrequency");
for (int i = 0; order[i] != 0; i++)
System.out.println(order[i] + "\t" + counts[order[i] - '0']);
Example output:
Enter an integer number
56464
Number Frequency
5 1
6 2
4 2
For completeness here's the complete main() method:
public static void main(String[] args) {
System.out.println("Enter an integer number");
String sb = new Scanner(System.in).nextLine();
char[] order = new char[10];
int[] counts = new int[10];
for (int i = 0, j = 0; i < sb.length(); i++)
if (counts[sb.charAt(i) - '0']++ == 0)
order[j++] = sb.charAt(i); // First occurrence of the digit
System.out.println("Number\tFrequency");
for (int i = 0; order[i] != 0; i++)
System.out.println(order[i] + "\t" + counts[order[i] - '0']);
}
Note:
If you would want to make your code safe against invalid inputs (that may contain non-digits), you could use Character.isDigit(). Here is only the for loop which is safe against any input:
for (int i = 0, j = 0; i < sb.length(); i++) {
char ch = sb.charAt(i);
if (Character.isDigit(ch)) {
if (counts[ch - '0']++ == 0)
order[j++] = ch; // First occurrence of ch
}
}
This should be a good code to print frequency using user input:
public static void main(String args[])
{
System.out.println("Please enter numbers ");
String time = in.nextLine(); //USER INPUT
time = time.replace(":", "");
char digit[] = {time.charAt(0), time.charAt(1), time.charAt(2), time.charAt(3)};
int[] count = new int[digit.length];
Arrays.sort(digit);
for (int i = 0; i < digit.length; i++)
{
count[i]++;
if (i + 1 < digit.length)
{
if (digit[i] == digit[i + 1])
{
count[i]++;
i++;
}
}
}
for (int i = 0; i < digit.length; i++)
{
if (count[i] > 0)
{
System.out.println(digit[i] + " appears " + count[i]+" time(s)");
}
}
}

Categories