I have to write a code as a task for my university and we have to recreate Minesweeper with java and it has to be runned in the command line.
For the matchfield we have to make an array that looks in the end like this picture:
Example how it sould look in the end
And to choose the field we have to use the scanner.
For example if you want to chose field C3, you have to type into the scanner C3.
At the moment im struggleing a little bit with the field.
I had 2 ideas but both didn't work out very well.
in the first try i tried to create everything with 2 for loops and 1 array but my problem was that I couldn't add 2 charrs, so I had the chars 0 to 9 and the charrs A to J.
In the second try I created 3 array, one with the numbers 0 to 9 and anothe array A to J and in the third array i wanted to combine both arrays. And now I'm wondering if this it's possible if I can acctually combine them in the way I want and if it's possible could somebody give me some help?
import java.util.Scanner;
import java.util.Arrays;
public class Minesweeper {
public static void main (String[] args) {
char c = 'A';
char d = '0';
char e = '9';
char f = 'J';
char[][] feldz = new char[11][11];
char[][] feldb = new char[11][11];
char[][] feld = new char[11][11];
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (i == 0 && j == 0) {
feldz[i][j] = ' ';
System.out.print(feldz[i][j] + " |");
}
if (d > e) {
d = '0';
}
if (d <= e && i > 0){
feldz[i][j] = d;
System.out.print(feldz[i][j] + " |");
}
if (i > 0 && j == 10) {
d++;
}
}
System.out.println("");
}
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (i == 0 && j == 0) {
feldb[i][j] = ' ';
System.out.print(feldb[i][j] + " |");
}
if (i > 0 && j == 0){
feldb[i][j] = ' ';
System.out.print(feldb[i][j] + " |");
}
if (c > f) {
c = 'A';
}
if(c <= f && j > 0){
feldb[i][j] = c;
System.out.print(feldb[i][j] + " |");
c++;
}
if (j == 10){
System.out.println("");
}
}
}
}
}
You don't actually need array to print the maze , nested loops is enough for that. 2d Array is only required to store the input. Please try the below code:
int size = 10;
int [][] maze = new int[size][size];
while (true){
System.out.print(' ');
for (int i = 0; i < size; i++) {
System.out.print('|');
System.out.print((char) ('A' + i));
}
for (int i = 0; i < size; i++) {
System.out.println("");
System.out.print(i);
for (int j = 0; j < size; j++) {
System.out.print('|');
if(maze[i][j] > 0) {
System.out.print(maze[i][j]);
} else {
System.out.print(' ');
}
}
}
int row = -1;
int col = -1;
System.out.println("\nEnter CoOrdinates");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if(input.length() == 2) {
char charAt = input.charAt(0);
if(charAt >= 'A' && charAt <= 'A'+size-1) {
col = charAt-'A';
}
charAt = input.charAt(1);
if(charAt >= '0' && charAt <= '0'+size-1) {
row = charAt-'0';
}
if(row != -1 && col != -1) {
System.out.println("Enter Action");
input = scanner.nextLine();
int action = Integer.parseInt(input);
maze[row][col] = action;
} else {
System.out.println("Incorrect Input");
}
}
}
Count the number of times aaa appears in a string, 1. without repetition and 2. when repetition is allowed. I tried the following code which works well for 1st case but does'nt work well for the second case.
public static void main(String[] args) {
String str="cbaadaaabefaaaag";
int count=0,count1=0;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='a' && str.charAt(i+1)=='a' && str.charAt(i+2)=='a')
{
count++;
}
}
System.out.println(count);
for(int i=0;i<str.length();i++)
{
if(i==0)
{
if(str.charAt(i)=='a' && str.charAt(i+1)=='a' && str.charAt(i+2)=='a')
{
count1++;
}
}
else
{
if(str.charAt(i-1)=='a' && str.charAt(i)=='a' && str.charAt(i+1)=='a')
{
count1++;
}
}
}
System.out.println(count1);
}
The input I tried is cbaadaaabefaaaag which should give 3 for 1st case and 2 for 2nd case, also when the input is aaaa it should be 1 for 1st case and 2 for overlaping case.
This code should help you:
public static void main(String args[]) throws Exception {
String str = "cbaadaaabefaaaaaaag";
System.out.println(count(str, true));
System.out.println(count(str, false));
}
public static int count(String str, boolean overlap) {
int count = 0;
for (int i = 0; i < str.length() - 2; i++) {
if (str.charAt(i) == 'a' && str.charAt(i + 1) == 'a'
&& str.charAt(i + 2) == 'a') {
if (!overlap) {
i += 2;
}
count++;
}
}
return count;
}
The condition i < str.length() - 2 ensures that you do not get a StringIndexOutOfBoundsException, because if there are only two characters left in the string, there cannot be anther substring aaa.
The overlap condition adds two to the current index, where a substring aaa was found, so your index points to the next character after the last found sequence aaa, which prevents overlapping.
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String str = scn.nextLine();
int count = 0, count1 = 0;
for (int i = 0; i < str.length() - 2; i++) {
if (str.charAt(i) == 'a' && str.charAt(i + 1) == 'a' && str.charAt(i + 2) == 'a') {
count++;
}
}
System.out.println(count);
for (int i = 0; i <= str.length() -1; i++) {
if (str.charAt(i) == 'a' && str.charAt(i + 1) == 'a' && str.charAt(i + 2) == 'a') {
i += 2;
count1++;
}
}
System.out.println(count1);
}
I need to find the first match in this task. Probably i am just missing something. As you can see, i found the last match.I am not copied the first half of the code. Thank you.
for (int i = 0; i <= n - 1; i++) {
if (iv[i] == a) {
hely = i;
}
}
if (hely == -1) {
System.out.println("text");
} else {
System.out.println("text " + a + " text " + (hely + 1) + "text");
}
break the loop when you find first match.
for (int i = 0; i <= n - 1; i++) {
if (iv[i] == a) {
hely = i;
break;
}
}
You need to exit the for loop after finding the first match:
for (int i = 0; i <= n - 1; i++) {
if (iv[i] == a) {
hely = i;
break;
}
}
Solving this problem from codingBat
Given a string, return the length of the largest "block" in the
string. A block is a run of adjacent chars that are the same.
maxBlock("hoopla") → 2
maxBlock("abbCCCddBBBxx") → 3
maxBlock("") → 0
I was trying to solve it using one for loop as below:
public int maxBlock(String str) {
int maxCounter=1;
int counter=1;
if(str.length()==0)
{
return 0;
}
for(int i=0;i<str.length()-1;i++)
{
if(str.substring(i,i+1).equals(str.substring(i+1,i+2)))
{
counter++;
}
if(counter>maxCounter)
{
maxCounter=counter;
counter=0;
}
}
return maxCounter;
}
It beats all the cases apart from one. Can anybody show a solution with one for loop?
Sorry for mentioning late but you can't use REGEX or anything from collections framework.
I think you get it wrong in certain edge cases:
public int yourMaxBlock(String str) {
int maxCounter = 1;
int counter = 1;
if (str.length() == 0) {
return 0;
}
for (int i = 0; i < str.length() - 1; i++) {
if (str.substring(i, i + 1).equals(str.substring(i + 1, i + 2))) {
counter++;
}
if (counter > maxCounter) {
maxCounter = counter;
counter = 0;
}
}
return maxCounter;
}
public int myMaxBlock(String str) {
int maxCounter = 1;
int counter = 1;
if (str.isEmpty()) {
return 0;
}
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i - 1) == str.charAt(i)) {
if (++counter > maxCounter) {
maxCounter = counter;
}
} else {
counter = 1;
}
}
return maxCounter;
}
public void test() {
String[] tests = new String[]{
"", "+", "++", "+++,++,++,+", "+,++,+++,++,", "+,++,+++,++++", "+++++,++,+++,++++"
};
for (String s : tests) {
int myMax = myMaxBlock(s);
int yourMax = yourMaxBlock(s);
System.out.println("myMaxBlock(" + s + ") = " + myMax + (myMax != yourMax ? " WRONG! you have " + yourMax : ""));
}
}
prints
myMaxBlock() = 0
myMaxBlock(+) = 1
myMaxBlock(++) = 2
myMaxBlock(+++,++,++,+) = 3
myMaxBlock(+,++,+++,++,) = 3
myMaxBlock(+,++,+++,++++) = 4 WRONG! you have 3
myMaxBlock(+++++,++,+++,++++) = 5 WRONG! you have 4
You can use a Pattern matcher "(.)(\\1)*" that look for repeated char in the String , Here is the code :
public int maxBlock(String str) {
Pattern pattern = Pattern.compile("(.)(\\1)*");
Matcher matcher = pattern.matcher(str);
int max = 0;
while (matcher.find()) {
max = Math.max(max, matcher.group().length());
}
return max;
}
I'm a little late to the party, but here's my CodingBat solution:
public int maxBlock(String str) {
int max = 0;
int count = 1;
char o = ' ';
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == o) {
count++;
if (count > max) { max = count; }
} else {
count = 1;
if (count > max) { max = count; }
}
o = c;
}
return max;
}
Here's a solution based loosely on yours. Note the use of charAt for a neater looking code example.
This starts at the second character of the string and looks backwards to see if we are still encountering the same character. If so, the counter increases. When we finish a string of identical chars, we compare against the max length found thus far and update if necessary.
public static int maxBlock(String str) {
int maxCounter = 1;
int counter = 1;
if (str.length() == 0) {
return 0;
}
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i - 1) == str.charAt(i)) {
counter++;
} else {
// end of a run
if (counter > maxCounter) {
maxCounter = counter;
}
counter = 1;
}
}
return Math.max(maxCounter, counter);
}
Just use one for loop. I think here is another way.
public int maxBlock(String str) {
int len = str.length();
int temp=(len>0)?1:0;
int r =0;
for(int i=1; i<len; i++){
if(str.charAt(i) == str.charAt(i-1)){
temp++;
}
else{
r = (temp>r)?temp:r;
temp=1;
}
}
r = (temp>r)?temp:r;
return r;
}
public int maxBlock(String str) {
int max = 0;
for(int i = 0 ; i < str.length() ; i ++ ) {
char compareChar = str.charAt(i);
int count = 0;
while (i + 1 < str.length()
&& compareChar == str.charAt(i+1)) {
i++;
count ++;
}
if (max < count + 1) {
max = count + 1;
}
}
return max;
}
Here's my solution. It's simpler than you think.
public int maxBlock(String str)
{
//create a counter to return
int counter = 0;
//create a temporary variable to store a running total.
int temp = 1;
//Start on the first character and test to see if the second
//character equals the first.
for (int i = 1; i < str.length(); i++)
{
//If it does, we increment the temp variable.
if (str.charAt(i) == str.charAt(i-1))
{
temp++;
}
//If it doesn't, we wipe the temp variable and start from one.
else
{
temp = 1;
}
//If the temporary variable exceeds the counter amount, we make
//the counter variable equal to the temp variable.
if (temp > counter)
{
counter = temp;
}
}
//Return the counter.
return counter;
}
public int maxBlock(String str) {
int maxLength = 0;
Map<String,Integer> map = new HashMap<String,Integer>();
for(int i = 0; i< str.length(); i++){
String key = str.substring(i,i+1);
if(i!=0 && str.charAt(i) == str.charAt(i-1) && map.containsKey(key)){
map.put(key, map.get(key)+1);
}
else{
map.put(key,1);
}
}
for(Map.Entry<String,Integer> entry : map.entrySet()){
if(maxLength <entry.getValue()){
maxLength = entry.getValue();
}
}
return maxLength;
}
public int maxBlock(String str) {
int count = 0;
int i = 0;
int maxcount = 0;
if (str.length() == 0) return 0;
while (i < str.length() - 1) {
if (str.charAt(i) == str.charAt(i + 1)) {
count++;
if (count > maxcount) {
maxcount = count;
}
} else count = 0;
i++;
}
return maxcount + 1;
}
public int maxBlock(String str) {
int tcount = 0;
if (str.length() < 1) {
return 0;
}
for (int i = 0; i < str.length(); i++) {
int count = 0;
for (int j = i; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
count++;
} else
break;
}
if (count > tcount) {
tcount = count;
}
i += count - 1;
}
return tcount;
}
this is easier it totally works.
int i = 0;
int j = 0;
while(i < inner.length && j < outer.length) {
if(inner[i] > outer[j]) {
j++;
} else if(inner[i] < outer[j]) {
return false;
} else {
i++;
}
}
if(i != inner.length)
return false;
return true;
}
Here My code for this
public int maxBlock(String str) {
int count = 1;
for(int i=0;i<str.length()-1;i++){
int count2 = 0;
if(str.substring(i,i+1).equals(str.substring(i+1,i+2) )){
for(int j = i ; j < str.length();j++){
if(str.substring(i,i+1).equals(str.substring(j,j+1))){
++count2;
}
else{
break;
}
}
}
if(count2 > count){
count = count2;
}
}
if(str.isEmpty())return 0;
return count;
}
// I have a program where I am supposed to count unique characters, only letters and numbers and don't count repeating numbers or letters. However, I have a problem finding out a way for the program not to count spaces and symbols such as "!" "#" "#" "$". So If i type in Hello! I only want the program to say "4", but it says "5" because it counts the exclamation point. Here is my code so far:
public static int countUniqueCharacters(String text1) {
int count = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.substring(0, i).contains(text1.charAt(i) + ""))
System.out.println();
else
count++;
}
return count;
}
In your else block add a condition that the count will be incremented only if the given character is a letter or a digit.
if (Character.isLetter(text1.charAt(i)) || Character.isDigit(text1.charAt(i))) {
count++;
}
In your example:
public static int countUniqueCharacters(String text1) {
int count = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.substring(0, i).contains(text1.charAt(i) + "")) {
System.out.println();
} else if (Character.isLetter(text1.charAt(i)) || Character.isDigit(text1.charAt(i))) {
count++;
}
}
return count;
}
here's a sample code written in C# try and understand it. It compares with ascii and adds in a list
string input = Console.ReadLine();//input
List<char> CountedCharacters = new List<char>();
for (int i = 0; i < input.Length; i++)
{ //checking for numerics //checking for alphabets uppercase //checking for alphabets lowercase
if ((input[i] >= 45 && input[i] <= 57) || (input[i] >= 65 && input[i] <= 90) || (input[i] >= 97 && input[i] <= 122))
{
bool AlreadyExists = false;
for (int j = 0; j < CountedCharacters.Count; j++)
{
////checking if already exists
if (CountedCharacters[j]==input[i])
{
AlreadyExists = true;
break;
}
}
////adding in list if doesnt exists
if (!AlreadyExists)
{
CountedCharacters.Add(input[i]);
}
}
}
for (int i = 0; i < CountedCharacters.Count; i++)
{
Console.WriteLine(CountedCharacters[i]);
}
Try this one using regex. You can add and remove the characters you need from the expression to count what you need.
public static int countUniqueCharacters(String text1) {
String newText = text1.replaceAll("[^A-Za-z0-9()\\[\\]]", "");
Set<Character> tempSet = new HashSet<>();
for (char item : newText.toCharArray()) {
tempSet.add(item);
}
return tempSet.size();
}