skip characters/numbers in JAVA - java

How do I skip a number or a character same for two numbers or characters together or apart while those characters/numbers exist within a row of numbers or word
example (not lists):
I want to skip the number 3 (in any position) when I count from 2 to 14
the result would be
2,4,5,6,7,8,9,10,11,12,14
another would be skipping the number 31 in any combination where 3 and 1 come out as long as both exist
these two examples would apply for the characters also.
What I was doing was
for(int i = startingNum; i <= endingNum; i++){
if(i "has a" 3){
skip number;
}
else{
counter++;
}
}
combination of numbers
for(int i = startingNum; i <= endingNum; i++){
if((i "has a" 3) AND (i "has a " 1)){
skip number;
}
else{
counter++;
}
}
at the character one I'm completely lost...

One way would be to convert the number to a string and check if it contains that number as a substring:
for(int i = startingNum; i <= endingNum; i++) {
if (!String.valueOf(i).contains("3")) { // Here
counter++;
}
}

One of the approaches is using results of parsing, for example:
public static Integer isParsable(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
...
import java.io.IOException;
public class NumChecker {
static String[] str = new String[]{"2", "4", "a", "sd", "d5", "6", "7", "8", "a1", "3", "10", "11", "12", "14"};
static int startingNum = 2;
static int endingNum = 10;
static int counter = 0;
static int mark = 3;
public static Integer isParsable(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
public static void main(String[] args) throws IOException {
for (int i = startingNum; i <= endingNum; i++) {
Integer num = isParsable(str[i]);
if (num != null) {
if (num == mark) {
counter++;
}
}
}
System.out.println(counter);
}
}
OUTPUT:
1

Related

Is there any way to count integer elements in text file?

So I have a text file as :
and I want to count the number of integers in the first row.
// e.g. The first row : 3 12 1 8 5 8 1 2 1 4 --> 10
Can I do that with a stream or for statement or another way?
I tried with for and it didn't work for me and I couldn't find any useful solution. Please, help me.
public class Egyszamjatek {
public static void main(String[] args) throws IOException {
List<String> game = Files.readAllLines(Paths.get("egyszamjatek.txt"));
ArrayList<OneGame> games = new ArrayList<>();
for (String game1 : game) {
String[] split = game1.split(" ");
int rounds = Integer.parseInt(split[0]) + Integer.parseInt(split[1]) + Integer.parseInt(split[2])
+ Integer.parseInt(split[3]) + Integer.parseInt(split[4]) + Integer.parseInt(split[5])
+ Integer.parseInt(split[6]) + Integer.parseInt(split[7]) + Integer.parseInt(split[8])
+ Integer.parseInt(split[9]);
String names = split[10];
games.add(new OneGame(rounds, names));
}
System.out.println("3.feladat: number of players : " + game.stream().count());
System.out.println("4. feladat: number of rounds: " );
}
static class OneGame {
int rounds;
String names;
public OneGame(int rounds, String names) {
this.rounds = rounds;
this.names = names;
}
}
}
solution with for loop
String firstLine = "3 12 1 8 5 8 1 2 1 4";
String[] splits = firstLine.split(" ");
int count = 0 ;
for(String intStr:splits){
try {
int i = Integer.parseInt(intStr);
count++;
}catch (NumberFormatException e){
e.printStackTrace();
}
}
System.out.println(count);
You could do something like:
List<OneGame> games = Files.lines(Paths.get("egyszamjatek.txt")) // Stream<String> each line as a single String
.map(g -> {
String[] split = g.split(" ");
int rounds = (int) Arrays.stream(split)
.filter(a -> isInteger(a)) // filter only integers
.count(); // count how many integers e.g. 10 in your first line
return new OneGame(rounds, split[rounds]); // create an instance with count and name
}).collect(Collectors.toList()); // collect to list
where isInteger(a) is a util that you can use from this answer. Its implementation would be :
public static boolean isInteger(String str) {
if (str == null) {
return false;
}
if (str.isEmpty()) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (str.length() == 1) {
return false;
}
i = 1;
}
for (; i < str.length(); i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
Note: the code relies on certain assumptions for e.g. the integer values for the number of rounds would supersede the name of the game and hence uses split[rounds] to access the name.

Sort array by value type

One array contains both numeric strings and mixed string values. How to sort this array and print numeric values first and remaining strings after?
String[] s = {"1","2","13","13a","10","10a","1a","1,"};
I want output like this --> 1 10 13 2 1, 10a 13a 1a
i am trying like this , and i got correct output but i want make it as easy way
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.*;
public class sortprog {
public static void main(String[] args) {
String[] s={"1","2","13","13a","10","10a","1a","1,"};
ArrayList alnubers=new ArrayList();
ArrayList alstrings=new ArrayList();
int count=0;
for(int i=0;i<s.length;i++)
{
if(Pattern.matches("[0-9]+",s[i]))
{
alnubers.add(s[i]);
}
else
{
alstrings.add(s[i]);
}
}
/*for(int i=0;i<s.length;i++)
{
String str=s[i];
for ( int j = 0; j < str.length(); ++j )
{
char c = str.charAt(j);
int k = (int) c;
//System.out.println("ASCII OF "+c +" = " + k + ".");
if(k>=48&&k<=57)
{
count++;
}
else
{
count=0;
break;
}
}
if(count!=0)
{
alnubers.add(str);
count=0;
}
else
{
alstrings.add(str);
count=0;
}
}*/
String[] sarr = new String[alstrings.size()];
alstrings.toArray(sarr);
Arrays.sort(sarr);
String[] narr = new String[alnubers.size()];
alnubers.toArray(narr);
Arrays.sort(narr);
String[] finalarr=new String[sarr.length+narr.length];
for(int l=0;l<narr.length;l++)
{
finalarr[l]=narr[l];
}
int i=0;
for(int l=narr.length;l<sarr.length+narr.length;l++)
{
finalarr[l]=sarr[i];
i++;
}
for(int f=0;f<finalarr.length;f++)
{
System.out.println(finalarr[f]);
}
}
}
You can call sort with your own comparator:
String[] s = { "1", "2", "13", "13a", "10", "10a", "1a", "1," };
Arrays.sort(s, new Comparator<String>() {
#Override
public int compare(String arg0, String arg1) {
if (arg0.matches("\\d+")
&& !arg1.matches("\\d+")) {
return -1;
} else if (!arg0.matches("\\d+")
&& arg1.matches("\\d+")) {
return 1;
} else {
return 0;
}
}
});
System.out.println(Arrays.toString(s));
What this does is create a comparator that makes strings containing just digits (\\d) of lower order than things that don't, so they will come first when sorted.
You can put in any code you like in the comparator, so if you want to have a number followed by a comma first, then this is easy to do.

Poker game hand evaluator arrays condition structure

I made up a quick poker game. It generates 5 random numbers and converts those numbers into actual cards values and symbols based on their value. However, I have problems when it comes to making the hand evaluation.
So far I only did the flush right as it's really easy but even then it's not perfect (it prints that the user has a flush 5 times... ) and I would really appreciate if someone could help me with the pair, two pair, three of a kind and straight. I could do the rest afterwards but I just need a heads-up on how to do those.
Thank you in advance for your help, here is the code :
package tests;
import java.util.*;
public class TESTS {
public static void main(String[] args) {
boolean[] pack = new boolean[52]; // Array to not generate the same number twice
int[] cards = new int[5]; //The 5 unique random numbers are stored in here.
String[] cardsvalues = new String[5]; // This will assign the card's value based on the random number's value
char[] cardssymbols = new char[5];//This will assign the card's symbol based on the random number's value
char symbols[] = {'♥', '♦', '♣', '♠'}; // possible symbols that the random number can take
String values[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}; // possible values that the random number can take
Random give = new Random();
for (int i = 0; i < cards.length; i++) { // Gives 5 unique random numbers
do {
cards[i] = give.nextInt(52);
} while (pack[cards[i]]);
pack[cards[i]] = true;
System.out.println(cards[i]);
}
for (int i = 0; i < cards.length; i++) { // This converts the number to a card symbol based on the number's value
final int numOfSymbol = cards[i] / 13;
cardssymbols[i] = symbols[numOfSymbol];
}
for (int i = 0; i < cards.length; i++) { // This converts the number to an actual card value based on the number's value.
final int numOfValues = cards[i] % 13;
cardsvalues[i] = values[numOfValues];
}
for (int i = 0; i < cardssymbols.length; i++) { // Prints the actual cards once they are converted
System.out.print(cardssymbols[i]);
System.out.println(cardsvalues[i]);
}
for (int i = 0; i < cardsvalues.length; i++) { //Here is the problem, i have no idea on how to make the handevaluator ...
if (cardsvalues[i] == cardsvalues[i] + 1) {
System.out.println("PAIR !!!");
} else if (cardsvalues[i] == cardsvalues[i] + 1 && cardsvalues[i] == cardsvalues[i] + 2) {
System.out.println("TRIPS !!!");
} else if (cardssymbols[0] == cardssymbols[1] && cardssymbols[1] == cardssymbols[2] && cardssymbols[2] == cardssymbols[3] && cardssymbols[3] == cardssymbols[4]) {
System.out.println("FLUSHHH");
}
}
}
Hints:
To simplify testing for straights and sorting by highest card, it is easier to represent ranks by their indexes, and only translate them to the symbols for printing.
Using a Card object allows for clearer code.
The Java Collection framework has useful functions for shuffling, slicing and sorting.
My solution:
public class Test {
static final char[] suits = {'♥', '♦', '♣', '♠'};
static final String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
static class Card {
final int suit;
final int rank;
Card(int s, int r) {
suit = s;
rank = r;
}
#Override
public String toString() {
return suits[suit] + ranks[rank]; // or however you want the cards to be printed
}
}
public static void main(String[] args) {
List<Card> deck = new ArrayList<>();
for (int s = 0; s < suits.length; s++) {
for (int r = 0; r < ranks.length; r++) {
deck.add(new Card(s,r));
}
}
Collections.shuffle(deck);
List<Card> hand = deck.subList(0,5);
Collections.sort(hand, Comparator.comparing(c -> c.rank));
System.out.println("Your hand is: " + hand);
System.out.println(value(hand));
}
static String value(List<Card> hand) {
boolean straight = true;
boolean flush = true;
for (int i = 1; i < hand.size(); i++) {
straight &= hand.get(i - 1).rank + 1 == hand.get(i).rank;
flush &= hand.get(i - 1).suit == hand.get(i).suit;
}
if (straight && flush) {
return "Straight Flush from " + hand.get(4);
}
List<Run> runs = findRuns(hand);
runs.sort(Comparator.comparing(r -> -r.rank));
runs.sort(Comparator.comparing(r -> -r.length));
if (runs.get(0).length == 4) {
return "Four of a Kind: " + runs;
}
if (runs.get(0).length == 3 && runs.get(1).length == 2) {
return "Full House: " + runs;
}
if (straight) {
return "Straight from " + hand.get(4);
}
if (runs.get(0).length == 3) {
return "Three of a Kind: " + runs;
}
if (runs.get(1).length == 2) {
return "Two pair: " + runs;
}
if (runs.get(0).length == 2) {
return "Pair: " + runs;
}
return "High card: " + runs;
}
/** Represents {#code length} cards of rank {#code rank} */
static class Run {
int length;
int rank;
#Override
public String toString() {
return ranks[rank];
}
}
static List<Run> findRuns(List<Card> hand) {
List<Run> runs = new ArrayList<>();
Run run = null;
for (Card c : hand) {
if (run != null && run.rank == c.rank) {
run.length++;
} else {
run = new Run();
runs.add(run);
run.rank = c.rank;
run.length = 1;
}
}
return runs;
}
}
Example output:
Your hand is: [♣10, ♥J, ♦J, ♠K, ♥K]
Two pair: [K, J, 10]

Numbers to letters in java (like old mobile phones' keyboard)

Just like older mobile phones' keypads work. I should input a string of numbers and the program should print out a text based on those numbers.
e.g: Input: 4448 9666777557777 should output to: ITWORKS.
Here's my code so far but it's not printing out anything. Could you please tell me what's wrong with it and what could've I done better?
Scanner sc = new Scanner(System.in);
String[] letters = {
"0",
"1",
"ABC",
"DEF",
"GHI",
"JKL",
"MNO",
"PQRS",
"TUV",
"WXYZ"
};
System.out.println("Write something.");
String numbers = sc.nextLine();
char[] toChar = numbers.toCharArray();
int count = 0;
for (int index = 0; index < toChar.length; index++) {
if (toChar[index] >= '2' && toChar[index] <= '9') {
if (index > 0 && toChar[index] == toChar[index - 1]) {
count++;
}
else if (count > 0) {
System.out.print(letters[toChar[index - 1] - '0'].charAt(count - 1));
count = 0;
}
}
}
How about this?
import java.util.Scanner;
public class Test {
private static final String[] letters = {
"0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
};
private static char getChar(int digit, int count) {
while (count > letters[digit].length()) {
count -= letters[digit].length();
}
return letters[digit].charAt(count - 1);
}
private static String getString(String input) {
int lastDigit = 0, count = 1;
String result = "";
for (int i = 0; i < input.length(); i++) {
int currentDigit = input.charAt(i) - '0';
if (currentDigit >= 2 && currentDigit <= 9) {
if (lastDigit == 0) {
lastDigit = currentDigit;
} else if (currentDigit == lastDigit) {
count++;
} else {
result += getChar(lastDigit, count);
lastDigit = currentDigit;
count = 1;
}
}
}
return result + getChar(lastDigit, count);
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Write something");
System.out.println(getString(scanner.nextLine()));
}
}
}
I enhanced the problem decomposition. It works for all examples OP has shown so far.
If I understand your intention correctly, count should increment only if current digit is the same as previous:
for (int pos = 1, char c = toChar[0], int count = 1; pos <= toChar.length; pos++, count = 1) {
int n = letters[c - '0'].length;
while (pos < toChar.length && c == toChar[pos] && count < n) {
pos++;
count++;
}
System.out.println(letters[c - '0'].charAt(count - 1));
if (pos < toChar.length - 1) {
c = toChar[++pos];
}
}
This code will help you!
Check this one
public class Denene {
public static String getChar(String cha)
{
String [] chars= {"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
String[] strSplit = cha.split(" "); //7777 88 7777 2 66 8
int len=strSplit.length;
char r;
char []ar =new char[len];
for(int i=0;i<len;i++){
String str=strSplit[i];
ar[i]= chars[Integer.parseInt(String.valueOf(str.charAt(0)))].charAt(str.length()-1);
}
return new String(ar);
}
public static void main(String[] args) {
System.out.println("Enter any number .....");
System.out.println(getChar(new Scanner(System.in).nextLine())); //Output : susant
}
}

Replacing digit words into digits

I am trying to replace all digit words zero-nine into their corresponding digits 0-9 in a string.
I have created the two arrays of digit words and digits and then trying for loop with a replace to change the sentence.
Not sure what i am doing wrong.
I'm referencing my getNoDigitWordString method.
import java.util.*;
public class StringProcessor {
private String noSpaces;
private String input, noVowels;
private String noDigitWords;
private int numOfWords = 0, uppercaseLetters = 0,
numOfDigits = 0, digitWords = 0;
private String [] wordDigits = {"zero","one", "two", "three","four",
"five", "six", "seven", "eight", "nine"};
private String [] digits = {"0", "1", "2", "3", "4",
"5", "6", "7", "8", "9"};
public StringProcessor()
{
input = "";
}
public StringProcessor(String s)
{
StringTokenizer str = new StringTokenizer(s);
numOfWords = str.countTokens();
for (int i = 0; i < s.length(); i++)
{
if (Character.isUpperCase(s.charAt(i)))
uppercaseLetters++;
}
for (int i = 0; i < s.length(); i++)
{
if (Character.isDigit(s.charAt(i)))
numOfDigits++;
}
String [] strSplit = s.split(" ");
for(int i = 0; i < strSplit.length; i++)
{
for (int j = 0; j < wordDigits.length; j++)
{
if (strSplit[i].equalsIgnoreCase(wordDigits[j]))
digitWords++;
}
}
noSpaces = s.replace(" ","");
noVowels = s.replaceAll("[aeiou]", "-");
for(int i = 0; i < 10; i++)
{
noDigitWords = s.replace("wordDigits[i]", "digits[i]");
}
}
public void setString(String s)
{
input = s;
}
public String getString()
{
return input;
}
public int wordCount()
{
return numOfWords;
}
public int uppercaseCount()
{
return uppercaseLetters;
}
public int digitCount()
{
return numOfDigits;
}
public int digitWordCount()
{
return digitWords;
}
public String getNoSpaceString()
{
return noSpaces;
}
public String getNoVowelString()
{
return noVowels;
}
public String getNoDigitWordString()
{
return noDigitWords;
}
public static void main(String[] args)
{
String input;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a line of text: ");
input = keyboard.nextLine();
StringProcessor str = new StringProcessor(input);
System.out.println("words: " + str.wordCount());
System.out.println("uppercase: " + str.uppercaseCount());
System.out.println("digits: " + str.digitCount());
System.out.println("digit words " + str.digitWordCount());
System.out.println("line with no spaces: " + str.getNoSpaceString());
System.out.println("line with vowels replaced: " + str.getNoVowelString());
System.out.println("line with digit words replaced: " + str.getNoDigitWordString());
}
}
Thanks.
This is what you're looking for:
noDigitWords = s;
for(int i = 0; i < strSplit.length; i++)
{
for (int j = 0; j < wordDigits.length; j++)
{
if (strSplit[i].equalsIgnoreCase(wordDigits[j])){
noDigitWords = noDigitWords.replace(strSplit[i], digits[j]);
break;
}
}
}
Instead of this:
for(int i = 0; i < 10; i++)
{
noDigitWords = s.replace("wordDigits[i]", "digits[i]");
}
Aside from the problem #dcharms pointed out, this is not going to work:
for(int i = 0; i < 10; i++)
{
noDigitWords = s.replace(wordDigits[i], digits[i]);
}
Here's what happens: First, you search s for "zero", and call s.replace. This returns a string with the word "zero" replaced by "0". Then that string is assigned to noDigitWords. But s itself does not change.
Then, next time through the loop, you search in the original s for the next word. The work you did in the previous iteration, which was in noDigitWords, gets thrown away.
The result will be that the last word you search for, "nine", should get replaced. But any other replacements you've made will be thrown away.
Each time the following code calls the replace method, the string noDigitWords is overwritten.
for(int i = 0; i < 10; i++)
{
noDigitWords = s.replace("wordDigits[i]", "digits[i]");
}
After the final iteration of the loop, the string "one nine" becomes "one 9" rather than "1 9" as desired. The solution is to call the replace method on the return value of the previous iteration of the loop. Initialize the string noDigitWords to the value of the string s. Each iteration do the replace on noDigitWords as shown below.
noDigitWords = s;
for(int i = 0; i < 10; i++)
{
noDigitWords = noDigitWords.replace(wordDigits[i], digits[i]);
}
Try replacing noDigitWords = s.replace("wordDigits[i]", "digits[i]"); with noDigitWords = s; outside for loop and
noDigitWords = noDigitWords.replaceAll(wordDigits[i], digits[i]); inside.
Your original was looking for a string "wordDigits[i]" instead of the contents of wordDigits[i]. Your output had a similar issue.

Categories