public static String generate(){
StringBuffer stringBuffer = new StringBuffer();
for(int i = 0; i < TicTacToeUtil.NUM_OF_SPACES + 1; i++){
for(int j = 0; j < TicTacToeUtil.NUM_OF_SPACES + 1; j++) {
stringBuffer.append("1");
}
stringBuffer.append(" ");
}
String finalString = stringBuffer.toString();
return finalString;
}
the code above is basically a game, NUM_OF_SPACES = 2, so the print will be "111 111 111",but , I want to replace all the 1s by either 'X' or 'O', which is randomly chosen between these two char. For example,"XOX XOO OOO", this is generated randomly. Thanks in advance.
You can use the Random#nextBoolean() method to get either true or false randomly. If the value is true, append 'X. Otherwise append 'O':
public static String generate()
{
Random r = new Random(); // create a Random object
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 2 + 1; i++) {
for (int j = 0; j < 2 + 1; j++) {
if (r.nextBoolean()) { // r.nextBoolean() return 'true' or 'false'
stringBuilder.append("X");
} else {
stringBuilder.append("O");
}
}
stringBuilder.append(" ");
}
String finalString = stringBuilder.toString();
return finalString; // return stringBuilder.toString();
}
You can use Random class to generate random numbers. Here I used nextBoolean() method from Random class to generate boolean value randomly.
public static String generate() {
StringBuilder stringBuilder = new StringBuilder();
Random r = new Random(); // create a Random object
for (int i = 0; i <TicTacToeUtil.NUM_OF_SPACES+ 1; i++) {
for (int j = 0; j <TicTacToeUtil.NUM_OF_SPACES + 1; j++) {
if (r.nextBoolean()) { // r.nextBoolean() return 'true' or 'false'
stringBuilder.append("X");
} else {
stringBuilder.append("O");
}
}
stringBuilder.append(" ");
}
String finalString = stringBuilder.toString();
return finalString;
}
I selected a value for TicTacToeUtil.NUM_OF_SPACES as 2 and the output was like follows,
XXX XOO XXX
I replaced StringBuffer with StringBuilder as it's common practice. ( I think StringBuffer class is replicated. )
Related
so i am supposed to print out a list of string in this format. 2017/2018 , 2018/2019, 2019/2020 up until 2029/2030 in this same format, please i am stuck and have no idea how to go about it.
public List<String> getSessions() {
StringBuilder sb = new StringBuilder();
int a = 0;
int b = 0;
String firstHalf = "2017";
String otherHalf = "2018";
List<String> session = new ArrayList<>();
for(int i = 0; i < 13; i++) {
a = Integer.parseInt(firstHalf) + 1;
sb.append(a);
sb.append("/");
for(int j = i; j < 13; j++) {
b = Integer.parseInt(otherHalf) + 1;
sb.append(b);
}
session.add(sb.toString());
}
System.out.println(session);
return session;
}
however it doesn't do the needed, please help me out. thanks
Not sure what you're trying to do, but you can use this to print out values :
List<String> session = new ArrayList<>();
for (int i = 2017; i < 2030; i++) {
session.add(i + "/" + (i + 1) + "\n");
}
System.out.println(session);
You don't need to use a nested loop or even a StringBuilder.
You do not need two for loops. Instead you can do following:
public List<String> getSessions() {
int a = 2017;
int b = 2018;
List<String> session = new ArrayList<>();
while (b <= 2030) {
StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append("/");
sb.append(b);
session.add(sb.toString());
a++;
b++;
}
System.out.println(session);
return session;
}
Hello I can't make this work, I am given a main word followed by another sub words if the word is contained in the main word the part should be deleted.
//Example
//fmrog (in.nextLine)(main word)
//4 (in.nextInt)(the amount of sub words)
//roc(in.nextLine)(not contained)
//gor(in.nextLine)(not contained)
//rog(in.nextLine)(contained)
//ogr(in.nextLine)(not contained)
//result:fm
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder mainWord = new StringBuilder(in.nextLine);
int n = in.nextInt();
StringBuilder MainWord2 = new StringBuilder(mainWord);
in.nextLine();
for (int i = 0; i < n; i++) {
String subWord = in.nextLine();
int chars = subWord.length();
if (chars> mainWord.length()){
continue;
}
for (int j = 0; j < subWord.length(); j++) {
int r = 0;
for (int k = 0; k < mainWord.length(); k++) {
r++;
if (k > MainWord2.length() - 1) {
break;
}
if (MainWord2.charAt(k) == subWord.charAt(j)) {
break;
}
}
if (r <= MainWord2.length() && MainWord2.charAt(r-1) == subWord.charAt(j)) {
MainWord2.deleteCharAt(r - 1);
if (j >= subWord.length() -1 ) {
mainWord = MainWord2;
break;
}
}
if (r > MainWord2.length()) {
MainWord2 = mainWord;
break;
}
}
}
System.out.println(mainWord);
}
}
Honestly I am stucked maybe there is an easier way to solve this. The main thing is that when I write a case like : "super 2 pe surr" At the end at "surr" the two StringBuilders start to act as one when I delete chatAt at one of them the other one changes also
No need to make it so complex.
String input = // complete user input
String[] words = String.split(input);
String mainWord = words[0];
int numWords = Integer.parseInt(words[1]); // this variable isn't needed
for(int i = 2; i < words.length; i++) {
if (mainWord contains words[i]) {
mainWord = mainWord.replace(words[i], ""); // remove subword from mainword
}
}
At the end, mainWord will be the original mainWord without any subwords that were entered later.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
String[] words = new String[n];
for (int i = 0; i <n ; i++) {
words[i] = in.nextLine();
}
String mainWord = words[0];
for (int i = 1; i <words.length ; i++) {
if (mainWord.contains(words[i])){
mainWord = mainWord.replace(words[i], "");
}
}
System.out.println(mainWord);
}
}
Here but the thing is if the letters are not one next to another it doesnt remove the subword.
I'm having trouble in using this code I found on the net. my goal is to count the number of times a letter show and display the letter with the most occurrence and if there are 2 or more letters that occurred at the same number of times then they will both show up.
This is my current output:
Current Output
Here is the code i found on the net and working with:
public void fcount(String str)
{
int[] occurence = new int[255];
// Scanner scanner = new Scanner(System.in);
// str = scanner.nextLine();
// optional to put eveyting in uppercase
str = str.toUpperCase();
// convert to char
char[] digit = str.toCharArray();
// count
for(int i = 0; i < digit.length; i++)
occurence[digit[i]]++;
// find max
int max = 0; // max value
char maxValue = 0; // max index
for(int i = 0; i < occurence.length; i++)
{
// new max ?
if(occurence[i] > max) {
max = occurence[i];
maxValue = (char) i;
}
}
// result
System.out.println("Character used " + max + " times is: " + (char) maxValue);
// return "";
}
And Here is the the loop where i'm using it:
public void calpha()
{
char startUpper = 'A';
String cones = null;
for (int i = 0; i < 12; i++) {
cones = Character.toString(startUpper);
System.out.println(startUpper);
}
fcount(cones);
}
There is an error in you loop:
cones = Character.toString(startUpper);
You are just re-assigning the value of cones, so fcount receives a string containing only the last character.
A solution is
cones += Character.toString(startUpper);
You have an issue in your int[] occurence = new int[255]; statement and usage: occurence[digit[i]]++ may lead to IndexOutOfBoundsException since char type is up to 2^16
Your code can not deal with non-ANSII characters. Mine does.
import java.util.*;
class Problem {
public static void main(String args[]) {
final String input = "I see trees outside of my window.".replace(" ", "");
final List<Character> chars = new ArrayList<>(input.length());
for (final char c : input.toCharArray()) {
chars.add(c);
}
int maxFreq = 0;
final Set<Character> mostFrequentChars = new HashSet<>();
for(final char c : chars) {
final int freq = Collections.frequency(chars, c);
if (freq > maxFreq) {
mostFrequentChars.clear();
mostFrequentChars.add(c);
maxFreq = freq;
}
else {
if (freq == maxFreq) {
mostFrequentChars.add(c);
}
}
}
for (Character c : mostFrequentChars) {
System.out.println(c);
}
}
}
Try this code:
public static void main(String[] args) throws IOException {
char startUpper = 'A';
String cones = "";
for (int i = 0; i < 12; i++) {
cones += Character.toString(startUpper);
System.out.println(startUpper);
}
fcount(cones);
}
public static void fcount(String str) {
HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
HashSet<Character> letters = new HashSet<Character>();
str = str.toUpperCase();
//Assume that string str minimium has 1 char
int max = 1;
for (int i = 0; i < str.length(); i++) {
int newValue = 1;
if (hashMap.containsKey(str.charAt(i))) {
newValue = hashMap.get(str.charAt(i)) + 1;
hashMap.put(str.charAt(i), newValue);
if (newValue>=max) {
max = newValue;
letters.add(str.charAt(i));
}
} else {
hashMap.put(str.charAt(i), newValue);
}
}
System.out.println("Character used " + max + " times is: " + Arrays.toString(letters.toArray()));
// return "";
}
I am looking for an implementation of the following:
I have a string: 001001001
And I need to receive at the output: 001 001 001
I checked the formatNumber and DecimalFormat - they can not provide such kind of output.
Is there any other built-in methods?
Currently I created some server-side function (that is actually not so brilliant solution I think):
StringBuffer result = new StringBuffer("");
for (int i = 1; i <= 9; i++) {
result.append(input.charAt(i - 1));
if (i % 3 == 0)
result.append(" ");
}
return result.toString();
I use the method below.
Does not add extra space at the end like in the example from nKognito.
public static String format(String inputUnformatted, int groupSize, String separator) {
StringBuilder result = new StringBuilder(inputUnformatted);
int i = groupSize;
while (i < inputUnformatted.length()) {
result.insert(inputUnformatted.length() - i, separator);
i += groupSize;
}
return result.toString();
}
public static void main(String[] args) {
String input = "001001001";
StringBuilder result = new StringBuilder();
int j = 0;
for (int i = 0; i < input.length(); i++) {
if (j > 2) {
result.append(" ");
j = 0;
}
result.append(input.charAt(i));
j++;
}
System.out.println(result.toString());
}
try this piece of code
Given a string how can i figure out the number of times each char in a string repeats itself
ex: aaaabbaaDD
output: 4a2b2a2D
public static void Calc() {
Input();
int count = 1;
String compressed = "";
for (int i = 0; i < input.length(); i++) {
if (lastChar == input.charAt(i)) {
count++;
compressed += Integer.toString(count) + input.charAt(i);
}
else {
lastChar = input.charAt(i);
count = 1;
}
}
System.out.println(compressed);
}
What you'r looking for is "Run-length encoding". Here is the working code to do that;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RunLengthEncoding {
public static String encode(String source) {
StringBuffer dest = new StringBuffer();
// iterate through input string
// Iterate the string N no.of.times where N is size of the string to find run length for each character
for (int i = 0; i < source.length(); i++) {
// By default run Length for all character is one
int runLength = 1;
// Loop condition will break when it finds next character is different from previous character.
while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
runLength++;
i++;
}
dest.append(runLength);
dest.append(source.charAt(i));
}
return dest.toString();
}
public static String decode(String source) {
StringBuffer dest = new StringBuffer();
Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
int number = Integer.parseInt(matcher.group());
matcher.find();
while (number-- != 0) {
dest.append(matcher.group());
}
}
return dest.toString();
}
public static void main(String[] args) {
String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
System.out.println(encode(example));
System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B"));
}
}
This program first finds the unique characters or numbers in a string. It will then check the frequency of occurance.
This program considers capital and small case as different characters. You can modify it if required by using ignorecase method.
import java.io.*;
public class RunLength {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
System.out.println("Please enter the string");
String str = br.readLine();//the input string is in str
calculateFrequency(str);
}
private static void calculateFrequency(String str) {
int length = str.length();
String characters[] = new String[length];//to store all unique characters in string
int frequency[] = new int[length];//to store the frequency of the characters
for (int i = 0; i < length; i++) {
characters[i] = null;
frequency[i] = 0;
}
//To get unique characters
char temp;
String temporary;
int uniqueCount = 0;
for (int i = 0; i < length; i++) {
int flag = 0;
temp = str.charAt(i);
temporary = "" + temp;
for (int j = 0; j < length; j++) {
if (characters[j] != null && characters[j].equals(temporary)) {
flag = 1;
break;
}
}
if (flag == 0) {
characters[uniqueCount] = temporary;
uniqueCount++;
}
}
// To get the frequency of the characters
for(int i=0;i<length;i++){
temp=str.charAt(i);
temporary = ""+temp;
for(int j=0;i<characters.length;j++){
if(characters[j].equals(temporary)){
frequency[j]++;
break;
}
}
}
// To display the output
for (int i = 0; i < length; i++) {
if (characters[i] != null) {
System.out.println(characters[i]+" "+frequency[i]);
}
}
}}
Some hints: In your code sample you also need to reset count to 0 when the run ends (when you update lastChar). And you need to output the final run (after the loop is done). And you need some kind of else or continue between the two cases.
#Balarmurugan k's solution is better - but just by improving upon your code I came up with this -
String input = "aaaabbaaDD";
int count = 0;
char lastChar = 0;
int inputSize = input.length();
String output = "";
for (int i = 0; i < inputSize; i++) {
if (i == 0) {
lastChar = input.charAt(i);
count++;
} else {
if (lastChar == input.charAt(i)) {
count++;
} else {
output = output + count + "" + lastChar;
count = 1;
lastChar = input.charAt(i);
}
}
}
output = output + count + "" + lastChar;
System.out.println(output);