我正在尝试获取字符串中的最后两个字符(英寸)和前两个字符(英尺)。因为我尝试了很多东西,有没有我看不到的东西。
高度应该在两组数字之间有一个空格,例如5 10或12 02,所以这就是为什么我要获取某些字符的原因。因此,我可以将它们移到另一个字符串中以将它们添加在一起,因为我想将两个人的高度加在一起,这就是我到目前为止所得到的...
import javax.swing.JOptionPane;
public class TestProgramming
{ //begin class
public static void main(String[] args)
{ // begin main
// ***** variables *****
int h1;
int h2;
String height1 = "0";
String height2 = "0";
String feet1;
String feet2;
String inches1;
String inches2;
String FinalFoot = "0";
String FinalInch = "12";
// ***** input box 1 *****
height1 = JOptionPane.showInputDialog (null, "Please enter the height of the first person in inches.");
// ***** input box 2 *****
height2 = JOptionPane.showInputDialog (null, "Please enter the height of the second person in inches.");
// ***** parse *****
h1 = Integer.parseInt(height1);
h2 = Integer.parseInt(height2);
// ***** integer to string *****
Integer.toString(h1);
Integer.toString(h2);
// ***** taking the feet and inches from the two heights *****
feet1 = h1.substr(0, 1); // subtract the last 2 numbers
inches1 = h1.substr(2, 4); // subtract the first 2 numbers
feet2 = h2.substr(0, 1); // subtract the last 2 numbers
inches2 = h2.substr(2, 4); // subtract the first 2 numbers
如您所见,我遇到了问题:“距离两个高度只有几英尺远”。
最佳答案
尝试以下操作:(请注意,我对输入进行了硬编码,以便在控制台应用程序中进行更轻松的测试)
public static void main(String []args){
// removed the early declarations here. This is C-style, old, unnecessary and makes
// code harder to read
// ***** input box 1 ***** HARCODED - replace with UI call
String height1 = "6 10";
// ***** input box 2 ***** HARCODED - replace with UI call
String height2 = "3 10";
// ***** parse feet and inches from each input *****
String feet1 = height1.substring(0, 1); // get the first digit
String inches1 = height1.substring(2, 4); // get the last 2 digits
String feet2 = height2.substring(0, 1); // get the first digit
String inches2 = height2.substring(2, 4); // get the last 2 digits
// convert parsed string data to their integer counterparts
int f1 = Integer.parseInt(feet1);
int i1 = Integer.parseInt(inches1);
int f2 = Integer.parseInt(feet2);
int i2 = Integer.parseInt(inches2);
// calculate total feet
int totalFeet = f1 + f2 + (i1 + i2) / 12;
// calculate total inches (using modulus operator)
int totalInches = (i1 + i2) % 12;
// and do the output... assuming this is what you want...
System.out.println(totalFeet + " " + totalInches);
}
另外,它是
substring
而不是subtract
或substr
。关于java - 为什么我不能在输入框的两个字符串中得到前两个字符?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19439554/