Frage

I am working on a USACO problem (ride) and I am trying to convert a capital char (i.e.'A') to it's respective int (for 'A' it would be 1) and It does not seem to be working. What I am currently doing is:

for(char c1 : st1ch)
{
    int charint = (int)c1;
    totalcharsum1 = totalcharsum1*charint;
}

..in order to convert a read string from a file (which I converted to an array of chars) to their int counterparts. I assumed and read that (int)"A" etc. would be 1. However, my code does not produce the right result apparently. I believe this is the problem as I can see no other problems. I have found no guide to this problem. Of course my mistake may be elsewhere so Ill post my code below anyway:

import java.io.*;

class ride {

    public static void main(String[] arg) throws IOException{

        BufferedReader reader = new BufferedReader(new FileReader ("ride.in"));
        String st1 = reader.readLine();
        String st2 = reader.readLine();
        int totalcharsum1 = 1;
        int totalcharsum2 = 1;
        char[] st1ch = st1.toCharArray();
        char[] st2ch = st2.toCharArray();

        for(char c1 : st1ch)
        {
            int charint = (int)c1;
            totalcharsum1 = totalcharsum1*charint;
        }
        for(char c2 : st2ch)
        {
            int charint = (int)c2;
            totalcharsum2 = totalcharsum2*charint;
        }
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("ride.out")));
        if(totalcharsum1%47 == totalcharsum2%47)
        {
            out.println("GO");
        }else{
            out.println("STAY");
        }
        out.close();
        System.exit(0);
    }
  }

My questions is how do you convert a capital char to its respective int on the alphabet? Thanks, Sam.

War es hilfreich?

Lösung

You can convert an char to an int in Java by subtracting their absolute ASCII values. Below is a method that returns the product of the integer values of each character in a String (useful for ride.java):

public static int makeNumber(String name) {
        int product = 1;
        //iterate through each character in the String name
        for (int i = 0; i < name.length(); i++) {
            //get the character value
            int charVal = (name.charAt(i) - 'A') + 1; 
            //multiply the product by the character value
            product *= charVal;
        }
        return product;
    }
}

Andere Tipps

Subtract their ASCII values.

char ch = 'X';
int diff = ch -'A';
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top