Errors in my code using do/while - java

I am a student (big time "Newbie") learning java. The two examples below are in fact homework. Example 1 is a game of guess the card (black or red) and Example 2 is a game of rock, paper ,scissors.
I have searched this site for answers, and the responses I have seen go out of context with where we are in our curiculum. At this point we are in do/while, while & for loops.
This is the code I came up with (no small feat for me) that I would like to have debuged. I do not care about making it more efficient or anything of the like. I am more concerned with having it work. I am using netbeans and I have put (<---)'s where there seems to be a problem. Your help would be greatly appriciated. Thanks in advance.
P.S. The course is in french, so do not be suprised if some of the variable names do not make sense.
EX1------------------------------------------------------------------------------------
package devoir.pkg3;
import java.util.Scanner;
public class Dev3Ex4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char r = 'r', n = 'n', q = 'q';
int i, compteur = 0, compteurDeux = 0;
do {
System.out.println("Deviner la couleur de la carte. \"r\" rouge, \"n\" noire et \"q\" quitter.");
char clavier = scanner.next().charAt(0);
i = (int) (2.0 * Math.random());
compteur = compteur + 1;
if (i == 0) {
char tmp = 'n';
}
if (i == 1) {
char tmp = 'r';
}
if (clavier == tmp) { <------ (temp value error)
compteurDeux = compteurDeux + 1;
System.out.println("Bon choix ! Score: " + compteurDeux + "/" + compteur);
}
if (clavier != tmp) { <------ (temp value error)
System.out.println("Non...Score: " + compteurDeux + "/" + compteur);
}
} while (clavier != 'q'); <------ (clavier value error)
System.out.println("Votre score final est " + compteurDeux + "/" + compteur);
}
}
EX2------------------------------------------------------------------------------------
package devoir.pkg3;
import java.util.Scanner;
public class Dev3Ex5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char q = 'q';
int i, compteur = 0, compteurDeux = 0;
do {
System.out.println("Jouons a Roche/papier/ciseaux. \"r\" roche, \"p\" papier. \"c\" ciseax et \"q\" quitter.");
char clavier = scanner.next().charAt(0);
i = (int) (3.0 * Math.random());
if (clavier == 'r') {
int tmp = 0;
}
if (clavier == 'c') {
int tmp = 1;
}
if (clavier == 'p') {
int tmp = 2;
}
if (tmp == 0 && i == 1 || tmp == 1 && i == 2 || tmp == 2 && i == 0) {<--(All tmp values error)
compteur = compteur + 1;
System.out.println("Bon choix ! Score: " + compteur + "/" + compteurDeux);
}
if (tmp == 1 && i == 0 || tmp == 2 && i == 1 || tmp == 0 && i == 2) {<--(All tmp values error)
compteurDeux = compteurDeux + 1;
System.out.println("Non...Score: " + compteur + "/" + compteurDeux);
}
if (tmp == i) { <--(tmp value error)
System.out.println("Parti nul. Score " + compteur + "/" + compteurDeux);
}
} while (clavier != 'q'); <--(clavier value error)
System.out.println("Votre score final est " + compteur + "/" + compteurDeux);
}
}

You have problems with your local variable declaration inside code blocks
if (i == 0) {
char tmp = 'n';
}
if (i == 1) {
char tmp = 'r';
}
Change it to something like this:
char tmp='';
if (i == 0) {
tmp = 'n';
}
if (i == 1) {
tmp = 'r';
}
Same for char clavier and int tmp - declare & define them first before using them, usually at the start of your function, so that all your variables will be in one place.
Note: This is considered to be best practice to define variables at the top of your Method and class block.

Your issue is one of scope: when you define char tmp = 'n' inside of an if { } block, that variable tmp is available for use only inside of that block. You need to define char tmp outside of the series of if statements, then simply specify its value inside them, like:
char tmp = ' ';
if (i == 0) {
tmp = 'n';
}
else if (i == 1) {
tmp = 'r';
}
etc.
Same thing for your clavier variable in both examples, which are declared inside the do {} block, and will thus be available only inside that block, not in the control for the block.

1.char tmp has to be declared outside the block as shown below.
char tmp;
if (i == 0) {
tmp = 'n';
}
if (i == 1) {
tmp = 'r';
}
Same with clavier, has to be declared outside do to be used in the while condition.
char clavier
do{
2.Same with the second program. declare the tmp values outside and then use them.

Related

Increment Alpha-Numeric values but restrict to 3 characters

The scenario is - I read the last line of a file, increment it by one and write it back.
The read and write has been done. I am finding it difficult to increment the alpha-numberic values as it has a few conditions.
The conditions are:
It should only be 3 characters long
Example : A01, A02.... A99, B01, B02.... B99..
Once Z99 is reached it should be AA1, AA2, AA3...AA9, .....
Then AB1, AB2,... AZ9
So basically while incrementing the value should not go AA10 which makes it 4 characters
What I am doing now is separating the alphabets and integers, incrementing it and concatenating them back.
The code so far:
String[] part = lastLine.split("(?<=\\D)(?=\\d)");
System.out.println(part[0]);
System.out.println(part[1]);
int numberOnly = Integer.parseInt(lastLine.replaceAll("[^0-9]", ""));
numberOnly++;
String lettersOnly = lastLine.replaceAll("[^A-Z]", "");
if (lettersOnly.length() > 1){
String lastLetter = lettersOnly.substring(lettersOnly.length() - 1);
if(lastLetter.equalsIgnoreCase("Z") && number.equalsIgnoreCase("9") ){
String notLastLetter = lettersOnly.substring(lettersOnly.length() - 2);
char d = lettersOnly.charAt(0);
d++;
System.out.println("Letters after increment more tan two : " +d);
lettersOnly = Character.toString(d) + "Z";
}
}
else{
}
System.out.println("Letters after increment : " +lettersOnly);
Any help would be greatly appreciated.
public class AlphaNumericCounter {
String[] part;
int counter; //Variable storing numeric part of counter
String alpha; //Variable storing Alpha part of counter
static String final_output = "A00"; // First Input considered as A00 and also the variable which will be store each count
static boolean continueIncrement = true; //For running the loop till we reach ZZ9
/* Def constructor */
public AlphaNumericCounter() {
}
/* Constructor called from main method with primary input A00 */
public AlphaNumericCounter(String number) {
part = number.split("(?<=\\D)(?=\\d)");
}
/* Function called each time from inside loop to generate next alphanumeric count */
public void increment() {
part = final_output.split("(?<=\\D)(?=\\d)");
counter = Integer.valueOf(part[1]) + 1;
alpha = part[0];
}
public String toString() {
if (alpha.length() == 1){
if (String.valueOf(counter).length() > 2){
if ((int)alpha.charAt(0) + 1 > 90/*If Z encountered*/){
alpha = "AA";
}else{
alpha = String.valueOf((char)((int)alpha.charAt(0) + 1));//Take Next Alphabet
}
counter = 1; //Reset counter to 1
}
}else{
//We have AA, AB ... ZZ format of alpha
if (String.valueOf(counter).length() > 1){
if ((int)alpha.charAt(0) + 1 > 90 && (int)alpha.charAt(1) + 1 > 90){
continueIncrement = false;
System.out.println("NO MORE COMBINATION AVAILABLE"); //We reached ZZ
return "";
}else if ((int)alpha.charAt(1) + 1 <= 90){
alpha = String.valueOf((char)((int)alpha.charAt(0))) + String.valueOf((char)((int)alpha.charAt(1) + 1));
counter = 1;
}else if ((int)alpha.charAt(1) + 1 > 90){
if ((int)alpha.charAt(0) + 1 <= 90){
alpha = String.valueOf((char)((int)alpha.charAt(0) + 1)) + "A";
counter = 1;
}
}
}
}
generateString();
return final_output;
}
private void generateString(){
int l1 = String.valueOf(counter).length();
int l2 = alpha.length();
final_output = alpha + (l2 == 1 && l1 == 1 ? "0" : "") + String.valueOf(counter);
}
public static void main(String[] args) {
AlphaNumericCounter lic = new AlphaNumericCounter(final_output);
while (continueIncrement){
lic.increment();
System.out.println(lic);
}
}
}
What about incrementing each "digit" separatly from right to left and handle overvlow to the next digit:
String number;//number - is your originally string
char[] digits = number.toCharArray();
boolean overflow = true;
for(int i = 2; i >= 0; i--){
if(overflow){
switch(digits[i]){
case 'Z':
digits[i] = '0';
overflow = true;
break;
case '9':
digits[i] = 'A';
overflow = false;
break;
default:
digits[i]++;
overflow = false;
}
}
}
if(overflow){
//handle ZZZ overflow here
}
String result = new String(digits);
A simple solution is to count in Base36
Try this:
class AlphaNumericIncrementer {
public static void main(String[] args) {
/*
When starting at '000' => We hit 'zzz' (i.e. Dead End) at 46,656
When starting at 'A00' => We hit 'zzz' (i.e. Dead End) at 33,696
*/
int index = 0;
String currentNumber = "000";
while (index < 46656) {
index++;
String incrementedNumber = base36Incrementer(currentNumber, 36);
currentNumber = incrementedNumber;
if (incrementedNumber.toCharArray().length != 3) {
System.out.println("We got intruder with length: " + incrementedNumber.toCharArray().length);
System.out.println("Our Intruder is: " + incrementedNumber);
break;
}
System.out.println(incrementedNumber);
}
System.out.println("Number of entries: " + index);
}
// The function that increments current string
public static String base36Incrementer(String v, int targetBase) {
String answer = Integer.toString(Integer.parseInt(v, targetBase) + 1, targetBase);
return String.format("%3s", answer).replace(' ', '0');
}
}

Finding substring in a string in Java

I am writing a program to find substring in the string in Java without using any Java Library.
I had written a function subString(String str1, String str2) as shown below.
It is working for the following input:
str1="rahul"
str2="My name is rahul"
str1="rahul"
str2="rahul sah"
str3="rahul"
str2="sah rahul"
The problem occurs when I give input as:
str1="rahul"
str2="rararahul"
str1="rahul"
str2="My name is sunil"
It goes to infinite loop. Can anyone have a look into my code snippet and help me out.
public static boolean subString(String str1, String str2) {
boolean found = false;
int len1 = str1.length();
int len2 = str2.length();
int status = 0;
char[] arr1 = new char[len1];
char[] arr2 = new char[len2];
for (int ii = 0; ii < len1; ii++) {
arr1[ii] = str1.charAt(ii);
}
for (int jj = 0; jj < len2; jj++) {
arr2[jj] = str2.charAt(jj);
}
for (int ii = 0; ii < len1; ii++) {
for (int jj = 0; jj < len2; jj++) {
if (arr1[ii] == arr2[jj]) {
if (ii < len1 - 1) {
System.out.println("Found1::" + "arr1::" + arr1[ii]
+ "and arr2::" + arr2[jj]);
found = true;
ii++;
} else if (arr1[ii] == arr2[jj] && ii == len1 - 1) {
System.out.println("Found2::" + "arr1::" + arr1[ii]
+ "and arr2::" + arr2[jj]);
found = true;
break;
}
} else if (found == false && arr1[ii] != arr2[jj]) {
System.out.println("Found3::" + "arr1::" + arr1[ii]
+ "and arr2::" + arr2[jj]);
found = false;
} else if (found == true && arr1[ii] != arr2[jj]) {
System.out.println("Found4::" + "arr1::" + arr1[ii]
+ "and arr2::" + arr2[jj]);
found = false;
ii = 0;
}
}
}
return found;
}
}
Others have suggested using String.contains() - which is java.lang code, rather than a Java library. However, you obviously want to explore how you could do this yourself. One way to do that is to look at the OpenJDK 7 source code for String.contains(), which under the covers uses String.indexOf(). You can see the (fairly basic) algorithm they use there.
Problem with your code
Interestingly, your code works for "rahul" and "rararahul" when I paste it into my dev environment. The infinite loop on non matching exists, though. This will occur for any str2 that contains any of the characters of str1. This is because once you find a match of any character in str1 within str2, you reset your variables to start again. Your output is actually enough to debug that, if you look at the sequence that it goes through each string.
Possible fix
If you want to pursue your own approach and learn from that then consider stopping and doing a little design on paper with your own approach. You're looking for an occurence of str1 in str2. So you probably want to swap your loops around. Then you can be more efficient. You can go through the longer String (str2) character by character in the outer loop. Then you only really need to go into the inner loop if the first character of the shorter string (str1) matches the character you're dealing with in str2.
e.g. for the loop bit of your code
boolean retFound = false;
for (int jj = 0; jj < len2; jj++) {
if (arr1[0] == arr2[jj]) {
boolean tempFound = true;
int foundIndex = jj;
for (int ii = 0; ii < len1; ii++) {
if (arr1[ii] != arr2[jj+ii]) {
tempFound = false;
break;
}
}
if (tempFound) {
System.out.println("Found substring " + str1 + " in " + str2 + " at index " + foundIndex);
System.out.println("Carrying on to look for further matches...");
tempFound = false;
retFound = true;
}
}
}
return retFound;
Note, this won't be fast, but it should work. I've tested on all the string samples you provided. You get a bonus too - it will find multiple matches. If you don't want that (just want true false), break out when it says "Carrying on to look for..."
As others have said, if you want to continue with your original code, certainly don't try to change loop variables (i.e. ii) within the inner loop. That's bad practice, hard to read and prone to lots of bugs.
in the block startin with
} else if (found == true && arr1[ii] != arr2[jj]) {
you set ii back to zero. And thats why ii never will be bigger or equals len1
You need to put the outer loop for jj and inner loop for ii:
int ii=0;
for (int jj = 0; jj < len2; jj++) {
if (arr1[ii] == arr2[jj]) {
if (ii < len1 - 1) {
System.out.println("Found1::" + "arr1::" + arr1[ii]
+ "and arr2::" + arr2[jj]);
found = true;
ii++;
} else if (arr1[ii] == arr2[jj] && ii == len1 - 1) {
System.out.println("Found2::" + "arr1::" + arr1[ii]
+ "and arr2::" + arr2[jj]);
found = true;
break;
}
} else if (found == false && arr1[ii] != arr2[jj]) {
System.out.println("Found3::" + "arr1::" + arr1[ii]
+ "and arr2::" + arr2[jj]);
found = false;
} else if (found == true && arr1[ii] != arr2[jj]) {
System.out.println("Found4::" + "arr1::" + arr1[ii]
+ "and arr2::" + arr2[jj]);
found = false;
ii = 0;
}
}
EDIT:
You are also initializing the inner for loop for each character in the larger string. You don't need two loops at all. I have changed it appropriately. This should work.
You can use one loop and matching condition where the search will begin when the first char will be found in the full string. And then, the search will continue where where the matching will one by one from the list.Okay, here I am giving an example to explain.
public static boolean subString2(String smallString, String fullString)
{
int k = 0;
for (int i = 0; i < fullString.length(); i++)
{
System.out.println("fullStringCharArray[i]: " + fullString.charAt(i));
if (smallString.charAt(k) == fullString.charAt(i))
{
System.out.println("Found: " + smallString.charAt(k));
k++;
if (k == smallString.length())
return true;
}
else
{
k = 0;
}
}
return false;
}
Here, what is happening, we are going to search in fullString. if the first char of your smallString 'rahul' is 'r' then until it is found, the other part of the string ('ahul') will not be matched. so when the 'r' is matched then it will try to search for 'a' and then 'h' and more. So, if the count of search true(k) is equal of smallString length then the substring exists. I hope, I could explain properly. Sorry for my English.
Use This Code.
This will help you and very short and clear
public static boolean subString(String str1, String str2) {
int str1Len = str2 == null ? 0 : str1.length();
int str2Len = str2 == null ? 0 : str2.length();
for (int i = 0; i < str2Len; i++) {
if (str1.charAt(0) == str2.charAt(i)) {
int count = 0;
for (int j = 0; j < str1Len; j++) {
if (str1.charAt(j) == str2.charAt(i)) {
i++;
count++;
}
}
if (count == str1Len) {
return true;
}
}
}
return false;
}
public class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String str=sc.nextLine();
String Str1=" ";
System.out.println("Enter the numbers");
int start=sc.nextInt();
int end=sc.nextInt();
for (int i = start; i < end; i++)
Str1 += String.valueOf(str.charAt(i));
System.out.println(Str1);
}
}

Java for loop error

I am trying to get user input for sortValues[] array using the for statement (enter character 1, enter character 2, etc).
However, when I execute this, the program will not allow me to enter for character 2, instead skipping directly to character 3, as seen below.
How to resolve this? The code is included below.
thanks!
static public void s_1d_char () {
int counter=0;
int x=0;
c.print("How many characters? ");
counter = readInt();
char[] sortValues = new char[counter+1];
for (x=1;x<=counter;x++) {
System.out.println("Enter character "+(x)+":");
sortValues[x] = readChar();
}
}
readChar implementation (this is from a library):
public synchronized char readChar ()
{
char result, ch;
if (ungotChar != EMPTY_BUFFER)
{
result = (char) ungotChar;
ungotChar = EMPTY_BUFFER;
return (result);
}
if (lineBufferHead != lineBufferTail)
{
result = lineBuffer [lineBufferTail];
lineBufferTail = (lineBufferTail + 1) % lineBuffer.length;
return (result);
}
startRow = currentRow;
startCol = currentCol;
if (currentRow > maxRow)
{
startRow++;
currentCol = 1;
}
// Turn cursor on if necessary
consoleCanvas.setCursorVisible (true);
// Wait for a character to be entered
while (true)
{
ch = getChar ();
if (ch == '\n')
{
clearToEOL = false;
if (echoOn)
print ("\n");
clearToEOL = true;
lineBuffer [lineBufferHead] = '\n';
lineBufferHead = (lineBufferHead + 1) % lineBuffer.length;
break;
}
if (ch == '\b')
{
if (lineBufferHead == lineBufferTail)
{
consoleCanvas.invertScreen ();
}
else
{
int chToErase;
lineBufferHead = (lineBufferHead + lineBuffer.length - 1) % lineBuffer.length;
chToErase = lineBuffer [lineBufferHead];
if (echoOn)
{
if (chToErase != '\t')
{
erasePreviousChar ();
}
else
{
int cnt;
eraseLineOfInput ();
cnt = lineBufferTail;
while (cnt != lineBufferHead)
{
print (lineBuffer [cnt]);
cnt = (cnt + 1) % lineBuffer.length;
}
}
}
}
} // if backspace
else if (ch == '\025')
{
if (echoOn)
{
eraseLineOfInput ();
}
lineBufferHead = lineBufferTail;
}
else
{
if (echoOn)
{
print (ch);
}
lineBuffer [lineBufferHead] = ch;
lineBufferHead = (lineBufferHead + 1) % lineBuffer.length;
}
} // while
result = lineBuffer [lineBufferTail];
lineBufferTail = (lineBufferTail + 1) % lineBuffer.length;
// Turn cursor on if necessary
consoleCanvas.setCursorVisible (false);
return (result);
}
I recommend getting user input with a scanner:
import java.util.Scanner;
// ...
int counter = 0;
System.out.println("How many characters?");
Scanner keyboard = new Scanner(System.in);
counter = keyboard.nextInt();
char[] sortValues = new char[counter+1];
// Start your index variable off at 0
for (int x = 0; x < counter; x++) {
System.out.println("Enter character "+(x)+":");
keyboard = new Scanner(System.in);
String line = keyboard.nextLine();
sortValues[x] = line.charAt(0);
}
This will capture the first character of the line. If the user enters more than one character, the program will read only the first.
Also, you should really start your index variable x off at 0, considering arrays are 0-based indexed.
instead of readChar() try:
sortValues[x] = Integer.parseInt(System.console().readLine());
How to read integer value from the standard input in Java

Getting a NumberFormatException

I was writing some code for an interviewstreet.com challenge
My code gives a NumberFormatException
import java.io.*;
public class BlindPassenger
{
public static void main(String [] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int t,n;
//System.out.println(line);
t = Integer.parseInt(line);
for(int i=0;i<t;++i)
{
line = br.readLine();
n = Integer.parseInt(line); --n;
if(n == 0)
{
System.out.println("poor conductor");
}
else
{
char direction='l',seat_posn='l';
int row_no = 0, relative_seat_no = 0;
row_no = (int) Math.ceil(n/5.0);
relative_seat_no = n % 5;
if(row_no % 2 == 0)
{
//even row, need to reverse the relative seat no
relative_seat_no = 6 - relative_seat_no;
}
if(relative_seat_no < 3)
{
direction = 'L';
if(relative_seat_no == 1) seat_posn = 'W';
else seat_posn = 'A';
}
else
{
direction = 'R';
if(relative_seat_no == 3) seat_posn = 'A';
else if(relative_seat_no == 4) seat_posn = 'M';
else seat_posn = 'W';
}
System.out.println(row_no + " " + seat_posn + " " + direction);
}
}
}
}
Here is the test case that they use
3
1
2
3
Output:
poor conductor
1 W L
1 A L
There seems to be a trailing space or something at the end of each line that causes the exception.
$ java BlindPassenger <input00.txt
Exception in thread "main" java.lang.NumberFormatException: For input string: "3
"
at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at BlindPassenger.main(BlindPassenger.java:11)
This has taken up half an hour and I don't know how to fix this.
Kills the fun of the event doesn't it. Can someone tell me what I'm doing wrong.
Integer.parseInt() can't handle strings that don't fit its expected format, as you've found out. You could trim() the string before you parse it:
t = Integer.parseInt(line.trim());
This gets rid of leading and trailing whitespace.
You have to trim the string
import java.io.*;
public class BlindPassenger
{
public static boolean isEmpty(final String string)
{
return string == null || string.trim().isEmpty();
}
public static void main(String [] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int t,n=0;
//System.out.println(line);
t = Integer.parseInt(line);
for(int i=0;i<t;++i)
{
line = br.readLine();
if(!isEmpty(line)){
n = Integer.parseInt(line.trim());
--n;
}
if(n == 0)
{
System.out.println("poor conductor");
}
else
{
char direction='l',seat_posn='l';
int row_no = 0, relative_seat_no = 0;
row_no = (int) Math.ceil(n/5.0);
relative_seat_no = n % 5;
if(row_no % 2 == 0)
{
//even row, need to reverse the relative seat no
relative_seat_no = 6 - relative_seat_no;
}
if(relative_seat_no < 3)
{
direction = 'L';
if(relative_seat_no == 1) seat_posn = 'W';
else seat_posn = 'A';
}
else
{
direction = 'R';
if(relative_seat_no == 3) seat_posn = 'A';
else if(relative_seat_no == 4) seat_posn = 'M';
else seat_posn = 'W';
}
System.out.println(row_no + " " + seat_posn + " " + direction);
}
}
}
}

Convert letter to digits

I want to change the letters A to point 1 and so the letter Z to be number 26, then changed again to number 27 letters AA, AB to 28. How do I? Do I have to use the "switch"? I use java program.
Did not test this, but something along these lines should work:
public String numberToCharacterRepresentation(int number) {
char[] ls = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
String r = "";
while(true) {
r = ls[number % 26] + r;
if(number < 26) {
break;
}
number /= 26;
}
return r;
}
The reverse:
public int stringToNumber(String str) {
char[] ls = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
Map<Character, Integer> m = new HashMap<Character, Integer>();
int j = 0;
for(char c: ls) {
m.put(c, j++);
}
int i = 0;
int mul = 1;
for(char c: new StringBuffer(str).reverse().toString().toCharArray()) {
i += m.get(c) * mul;
mul *= ls.length;
}
return i;
}
Use the Character object 0=>0 a=>10, etc If you only use letters then subtract 10
Character.forDigit(10,Character.MAX_RADIX) //will return 'a'
Character.getNumericValue('a') // will return 10
A simple solution is to treat the problem like writing letters instead of digits.
public static String asLetters(long num) {
StringBuilder sb = new StringBuilder();
while(num > 0) {
sb.append((char) ('#' + num % 26));
num /= 26;
}
return sb.toString();
}
For those of you wanting to do this for Excel:
public String getEquivColumn(int number){
String converted = "";
// Repeatedly divide the number by 26 and convert the
// remainder into the appropriate letter.
while (number >= 0)
{
int remainder = number % 26;
converted = (char)(remainder + 'A') + converted;
number = (number / 26) - 1;
}
return converted;
}
How about using c-'A'+1 to convert the letter in c to the number you want? Calculating the next place would be the same except add 27 instead. Basically what you're doing is converting a base-26 number to decimal except you have no zero.
This will do the job.
public String map(int i) {
String res = "";
if (i <= 0) {
throw new IllegalArgumentException("Can only map +ve numbers");
}
while (i > 0) {
res = Character.toString('A' + ((i - 1) % 26)) + res;
i = i / 26;
}
return res;
}
A more complicated version using a StringBuilder would be a more efficient, but this one is easier to understand.
Perhaps the simplest way for A-Z would be something like:
char c = *whatever letter you need*;
int cAsInt = Integer.toString(c - '#'); // # is 1 less than A
For things like AA, BB, etc., it would depend on how many combinations you need. Setting up a mapping might be quickest, but if the possibilities are endless, you'll have to figure out some formula.
import javax.swing.JOptionPane;
public class TBesar{
public static long x(int a, int b){
if (b==0){
return(1);
}
else{
return(a*(x(a,(b-1))));
}
}
public static long KatakeAngka(String nama){
int A = 0;
int B = 26;
long C = 0;
long Z;
int panjang = nama.length();
char namas[] = new char[panjang];
for (int i=0;i<panjang;i++){
namas[i] = nama.charAt(i);
switch (namas[i]){
case 'a' : A=1;break;
case 'b' : A=2;break;
case 'c' : A=3;break;
case 'd' : A=4;break;
case 'e' : A=5;break;
case 'f' : A=6;break;
case 'g' : A=7;break;
case 'h' : A=8;break;
case 'i' : A=9;break;
case 'j' : A=10;break;
case 'k' : A=11;break;
case 'l' : A=12;break;
case 'm' : A=13;break;
case 'n' : A=14;break;
case 'o' : A=15;break;
case 'p' : A=16;break;
case 'q' : A=17;break;
case 'r' : A=18;break;
case 's' : A=19;break;
case 't' : A=20;break;
case 'u' : A=21;break;
case 'v' : A=22;break;
case 'x' : A=23;break;
case 'w' : A=24;break;
case 'y' : A=25;break;
case 'z' : A=26;break;
}
int D = panjang-(i+1);
Z = (x(B,D))*A;
C = C+Z;
}return(C);
}
public static String hitung(long angka){
String B ;
if(angka<27){
if(angka==1){
B="a";
}else if(angka==2){
B="b";
}else if(angka==3){
B="c";
}else if(angka==4){
B="d";
}else if(angka==5){
B="e";
}else if(angka==6){
B="f";
}else if(angka==7){
B="g";
}else if(angka==8){
B="h";
}else if(angka==9){
B="i";
}else if(angka==10){
B="j";
}else if(angka==11){
B="k";
}else if(angka==12){
B="l";
}else if(angka==13){
B="m";
}else if(angka==14){
B="n";
}else if(angka==15){
B="o";
}else if(angka==16){
B="p";
}else if(angka==17){
B="q";
}else if(angka==18){
B="r";
}else if(angka==19){
B="s";
}else if(angka==20){
B="t";
}else if(angka==21){
B="u";
}else if(angka==22){
B="v";
}else if(angka==23){
B="w";
}else if(angka==24){
B="x";
}else if(angka==25){
B="y";
}else{B="z";}
return(B);
}
else{
return(hitung(angka/26)+hitung(angka%26));
}
}
public static void main (String [] args){
String kata = JOptionPane.showInputDialog(null,"Masukkan Kata ke 1");
String kata2 = JOptionPane.showInputDialog(null, "Masukkan Kata ke 2");
long hasil = KatakeAngka(kata);
long hasil2 = KatakeAngka(kata2);
long total = hasil+hasil2;
String HasilKata = hitung(total);
JOptionPane.showMessageDialog(null,kata+" = "+hasil+"\n"+kata2+" = "+hasil2+"\n"+kata+" + "+kata2+" = "+HasilKata);
}
}
This will work for A to ZZ :
public static int columnCharToNumber(String str) {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if(str.length() == 1) {
return alphabet.indexOf(str);
}
if(str.length() == 2) {
return ( alphabet.indexOf(str.substring(1)) + 26*(1+alphabet.indexOf(str.substring(0,1)))) ;
}
return -1;
}

Categories