0
我想弄清楚如何將特定基地中的任何值轉換爲其在不同基地中的相應表示。您將得到一個值,它的基數和該值需要轉換爲.dat文件中每行的值。Java基地轉換程序給定的值,其基數和新基地
的3行中的.dat文件,其中在一條線上的第一個數字是值,隨後它在基地實施例,那麼它需要的基轉換爲:
AB 16 10
我相信我已經想通了,除了如何在鹼如16佔字母值的18。請幫助:
public static void main(String args[]) throws IOException
{
Scanner file = new Scanner(new File("baseConversion.dat"));
//Keep looping while you can still read lines from the file
while (file.hasNextLine())
{
//Read a line from the file -- read it as a string
String line = file.nextLine();
int firstSpace = line.indexOf(" ");
int lastSpace = line.lastIndexOf(' ', line.length());
String oldBase = line.substring(firstSpace + 1, lastSpace);
// Get the new base from the string
int newBase = Integer.parseInt(line.substring(lastSpace + 1));
// Convert from the Old base to base 10
int numberInBase10 = convertToTen(line.substring(0, firstSpace), Integer.parseInt(oldBase));
System.out.println("Converted " + line.substring(0, firstSpace) + " from base " + oldBase + " to " +
numberInBase10 + " in base 10\n");
public static String convert(int numberInBase10, int base)
{
int quotient = numberInBase10/newBase;
int remainder = numberInBase10 % newBase;
if(quotient == 0)
{
return Integer.toString(remainder);
}
else
{
return convert(quotient, newBase) + Integer.toString(remainder);
}
}
// DO THIS Print out results
}
file.close();
}
static int convertToTen(String num, int base)
{
int leng = num.length();
int base10 = 0;
int remainder = 0;
int add = 0;
for(int i = leng-1; i >=0; i--)
{
int intValueForC = 0;
remainder = 0;
char c = num.charAt(leng-i-1);
if(!Character.isDigit(c))
{
intValueForC = c - 55;
}
else
{
intValueForC = c - 48;
}
add +=(intValueForC * Math.pow(base, i));
}
return add;
}
}
它幾乎是除了我想出了我在老問題中要求的部分,現在我有一個新的問題。 – user2880377
沿着這些線:'if(digit> = base){digit ='A'+(digit - base)};'翻譯成16或18個鹼基時。只是一個想法。 –