Checking characters in a string - java

I want to wrote a program which checks every character in a string. If the two characters are same in a row I want to increase count by 1. The program should scan all the characters and give us a value. T is for deciding how many String's we will enter.
For example: (input)
5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB
Ouput
3
4
0
0
4
But I get 0
3
4
0
0
Could you help? What I have done wrong?
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution
{
public static void main(String[] args)
{
int i,T,j,count;
String S;
char K;
count = 0;
Scanner scan = new Scanner(System.in);
T = scan.nextInt();
for (i = 0; i <= T - 1; i++)
{
count = 0;
S = scan.nextLine();
char[] list = new char[S.length()];
for(j = 0; j <= S.length() - 1; j++)
{
list[j] = S.charAt(j);
}
for(j = 1; j <= S.length() - 1; j++)
{
if(list[j - 1] == list[j])
{
count++;
}
}
System.out.println(count);
}
}
}

I think something like the below should help you out, It first requires a number of strings that will be entered and then in the entered string will count the number of times a character is the same as the previous character. It wont take a series of strings though, it will do them one by one, see the example output below:
public static void main(String[] args){
int numInput;
String inputString;
Scanner scanner = new Scanner(System.in);
numInput = scanner.nextInt();
for(int y = 0; y < numInput;y++){
inputString = scanner.next();
char[] chars = inputString.toCharArray();
int counter = 0;
char curr;
for(int x = 0; x < chars.length;x++){
curr = chars[x];
if(x>0){
if(chars[x-1] == curr){
counter++;
}
}
}
System.out.println("Count for string " + inputString + " was " + counter);
}
scanner.close();
}
Testing:
5
AASAAB
Count for string AASAAB was 2
AAAAAA
Count for string AAAAAA was 5
AAVAAD
Count for string AAVAAD was 2
MOOMOO
Count for string MOOMOO was 2
MAAAAAA
Count for string MAAAAAA was 5

Try this...
public static void main(String[] args) {
int i, T, j, count;
String S;
char K;
count = 0;
Scanner scan = new Scanner(System.in);
T = scan.nextInt();
for (i = 0; i <= T - 1; i++) {
scan = new Scanner(System.in);
count = 0;
S = scan.nextLine();
char[] list = new char[S.length()];
for (j = 0; j <= S.length() - 1; j++) {
list[j] = S.charAt(j);
}
for (j = 1; j <= S.length() - 1; j++) {
if (list[j - 1] == list[j]) {
count++;
}
}
System.out.println(count);
}
}

Related

Sorting empty and word array in java

I want to write a code which can sort char array element. But the problem is where i want to sort 'a' before 'aa' element and I don't know how to write this part. It always sort 'aa' before 'a'. At first it get inputs from user and if we write '0' it will print sorted array.
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int i, num = 0;
char[][] arr = new char[1000][1000];
char[] index = new char[1000];
Scanner myObj = new Scanner(System.in);
for(i = 0; i < 1000; i++){
arr[i] = myObj.next().toCharArray();
if(arr[i][0] == '0'){
break;
}
else{
num++;
}
for(int j = 0; j < i; j++){
if(arr[i][0] < arr[j][0]){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
for(i = 0; i < num; i++){
System.out.println(arr[i]);
}
}
}
You have to consider that 'aa' is not a char, instead 'a' is a char.
If you want to sort strings the code is nearly okay.
Here an example:
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int num = 0;
String[] arr = new String[1000];
String index = "";
Scanner myObj = new Scanner(System.in);
for(int i = 0; i < 1000; i++){
arr[i] = myObj.nextLine();
if(arr[i].equals("0")){
break;
}
else{
num++;
}
for(int j = 0; j < i; j++){
if(arr[i].compareTo(arr[j]) < 0){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
System.out.print("[ ");
for(int i = 0; i < num; i++){
System.out.print(arr[i] + " ");
}
System.out.println("]");
}
}
Input:
aaaaaaaa
aaaaaaa
aaaaaa
aaaaa
aaaa
aaa
aa
a
0
Expected Output:
[ a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa ]
It is only sorting by the first char of an entered word.
Thus it seems like the input-order is preserved.
Issue
Adding some debug-prints shows the comparison of first-char is leading to incorrect or unwanted aa before a case:
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int i, num = 0;
char[][] arr = new char[1000][1000];
char[] index = new char[1000];
Scanner myObj = new Scanner(System.in);
for(i = 0; i < 1000; i++){
arr[i] = myObj.next().toCharArray();
if(arr[i][0] == '0'){
break;
}
else{
num++;
}
System.out.printf("Debug [%d]: '%s' \n", i, String.valueOf(arr[i]));
for(int j = 0; j < i; j++){
System.out.printf("Compare '%s' < '%s' = %s\n", arr[i][0], arr[j][0], (arr[i][0] < arr[j][0]));
if(arr[i][0] < arr[j][0]){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
for(i = 0; i < num; i++){
System.out.println(arr[i]);
}
}
}
Output:
a
Debug [0]: 'a'
aa
Debug [1]: 'aa'
Compare 'a' < 'a' = false
0
a
aa
Refactored and solved
I just added a bit output to interact with user.
Also refactored a bit (extract into methods, and control length of arrays with a configurable constant).
import java.util.Scanner;
public class First {
private static final int LENGTH = 10;
private static final Scanner myObj = new Scanner(System.in);
public static void main(String[] args) {
char[][] arr = new char[LENGTH][LENGTH];
System.out.println("Enter elements (each on a new line, 0 stops):");
int num = readArray(0, arr);
System.out.printf("Printing %d elements:\n", num);
printArray(num, arr);
}
private static int readArray(int num, char[][] arr) {
char[] index;
int i;
for (i = 0; i < LENGTH; i++) {
arr[i] = readChars();
if (arr[i][0] == '0') {
break;
} else {
num++;
}
for (int j = 0; j < i; j++) {
if (String.valueOf(arr[i]).compareTo(String.valueOf(arr[j])) < 0) { // entire array compared (chars in sequence) instead only: arr[i][0] < arr[j][0]
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
return num;
}
private static void printArray(int num, char[][] arr) {
int i;
for (i = 0; i < num; i++) {
System.out.println(arr[i]);
}
}
private static char[] readChars() {
return myObj.next().toCharArray();
}
}
Output is as expected (a before aa):
Enter elements (each on a new line, 0 stops):
z
aa
b
a
0
Printing 4 elements:
a
aa
b
z
How it works
Entire array compared (chars in sequence) instead only the first char of each array.
before:
arr[i][0] < arr[j][0]
after:
String.valueOf(arr[i]).compareTo(String.valueOf(arr[j])) < 0
Bonus Tip: Naming can help to spot logical bugs
When renaming the methods and variable names it may get a bit clearer what the program does, we call it semantics:
myObj becomes scanner
i becomes index or wordIndex or lineIndex and lastLineIndex
j is actually a character-index ... but in this short scope it should can be self-evident
char-arrays can be lines or words
num becomes length of lines or countLines
and all the method-names are adjusted in semantics to operate on lines, expressed by name <verb>Lines
import java.util.Scanner;
public class First {
private static final int LENGTH = 10;
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
char[][] lines = new char[LENGTH][LENGTH];
System.out.println("Enter elements (each on a new line, 0 stops):");
int countLines = readLines(lines);
System.out.printf("Printing %d elements:\n", countLines);
printLines(lines, countLines);
}
private static int readLines(char[][] lines) {
int linesRead = 0;
for (int lineIndex = 0; lineIndex < LENGTH; lineIndex++) {
lines[lineIndex] = readLine();
if (lines[lineIndex][0] == '0') {
break;
} else {
linesRead++;
}
sortLines(lines, lineIndex);
}
return linesRead;
}
private static void sortLines(char[][] lines, int lastLineIndex) {
for (int j = 0; j < lastLineIndex; j++) {
if (String.valueOf(lines[lastLineIndex]).compareTo(String.valueOf(lines[j])) < 0) { // entire array compared (chars in sequence) instead only: arr[i][0] < arr[j][0]
char[] line = lines[lastLineIndex];
lines[lastLineIndex] = lines[j];
lines[j] = line;
j = 0;
}
}
}
private static void printLines(char[][] lines, int length) {
for (int i = 0; i < length; i++) {
System.out.println(lines[i]);
}
}
private static char[] readLine() {
return scanner.next().toCharArray();
}
}

How can I print a simple multiline numeric pattern opposite of how it is emitted now?

This is the output of the following code:
1
23
345
4567
But I want the output to be in the opposite direction like this.
Not sure how to achieve that.
1
23
345
4567
Code:
import java.util.Scanner;
public class numPattern1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = 1;
while (i <= n) {
int space = n - i + 1;
while (space <= n) {
System.out.print(" ");
space++;
}
int j = 1;
int p = i;
while (j <= i) {
System.out.print(p);
p++;
j++;
}
System.out.println();
i++;
}
}
}
For each line, there are two spaces times the length of the longest line minus the current line number. Then, you count from the current line number one plus the current line number values. Like,
int len = (n / 2) + 1;
for (int i = 0; i < len; i++) {
for (int j = 0; j < 2 * (len - i - 1); j++) {
System.out.print(' ');
}
for (int j = 0; j <= i; j++) {
System.out.print(j + i + 1);
}
System.out.println();
}
Outputs (as requested)
1
23
345
4567
Here it is:
public class numPattern1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = 1;
int k = 0;
while (i <= n) {
int space = 2*n - i - k ;
k++;
int l=0;
while (l <= space) {
System.out.print(" ");
l++;
}
int j = 1;
int p = i;
while (j <= i) {
System.out.print(p);
p++;
j++;
}
System.out.println();
i++;
}
}

How to print results of matched numbers with a space

Just thought of a simple program to practice java coding and am stuck at the end part.,..
the code prints out the required answer (what numbers match from input compared to results for a 5 number lottery) but the answer is printed without spaces. I thought perhaps to add a "" when += to matchingNumbers but that didnt do anything!
import java.util.Scanner;
import java.util.Arrays;
public class LottoChecker
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int [] yourNumbers = new int [5];
int yourInput, resultsInput;
int [] results = new int [5];
int currentNumber = 0;
String matchingNumbers = "";
for (int i=0; i<yourNumbers.length; i++)
{
System.out.println ("Enter your main numbers: " );
yourInput = in.nextInt();
yourNumbers[i]=yourInput;
}
for (int j=0; j<results.length; j++)
{
System.out.println("Enter the results from the main numbers: ");
resultsInput = in.nextInt();
results[j] = resultsInput;
}
System.out.println("Your Numbers: " +
Arrays.toString(bubbleSort(yourNumbers)));
System.out.println("The Results are: " +
Arrays.toString(results));
for (int i =0; i<yourNumbers.length;i++)
{
currentNumber = yourNumbers[i];
for (int j=0;j<results.length;j++)
if (currentNumber == results[j])
matchingNumbers += currentNumber + "";
}
System.out.println("Your matching numbers are: " +
matchingNumbers);
}
public static int [] bubbleSort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
return arr;
}
}
An elegant solution would be using StringJoiner(" ") and then add the numbers on each iteration.

line 21 show ; expected

The first line contains a single integer p denoting the length of array. The second line contains space-separated integers describing each respective element in array. The third line prints an integer indicating the number of negative arrays.
package asgn3;
import java.util.*;
public class Asgn3 {
public static void main(String[] args) {
int count = 0, result = 0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the array ");
String s = in.nextLine();
int j = 0;
String[] s1 = s.split(" ");
int a[] = new int[s1.length];
for(String s2:s1) {
a[j] = Integer.parseInt(s2));
j++;
}
for (int i = 0; i < a.length; i++) {
for ( j = i; j < a.length; j ++) {
for (int k = i; k <= j; k++) {
result += a[k];
}
if(result < 0)
count ++;
}
System.out.println("no. of negatve arrays is "+count);
}
}
}
The issues is usage of extra unnecessary parenthesis. Change,
a[j]=Integer.parseInt(s2));
with
a[j]=Integer.parseInt(s2);
Remove extra bracket ) from end of line
a[j] = Integer.parseInt(s2);

java print text with square/frame of *

I am trying to figure out how to print text wrapped with a 80x80 square of *.
My code so far:
Scanner scanner = new Scanner(System.in);
String text = scanner.next();
int square = 80;
if(square > 0){
for(int i = 0; i<square; i++){
for(int j = 0; j<square; j++){
if(i == 0 || j == 0 || i == square-1 || j == square-1)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
However I cant figure out how to put the text in the square, any ideas? The frame/square must always be 80x80 *'s even if the text is longer.
Try this. Split the input into a character array and print each one.
Scanner scanner = new Scanner(System.in);
String text = scanner.next();
char[] characters = text.toCharArray(); //create character array of letters
int square = 80; //length of box
if (square > 0) {
int index = 0;
for (int i = 0; i < square; i++) {
for (int j = 0; j < square; j++) {
if (i == 0 || j == 0 || i == square - 1 || j == square - 1)
System.out.print("*");
else {
if (index < characters.length && index < square * square) //if index in bounds
System.out.print(characters[index++]); //print next letter
else {
System.out.print(" "); //else whitespace
}
}
}
System.out.println();
}
}
Alternative approach. More lines of code, but less convulted imho.
static int frameSize = 80;
public static void printTopOrBottom() {
char[] topAndBot = new char[frameSize];
Arrays.fill(topAndBot, '*');
System.out.println(topAndBot);
}
public static char[] createLine() {
char[] tmpArr = new char[frameSize];
Arrays.fill(tmpArr, ' ');
tmpArr[0] = '*';
tmpArr[frameSize-1] = '*';
return tmpArr;
}
public static char[] getInputText() {
char[] lotsOfText = new char[ (int)(Math.random() * (160*160))];
Arrays.fill(lotsOfText, 'r');
return lotsOfText;
}
public static void main(String[] args) {
char[] input = getInputText();
ArrayList<char[]> lines = new ArrayList<char[]>();
int lettersPrinted = 0;
for(int i = 1; i < (frameSize-1); i++) {
char[] tmpArr = createLine();
// find out how many letters on line i, - max 78, but less if no input text left.
int lettersToPrint = Math.min((input.length - lettersPrinted), (frameSize-2));
// if any?
if(lettersToPrint > 0) {
System.arraycopy(input, lettersPrinted, tmpArr, 1, lettersToPrint);
}
lettersPrinted += lettersToPrint;
// add line
lines.add(tmpArr);
}
printTopOrBottom();
for(char[] line : lines) {
System.out.println(line);
}
printTopOrBottom();
}
Here's another one, using printf. Its 3 times faster than the choosen answer.
public static void main(String[] args) {
long start = System.currentTimeMillis();
int intSquare = 80;
int textLength = intSquare - 2;
String square = String.valueOf(textLength);
String textLine = "Tess is very beautiful. Tess is very beautiful. Tess is very beautiful. Tess is very beautiful. Tess is very beautiful. ";
String toPrint = null;
for (int i = 0; i < intSquare; i++) {
System.out.print("*");
}
System.out.println();
for (int i = 0; i < textLength; i++) {
toPrint = textLine.length() > textLength ? textLine.substring(0, textLength) : textLine;
textLine = toPrint.length() == textLength ? textLine.substring(textLength) : "";
System.out.printf("*%-" + square + "s*\n", toPrint);
}
for (int i = 0; i < intSquare; i++) {
System.out.print("*");
}
long end = System.currentTimeMillis();
System.out.println();
System.out.println(end - start);
}

Categories