java, code which counts when at certain char from large string input - java

my question is if i have a string- with two types of chars in the string '#' and '.' and I want to count how many times I land on '#' if each time I move to the right 3 and down one.
for example the given string would look like the following:
...#.#.......##....#.......#...
.#....#.##.#..#.......#.....##.
#..#...##.####..###.....#......
..#...##...#...#.#......#...#.#
.##.##.#...#.....#.##..##......
.#...#.#.##.###..#...#...#.....
.#..##..#....##.##....##....##.
..#...##....#..###........##...
.#..#..#.#....#.#...#.#......#.
.##.....#...#..#..#..#...###...
.#...#....#..#...........###...
.....#...........##.#......#...
.....#....##......##..#.#......
-1//stops the checking
what should happen is the following, 0 means landed on a . and X means it landed on # which is when count should go up by one each time this happens:
...#.#.......##....#.......#...
.#.o..#.##.#..#.......#.....##.
#..#..0##.####..###.....#......
..#...##.0.#...#.#......#...#.#
.##.##.#...#0....#.##..##......
.#...#.#.##.###0.#...#...#.....
.#..##..#....##.##0...##....##.
..#...##....#..###...o....##...
.#..#..#.#....#.#...#.#.0....#.
.##.....#...#..#..#..#...##X...
.#...#....#..#...........###..0//notice here next round it will exceed
.....#...........##.#......#.....0..#...........##.#......#...//line get doubled as if returning to beginning of the
.....#....##......##..#.#...........X....##......##..#.#......//same here
-1//to stop
so at the start, I move to the third index and down 1 which is to the next row and I check if that char is '#' if yes count++
so in this example- it moves three so the first row moves to ... then goes down to the next row which will be index 3 which in this case is .#. so the third is. and so on. and if it landed on # count++.
here's my code but it doesn't seem to work-
public static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
String a = "";//starts empty
int cnt = 0, b = 0;//cnt++ if '#', b helps us move 3 to the right each time
a = reader.nextLine(); //gets the string
if (b + 3 > a.length() - 1) {//checks that the length when moving 3 doesn't exceed string length
b = 0;// if it does exceed then go all the way to the left of the string
}
b += 3;//move right 3
a = reader.nextLine(); //get next line from the input
while (a != "-1") {//until there is -1 (to stop getting input) it continues to check
char c = a.charAt(b -
1);//takes whats at place b(-1 is because first index is 0 and not1) and note this is three to the right and after it moves down a row!// is line 23
if (c == '#' && a != "") {//checks if string isn't empty and if the char equals #
cnt++;//if yes count++
}
if (b + 3 > a.length() - 1) {//explained above
b = 0;
}
b += 3;
a = reader.nextLine();
}
System.out.println(cnt);
}
errors I get is the following:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 26
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
at java.base/java.lang.String.charAt(String.java:702)
at q.qq.main(Advent3.java:23)
help would be appreciated. let me know if something isn't clear or even how to improve:) thanks
code after talking in chat and trying to improve:
public class Advent3 {
public static Scanner reader= new Scanner(System.in);
public static void main(String[] args){
int b=4,cnt=0,line=1,s;
String str="";
char charsign;
str=reader.nextLine();
s=str.length();
str=reader.nextLine();
while(str!=""||str!="-1") {
line++;
s=str.length();
if(b%str.length()==0) {
charsign= str.charAt(10);
}
else {
charsign= str.charAt(b%str.length()-1);
}
if(charsign=='#') {
cnt++;
System.out.println(cnt);
}
b+=3;
str=reader.nextLine();
}
System.out.println(str);
System.out.println(cnt);
}
}
the code itself works and I think I'm very close but it doesn't print the right answer!
I'm stuck so help would be much-appreciated thanks!

public static int count(Scanner scan) {
int res = 0;
int col = -1;
String str;
boolean check = false;
while (!"-1".equals(str = scan.nextLine())) {
if (col >= str.length())
col %= str.length() - 1;
if (check && str.charAt(col) == '#')
res++;
col += 3;
check = true;
}
return res;
}
Demo:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println(count(scan)); // 5
}
Input:
...#.#.......##....#.......#...
.#....#.##.#..#.......#.....##.
#..#...##.####..###.....#......
..#...##...#...#.#......#...#.#
.##.##.#...#.....#.##..##......
.#...#.#.##.###..#...#...#.....
.#..##..#....##.##....##....##.
..#...##....#..###........##...
.#..#..#.#....#.#...#.#......#.
.##.....#...#..#..#..#...###...
.#...#....#..#...........###...
.....#...........##.#......#...
.....#....##......##..#.#......
-1
Output:
...#.#.......##....#.......#...
.#0...#.##.#..#.......#.....##.
#..#.0.##.####..###.....#......
..#...##0..#...#.#......#...#.#
.##.##.#...1.....#.##..##......
.#...#.#.##.##2..#...#...#.....
.#..##..#....##.#3....##....##.
..#...##....#..###..3.....##...
.#..#..#.#....#.#...#.#3.....#.
.##.....#...#..#..#..#...#4#...
.#...#....#..#...........###.4.
..4..#...........##.#......#...
.....5....##......##..#.#......
-1
5

Related

ROT13 in Java doesn´t want to work properly

At some point I have trouble programming ROT13 in Java. So the User shall write whatever he wants and the programm should rewrite it in ROT13. So here´s my programm until now:
import java.io.*;
public class rot13
{
public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed
String key [] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
String keyA [] = {"N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A","B","C","D","E","F","G","H","I","J","K","L","M"};
String letter;
System.out.println("Enter a phrase:");
String phrase = myInput.readLine();
int y = 0, i = 0;
while ( y <= phrase.length()){
letter = Character.toString(phrase.charAt(y));
while(i <= y){
if (letter != key[i]){
keyA [i] = keyA[i];
}
i++;
}
System.out.println(keyA [i]);
y++;
}
}
}
The problem is the following:
It only does go for a few letters, but stops working after like 3 lines or rather after 3 latters and puts up errors which are:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(Unknown Source)
at rot13.main(rot13.java:19)
I´ve tried different words, but it keeps printing out the same problem. Does anyone knows how to fix it or at least a way to do it more proberly?
Thanks in advance!!
Why it doesn't work
import java.io.*;
public class rot13
{
public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed
String key [] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
String keyA [] = {"N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A","B","C","D","E","F","G","H","I","J","K","L","M"};
String letter;
System.out.println("Enter a phrase:");
String phrase = myInput.readLine();
int y = 0, i = 0;
while ( y <= phrase.length()){
letter = Character.toString(phrase.charAt(y));
//Each time you go throught the first loop, you are comparing your actual position in the string and i
//But as you don't reset i back to 0, you only try to compare your previous index and your actual index : if y == 3, so i takes only the values 2 and 3
//Moreover, when y > 26, you try to access the key array outside of its bounds
while(i <= y){
// letter is a string so you should be using equals
if (letter != key[i]){
// You are putting the value at the i index in the i index, so you do basically nothing with this line
keyA [i] = keyA[i];
}
i++;
}
System.out.println(keyA [i]);
y++;
}
}
}
Alternative
Here's a solution you can use :
import java.io.*;
public class rot13 {
public static void main(String[] args) throws IOException {
BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));// Buffered Reader reads the number inputed
System.out.println("Enter a phrase:");
String input = myInput.readLine();
//We loop through every char in the string
for (char c : input.toCharArray()) {
//We check if the character is a letter, so we don't add the offset to special characters like space or dot
if (Character.isAlphabetic(c)) {
//Here we get the lower case version of the char and remove it 97, which is the ascii value of 'a'
//With this, we are mapping letters from a to z to numbers from 0 to 25
char lowerChar = (char) (Character.toLowerCase(c) - 97);
//We add the offset of 13
lowerChar += 13;
//We then use the modulo to move numbers higher than 15 back to the beginning
lowerChar %= 26;
//We finally come back to the ascii value of our lower case char
lowerChar += 97;
System.out.print(Character.isUpperCase(c) ? Character.toUpperCase(lowerChar) : lowerChar);
} else {
//If it's not a letter, we just print the char
System.out.print(c);
}
}
//We don't forget to close our BuffererReader
myInput.close();
}
}
This is a described version but you can shorten it by doing all the char operations on one line

get the last digit from the name

i want to know if i can get the last digit of the input, but if the last one is 0 i want it to ignore it and take the one before it... like bob120, last digit is 20 not 0, to make it the level for the person
here is my code and i tried for 2 days to know how but i'm stuck with this problem.
and i tried %10 but still it's the same problem.
number = number.substring(5,6);
level = Integer.parseInt(number);
I'm using scanner package
thank you in advance
if the input is a String and you like the use substring the code will be
int pos= number.lenght();
String lastChar = number.substring(pos-1,pos);
Note: number is a String : )...
Then you are right on the Integer.parseInt(), be aware of error if its not a number (try, catch)...
Then you need a if statement...change your pos and try again....
To do this task it would be better to use the String.toCharArray() at loop it backwards... so if you have time study this..
Something like this:
public int getLastNumDifThenZero(String text){
char[] ca = text.toCharArray();
for (int i = ca.length-1; i >= 0; i--) {
char a = ca[i];
try {
int n = Integer.parseInt(String.valueOf(a));
if (n!=0){
return n;
}
} catch (NumberFormatException e) {
//Not a number
}
}
return -1;
}
You can loop from the end of String and search for 'non-zero' value (result char is String) :
public static void main(String[] args) {
// example returns 7
String num = "85677000";
char lastDigit =' ';
// looping from end and searching non zero digit
for(int i=num.length()-1 ; i>=0 ;i--){
lastDigit=num.charAt(i);
if (lastDigit != '0'){
System.out.println(lastDigit);
break;
}
}
}

Index value wont Increase after comparing two chars

I started this because I was totally bored but because of this error I have been sitting here since so long and finally decided to take this to stackOverFlow. Here is the code Which I wrote.
I was trying to print characters by skipping 1 index. But when there are duplicates I want to print a space which would differentitate words from big string.
Updated Question: Everything fixed except I cant increase I value more than 1. I commented it in below program. Please look at it.
Let me cut the chase and get to the point. I need this output " Vishnu Vardhan" from this String "aVeIwSjHaNgUaaVdAgRjDkHxAmN";
My only requirement is if the string has two same letters it has to print space. So "aVeIwSjHaNgU [aa] VdAgRjDkHxAmN" the aa in the brackets has to be replaced by space.
It has to be dynamic, if any char is repeated it has to print a space and jump to required next char and print it.
Here is the Updated program. Using help from one of the comments.
public class Decrypter {
public static void main(String[] args) {
String Text = "aVeIwSjHaNgUaaVdAgRjDkHxAmN";
char[] convertedText = Text.toCharArray();//converted string to char array
for (int i = 1; i < convertedText.length; i++) { //Looping it to print alternate chars
/* if the character at an index is same as the character at next index then
add a space and increase index value by 2 so I can print the required char*/
if (i + 1 < convertedText.length) {
if (Text.charAt(i) == Text.charAt(i + 1)) {
i++;// Increasing I value by 2 here will give me required output. Everything is perfect now
System.out.printf("%s ", convertedText[i]);
} else {
System.out.printf("%s", convertedText[i]);
i++;
}
}
}
}
}
Current output : VISHNUadgjkxm
Required output: VISHNU VARDHAN
i dont know if converting string to charArray is required but i hope this will do. comment below if you have questions open for revision.
String text = "aVeIwSjjHaNgUkkVarqddlhxn";
//this is the holder of your new processed text.
String newText = "";
//start of counter. it may start in any number depends on requirements.
int x = 0;
//loop while the x is lessthan the length of your string.
while(x < text.length()){
//check if the x + 1 is not equal to the length of your string to avoid StringIndexOutOfBoundsException
if((x+1) != text.length()){
//in this area it will check if the current char is the same on next index
if(text.charAt(x) == text.charAt(x+1)){
// this will concatenate/append the value of char with space
newText += text.charAt(x) +" ";
// this will increase the value of your x by 1 and at the bottom there are also x++ that will add 1 to your x so the total sum of x if (text.charAt(x) == text.charAt(x+1)) are true, will be 2.
x++;
}
}
newText += text.charAt(x);
x++;
}
System.out.println(newText);
output :
aVeIwSj jHaNgUk kVarqd dlhxn
if this is not what you looking for please kindly update your question.
Fixed:
/**
*
* #author Chintu
*/
public class Decrypter {
public static void main(String[] args) {
String Text = "aVeIwSjHaNgUkkVarqdlhxn";
char[] convertedText = Text.toCharArray();//converted string to char array
for (int i = 1; i < convertedText.length; i++) { //Looping it to print alternate chars
/* if the character at an index is same as the character at next index then
add a space and increase index value by 2 so I can print the required char*/
if (i+1 < convertedText.length) {
if (Text.charAt(i) == Text.charAt(i + 1)) {
i++;
System.out.printf("%s ",convertedText[i]);
}
}
System.out.printf("%s", convertedText[i]);
}
}
}
Fixed
public class Decrypter {
public static void main(String[] args) {
String Text = "aVeIwSjHaNgUaaVdAgRjDkHxAmN";
char[] convertedText = Text.toCharArray();//converted string to char array
for (int i = 0; i < convertedText.length; i++) { //Looping it to print alternate chars
/* if the character at an index is same as the character at next index then
add a space and increase index value by 2 so I can print the required char*/
if (i + 1 < convertedText.length) {
if (Text.charAt(i) == Text.charAt(i + 1)) {
i += 2;
System.out.printf(" %s", convertedText[i]);
} else {
i++;
System.out.printf("%s", convertedText[i]);
}
}
}
}
}
output: VISHNU VARDHAN

Reduce the value of a letter, e.g. can change 'd' to 'c', but cannot change 'c' to 'd'. In order to form a palindrome

public class Solution {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int tc = Integer.parseInt(br.readLine());//I get Numberformat Exception here
for(int i=0;i<tc;i++) // Even if my inputs are on separate lines
{
String original = br.readLine();
palindrome(original);
}
}
public static void palindrome(String original)
{
String reverse="";
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
{
System.out.println(0);
}
else
{
char[] org = original.toCharArray();
int len = org.length;
int mid = len / 2;
if(len % 2 == 0)
{
char[] front = new char[mid];
char[] back = new char[mid];
for(int i=0;i<mid;i++)
{
front[i] = org[i];
}
int j=0;
for(int i=len-1;i>=mid;i--)
{
back[j] = org[i];
j++;
while(j > mid)
{
break;
}
}
change(front,back,mid);
}
else
{
char[] front = new char[mid];
char[] back = new char[mid];
for(int i=0;i<mid;i++)
{
front[i] = org[i];
}
int j=0;
for(int i=len-1;i>mid;i--)
{
back[j] = org[i];
j++;
while(j > mid)
{
break;
}
}
change(front,back,mid);
}
}
}
public static void change(char[] front,char[] back,int len)
{
int count =0;
for(int i =0;i<len;i++)
{
if(front[i] != back[i] )
{
count += (back[i] - front[i]);
}
}
System.out.println(count)
}
}
What i try to do here is get an input from the number of test cases say 3 in my first line followed by the test-cases themselves.
sample input :
3
abc
abcba
abcd
Now it has to check if the string is a palindrome if its so it ll print 0
else it breaks the string into two halves front and back and finds the minimum number of changes to make it a palidrome.
here i have also checked if its a odd or even length string if odd i have omitted the middle char.
By changes we can only change 'd' to 'b' not 'b' to 'd'
Once a letter has been changed to 'a', it can no longer be changed.
My code works fine for the above input but it doesnt for some other inputs i dont quiet understand why..
for instance if i give a custom test case as
5
assfsdgrgregedhthtjh
efasfhnethiaoesdfgv
ehadfghsdfhmkfpg
wsertete
agdsjgtukgtulhgfd
I get a Number Format Exception.
Your code works fine here, whithout NumberFormatException: http://ideone.com/QJqjmG
This may not solve your problem, but improves your code...
As first user input you are expecting an integer. You are parsing the String returned by br.readLine() and do not take care of the NumberFormatException parseInt(...) may throw.
Just imagine someone hits space or return key as first input.
So I propose to put a try-catch-block around the parseInt(...). Here is an example how this may look like.
Guys thank you for all your suggestion i just found out why my other test cases weren't working
public static void change(char[] front,char[] back,int len)
{
int count =0;
for(int i =0;i<len;i++)
{
if(front[i] != back[i] )
{
count += (back[i] - front[i]);
}
}
System.out.println(count)
}
This part of my code has to be changed to
public static void change(char[] front,char[] back,int len)
{
int count =0;
for(int i =0;i<len;i++)
{
if(front[i] != back[i] )
{
char great = findGreatest(front[i],back[i]);
if(great == back[i])
{
count += (back[i] - front[i]);
}
else
{
count += (front[i] - back[i]);
}
}
}
System.out.println(count);
}
public static char findGreatest(char first,char second)
{
int great = first;
if(first < second)
{
great = second;
}
return (char)great;
}
Because i get negative values coz of subtracting ascii's which are greater than them and as i have already mentioned i can only do 'd' to 'a' not the other way round.
Thank you for your time guys!

java.lang.StringIndexOutOfBoundsException: String index out of range when trying to check if a word is a palindrome

I been trying write code that checks if a word is a word that the first letter and the last letter are the same. In essence, it's code that checks to see if a Word is a palindrome.
Code
import java.util.*;
public class Class1 {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
String n = reader.next();
boolean right = true;
for (int i=0; i<n.length();i++)
{
int f = n.length()-i;
if (n.charAt(i) != n.charAt(f -i))
{
right=false;
}
}
System.out.println("The word is " + right);
}
}
I get this error:
TT
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(Unknown Source)
at Class1.main(Class1.java:12)
Thank you.
It's almost right, just int f = n.length()-i; should be int f = n.length()-1;.
n.length()-1 is the index of the last character in the string. So f-i will be the i-th character from the right.
Try this:
import java.util.*;
public class Class1 {
static Scanner reader = new Scanner(System.in);
public static void main(String[] args) {
String n = reader.next();
boolean right = true;
int f = n.length()-1;
for (int i=0; i<n.length();i++)
{
if (n.charAt(i) != n.charAt(f-i))
{
right=false;
}
}
System.out.println("The word is " + right);
}
}
Suppose take an example the length of String is 3 and when i reaches 2 then according to you f will be 1
then take this line n.charAt(f -i) it will be like charAt(1-2) so definately it will throw some exception
Try something like this
int s = n.length();
for (int i=0; i<(s/2)+1;++i) {
if (n.charAt(i) != n.charAt(s - i - 1)){
right=false;
}
}
System.out.println("The word is " + right);
Dont forget to debug the code to know about the flow only finding the solution is never going to help you
To add with other answers you don't need to loop through the whole string. you only need to loop through half of the string length to see if your string is a palindrome or not.
Suppose you are checking if madam is palindrome or not. You have to loop half of the length of madam that is 5/2 or 2 times only.
index0 m == m index4
index1 a == a index2
So here is the slightly modified code
for(int i = 0;i<n.length()/2;i++) {
if(n.charAt(i) != n.charAt(n.length()-1-i))
{
right=false;
}
}
The error you are getting is an index out of range, stating your input parameter for n.charAt(#) is outside n's index range, it being from 0 to n.length()-1
The error in your code however is at this point of the code:
int f = n.length()-i; //negate i from the length
if (n.charAt(i) != n.charAt(f -i)) //negate i from the already negated length
and the fix should be:
int f = n.length()-i-1;
if (n.charAt(i) != n.charAt(f))

Categories

Resources