I am writing a code for translating Signals from one form to another form.
My code works well but fails for the ends.
INPUT: String [] test = {"B","100","B","B","2","3","100","B","200","B","3","17","B","10" };
REQUIRED OUTPUT: B/101 B/1 B/106 B/201 B/21 B/11
GOT OUTPUT: B/1 B/101 B/1 B/106 B/201 B/21
Comparison of Required Output and got output
The first term B/1 is not required in got output.
B/11 is missing at the end in the required output.
ALGORITHM: "B" is replaced by "B/", and followed by addition of numbers appearing in Strings like "2", "3","100" which gives 105 and "1"
is to be added for "B" hence 106 and final result becomes 'B/106'.
I am new comer to java and programming. I need help to get the required output.
This is my code:
public class SignalConversion {
public static void main(String args[]) {
String [] test ={"B","100","B","B","2","3","100","B","200","B","3","17","B","10" };
int i=0; int x=test.length;
String netSignal="";
int total=0;
while(!(x==0)){
StringBuilder sb_matra= new StringBuilder();
StringBuilder sb_sur= new StringBuilder();
if(!test[i].equals("B")) {
total=total+(Integer.valueOf(test[i]));
}
else {
total=total+1;
sb_sur.append(test[i]+"/"+Integer.toString(total)+" " );
total=0;
}
netSignal=sb_sur.toString()+sb_matra.toString();
System.out.printf(netSignal);
i++;
x--;
}
}
}
When you encounter a "B", you should start summing the numbers following it, but only output the result when you encounter the next "B". That's why you have a problem at the ends. You print the first "B" when you encounter it, before calculating the number that should come with it.
Similarly, at the end of the loop, you should add an additional B with the last sum.
Here's a potential way of doing it (I think this loop is simpler than yours):
StringBuilder sb_sur= new StringBuilder();
boolean first = true;
for (int i = 0; i < test.length; i++) {
if(!test[i].equals("B")) {
total=total+(Integer.valueOf(test[i]));
} else {
if (!first) {
total=total+1;
sb_sur.append("B/"+Integer.toString(total)+" " );
total=0;
}
first = false;
}
}
total=total+1;
// account for the last B
sb_sur.append("B/"+Integer.toString(total)+" " );
I would have done this way,
public static void main(String[] args) {
String[] test = { "B", "100", "B", "B", "2", "3", "100", "B", "200",
"B", "3", "17", "B", "10" };
boolean foundB = false;
int total = 0;
for(int i=0;i<test.length;i++){
if(foundB){
if(test[i].equals("B")){
System.out.print("B/"+(total+1)+" ");
total=0;
}else{
total += Integer.parseInt(test[i]);
}
if(i==(test.length-1)){
System.out.print("B/"+(total+1)+" "); // The last B
}
}
if(test[i].equals("B")){
foundB = true; // start counting only after you find a B
}
}
}
Oh, i see Eran has made nearly the same attemp.
String[] test = { "B", "100", "B", "B", "2", "3", "100", "B", "200", "B", "3", "17", "B", "10" };
List<String> resultTest = new ArrayList<>();
int value = 0;
for (int i = 0; i < test.length; i++) {
if (i != 0 && test[i].equalsIgnoreCase("B")) {
resultTest.add("B\\" + (value + 1));
value = 0;
} else {
if (!test[i].equalsIgnoreCase("B")) {
value += Integer.parseInt(test[i]);
}
}
}
resultTest.add("B\\" + (value + 1));
resultTest.forEach(System.out::println);
Related
I'm a bit stuck on how I should replace each element in char array to a number.
Here's the code I have so far:
public static void main(String []args){
String[] dialTwo = {"a", "b", "c"};
String[] dialThree = {"d", "e", "f"};
String[] dialFour = {"g", "h", "i"};
String[] dialFive = {"j", "k", "l"};
String[] dialSix = {"m", "n", "o"};
String[] dialSeven = {"p", "q", "r", "s"};
String[] dialEight = {"t", "u", "v"};
String[] dialNine = {"w", "x", "y", "z"};
Scanner in = new Scanner(System.in);
System.out.print("Enter a phone number: ");
String phoneInput = in.next();
char[] inputToArray = phoneInput.toCharArray();
while (!phoneInput.matches("^[a-pA-P0-9]*$")) {
System.out.println("Not a valid number. Try agian.");
phoneInput = in.next();
}
I was able to successfully verify the string in case someone wanted to enter ;;';';.
Thank you for your help guys.
My teacher also wants me to use method classes, but I'm slightly confused on it so I'm doing it a bit differently.
So the output I want, if someone were to input "CFG" it would print 123.
My solution would be a bit simpler.
First, I would not use those arrays but one 2D array like :
static char[][] keyboard = {
{'a','b','c'}, //2
{'d','e','f'}, //3
{'g','h','i'}, //4
{'j','k','l'}, //5
{'m','n','o'}, //6
{'p','q','r','s'}, //7
{'t','u','v'}, //8
{'w','x','y','z'} //9
};
Then, from this, I would loop on every character of the input you have. For each character, I would search on which array it is. The value you need is the index + 2. So using a simple for-loop on keyboard, you can find where is the character and print the value you want. There is exception for numeric, space and symbol of course.
for each character in input
if character is numeric
output ( toNumeric ( character ) )
else
index = 0
while character not found
if character in array[index]
output ( index + 2 )
index++
For more code, well, you need to give more information because you need to work a bit too ;)
You can use Collections instead of String[]. Probably map would be good. But, since you are using String[] following code should help:
for (int i = 0; i < inputToArray.length; i++) {
if (Arrays.asList(dialTwo).contains(inputToArray[i]))
inputToArray[i]=2;
...
}
You need to fill the ... part with other if else conditions where you check for inputToArray[i] with other arrays and replace accordingly.
A simple way to do that is to map a function to use map
inputToArray.stream().map(/*some function*/).toArray();
private void int /*your function*/(char c){...}
A little rusty on Java so can't claim the syntax is correct but basically map a function that takes a char and returns your desired int to your array. After that all you have to do is write the actual function you are mapping.
There's also a number of ways you could just parse the string returned by next as there doesn't seem to be any particular reason in your code for the conversion to a char array
It should also be mentioned that it is rather inefficient to have arrays of 1 length strings for no specific reason. You could easily use strings instead
public static void main(String[] args) {
String[] dialTwo = { "a", "b", "c" };
String[] dialThree = { "d", "e", "f" };
String[] dialFour = { "g", "h", "i" };
String[] dialFive = { "j", "k", "l" };
String[] dialSix = { "m", "n", "o" };
String[] dialSeven = { "p", "q", "r", "s" };
String[] dialEight = { "t", "u", "v" };
String[] dialNine = { "w", "x", "y", "z" };
Scanner in = new Scanner(System.in);
System.out.print("Enter a phone number: ");
String phoneInput = in.next();
char[] inputToArray = phoneInput.toCharArray();
int i = 0;
while (!phoneInput.matches("^[a-zA-Z0-9]*$")) { // Used to check if any
// special character is
// enter in phone number
System.out.println("Not a valid number. Try agian.");
phoneInput = in.next();
}
List<String> one = (List) Arrays.asList(dialTwo);
// for converting array into list so that we can use contains method
// which is not //available in array
List<String> two = (List) Arrays.asList(dialThree);
List<String> three = (List) Arrays.asList(dialFour);
List<String> four = (List) Arrays.asList(dialFive);
List<String> five = (List) Arrays.asList(dialSix);
List<String> six = (List) Arrays.asList(dialSeven);
List<String> seven = (List) Arrays.asList(dialEight);
List<String> eight = (List) Arrays.asList(dialNine);
while (i < inputToArray.length) {
if (inputToArray[i] >= 48 && inputToArray[i] <= 57) {
// for numeric characters
System.out.print(inputToArray[i]);
} else if (one.contains(String.valueOf(inputToArray[i]).toLowerCase()))
/*
* searches given character by converting it into lower case in case
* of capital letters
*/
{
System.out.print(1);
} else if (two.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(2);
} else if (three.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(3);
} else if (four.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(4);
} else if (five.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(5);
} else if (six.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(6);
} else if (seven.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(7);
} else if (eight.contains(String.valueOf(inputToArray[i]).toLowerCase())) {
System.out.print(8);
}
i++;// counter variable for counting number of chars entered
}
}
We can use Regular Expression(regex) here to find alphabets in the input and replace each with corresponding integer till entire value contains integers.
Add the following code:
/*Search and replace all alphabets till only numbers are left in the string*/
while(phoneInput.matches("^[a-zA-Z0-9]*$") && !phoneInput.matches("^[0-9]*$")){
/*
* Scenario 1:
* The regex used will search for one occurrence of alphabets a, b & c(both upper and lower case)
* and replace with "1".
* Same goes down for other values as well.
*/
phoneInput = phoneInput.replaceFirst("[a-cA-C]", "2");
phoneInput = phoneInput.replaceFirst("[d-fD-F]", "3");
phoneInput = phoneInput.replaceFirst("[g-iG-I]", "4");
phoneInput = phoneInput.replaceFirst("[j-lJ-L]", "5");
phoneInput = phoneInput.replaceFirst("[m-oM-O]", "6");
phoneInput = phoneInput.replaceFirst("[p-sP-S]", "7");
phoneInput = phoneInput.replaceFirst("[t-vT-V]", "8");
phoneInput = phoneInput.replaceFirst("[w-zW-Z]", "9");
}
System.out.println("The formatted phone number is: " + phoneInput);
This should serve the purpose.
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]
I'm writing a function for a program and I need to generate a list of numbers in an Object[]
For example.
Object[] possibilities = functionName(13);
Should generate
Object[] possibilities = {"1", "2", "3","4","5","6","7","8","9","10","11","12","13"};
How should I go about achieving this?
String functionName(int number){
StringBuilder str = new StringBuilder("{");
for(int i = 1; i <= number; i++){
str.append(Integer.toString(i)).append(", ");}
String string = str.toString().trim();
string = string.substring(0, str.length()-1);
string += "}";
return string;
}
This should give you the desired string and you just print it.
First, you need a method to print the results from your functionName (that's setting a goal post). Something like,
public static void main(String[] args) {
Object[] possibilities = functionName(13);
System.out.println(Arrays.toString(possibilities));
}
Then you might implement functionName with a basic for loop like
static Object[] functionName(int c) {
Object[] ret = new String[c];
for (int i = 0; i < c; i++) {
StringBuilder sb = new StringBuilder();
sb.append("\"").append(i + 1).append("\"");
ret[i] = sb.toString();
}
return ret;
}
And when I run the above I get (the requested)
["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]
Try this method.
private Object[] function(int size) {
Object[] result = new String[size];
for (int i = 0; i < size; i++) {
result[i] = Integer.toString(i + 1);
}
return result;
}
}
I am keen to sort only numeric elements that are in String array. I am doing it in java. Please help me to solve this Problem.
Here is my Problem
For the given set of characters, choose integers only and sort them in descending order and put in their position leaving other characters position intact.
The change is position should only be of integers not of other characters.
Sample Input:-
d,1,4,c,9,6
109,87,911,b,645
77,19,#,.,95
8,99,14,2,5,6,49
Sample Output:-
Case #1: d,9,6,c,4,1
Case #2: 911,645,109,b,87
Case #3: 95,77,#,.,19
Case #4: 99,49,14,8,6,5,2
Thank you to all viewer. Please would you all help me to solve this problem in Java
Here is my Code, I have tried So far.
import java.util.Arrays;
import java.util.Iterator;
import java.util.ArrayList;
class alphaNumeric {
public static void main(String a[]) {
String s1[] = new String[9];
ArrayList l_numList = new ArrayList();
ArrayList l_strList = new ArrayList();
s1[0] = "1000.1";
s1[1] = "100";
s1[2] = "xBC100";
s1[3] = "XBB100";
s1[4] = "TEST";
s1[5] = "AYZ2100";
s1[6] = "99";
s1[7] = "90";
s1[8] = "1000";
System.out.print("Before sorting, numbers are ");
for(int i = 0; i < s1.length; i++)
{
System.out.print(s1[i]+" ");
}
System.out.println();
for (int i = 0; i < s1.length; i++) {
if (isNumber(s1[i])) {
l_numList.add(s1[i]);
} else {
l_strList.add(s1[i]);
}
}
Object[] l_objArray = (Object[]) l_numList.toArray();
int l_intArray[] = new int[l_objArray.length];
for (int i = 0; i < l_objArray.length; i++) {
l_intArray[i] = Integer.parseInt((String) l_objArray[i]);
}
Arrays.sort(l_intArray);
for (int i = 0; i < l_intArray.length; i++) {
System.out.println("after Numsort: " + l_intArray[i]);
}
System.out.print("After sorting, numbers are ");
for(int i = 0; i < l_intArray.length; i++)
{
System.out.print(l_intArray[i]+" ");
}
Object[] l_strArray = (Object[]) l_strList.toArray();
Arrays.sort(l_strArray);
for (int i = 0; i < l_strArray.length; i++) {
System.out.println("after Strsort: " + l_strArray[i]);
}
}
static boolean isNumber(String s) {
String validChars = "0123456789";
boolean isNumber = true;
for (int i = 0; i < s.length() && isNumber; i++) {
char c = s.charAt(i);
if (validChars.indexOf(c) == -1) {
isNumber = false;
} else {
isNumber = true;
}
}
return isNumber;
}
}
I couldn't figure out what you were trying to do, but here's how I'd do it
Extract a List of only the Integers AND create List of indexes at which they occur in original array
Sort that List using standard reverse sort
Put sorted List values back into the original array, using index List
Working example
public class SortOnlyNumbers {
public static void main(String[] args) {
sortOnlyNumbers(new String[] { "d", "1", "4", "c", "9", "6" });
sortOnlyNumbers(new String[] { "109", "87", "911", "b", "645" });
sortOnlyNumbers(new String[] { "77", "19", "#", ".", "95" });
sortOnlyNumbers(new String[] { "8", "99", "14", "2", "5", "6", "49" });
}
private static void sortOnlyNumbers(String[] array) {
List<Integer> indexes = new ArrayList<Integer>();
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
try {
numbers.add(Integer.parseInt(array[i]));
indexes.add(i);
} catch (NumberFormatException e) {
// don't care
}
}
Collections.sort(numbers, Collections.reverseOrder());
for (int i = 0; i < numbers.size(); i++) {
array[indexes.get(i)] = String.valueOf(numbers.get(i));
}
System.out.println(Arrays.toString(array));
}
}
Output
[d, 9, 6, c, 4, 1]
[911, 645, 109, b, 87]
[95, 77, #, ., 19]
[99, 49, 14, 8, 6, 5, 2]
i'm trying to get elements of an array based on a simple algorithm. in this example i get the elements whose indexes sum are two(module three) i wrote the method but the jcreator gives me "return statement is missing". how can i solve this.
public class hw1 {
public static void main(String[] args) {
String[][] RaggedArray = {
{ "hello", "hi", "i", "nice", "good", "love" },
{ "what", "java", "there" },
{ "and", "cool", "door", "my" },
{ "time", "phone", "homework" }
};
System.out.println(hw_one(RaggedArray));
}
public static String hw_one(String[][] array) {
String result;
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
if ((row + column) % 3 == 2) {
result = array[row][column];
}
}
}
return result;
}
}
I don't see how you can get a "return statement is missing" error when it clearly is not.
That said, my compiler complains that you're returning a potentially uninitialized variable (result). The following fixes the problem:
String result = null;
^^^^^^
you have to initialize the local varibale result before you use it.
Initialize it to null or an empty string.
String result = null; or String result = "";