如何键入字符串以结束Java中的整数扫描过程

时间:2015-11-30 13:16:58

标签: java java.util.scanner

我想使用Scanner扫描任意数量的整数然后得到平均值。在我停止之前,我想输入“END”。

以下代码包含: 线程“main”中的异常java.util.InputMismatchException 错误。那是因为我扫描字符串而不是int类型。

我该如何解决这个问题?

由于

public static int scanaverage()
{
System.out.println("Enter any number, type 'END' to exit");
Scanner input = new Scanner(System.in);
int total=0; 
int count = 0;

while (!(input.nextLine().equals("END")))
{
total += input.nextInt();
count += 1;
}
return total / count;
}

3 个答案:

答案 0 :(得分:2)

您可以扫描整行并检查该行是否是这样的数字

#include <opencv2/opencv.hpp>
#define CST_PI 3.1415926535897932384626433832795

// Random rotation matrix uniformly sampled from SO3 (see "Fast random rotation matrices" by J.Arvo)
cv::Matx<double,3,3> get_random_rotmat()
{
    double theta1 = 2*CST_PI*cv::randu<double>();
    double theta2 = 2*CST_PI*cv::randu<double>();
    double x3 = cv::randu<double>();
    cv::Matx<double,3,3> R(std::cos(theta1),std::sin(theta1),0,-std::sin(theta1),std::cos(theta1),0,0,0,1);
    cv::Matx<double,3,1> v(std::cos(theta2)*std::sqrt(x3),std::sin(theta2)*std::sqrt(x3),std::sqrt(1-x3));
    return -1*(cv::Matx<double,3,3>::eye()-2*v*v.t())*R;
}

cv::Matx<double,4,1> rotmat2quatwxyz(const cv::Matx<double,3,3> &R)
{
    // Implementation from Ceres 1.10
    const double trace = R(0,0) + R(1,1) + R(2,2);
    cv::Matx<double,4,1> quat_wxyz;
    if (trace >= 0.0) {
        double t = sqrt(trace + 1.0);
        quat_wxyz(0) = 0.5 * t;
        t = 0.5 / t;
        quat_wxyz(1) = (R(2,1) - R(1,2)) * t;
        quat_wxyz(2) = (R(0,2) - R(2,0)) * t;
        quat_wxyz(3) = (R(1,0) - R(0,1)) * t;
    } else {
        int i = 0;
        if (R(1, 1) > R(0, 0))
            i = 1;
        if (R(2, 2) > R(i, i))
            i = 2;

        const int j = (i + 1) % 3;
        const int k = (j + 1) % 3;
        double t = sqrt(R(i, i) - R(j, j) - R(k, k) + 1.0);
        quat_wxyz(i + 1) = 0.5 * t;
        t = 0.5 / t;
        quat_wxyz(0)     = (R(k,j) - R(j,k)) * t;
        quat_wxyz(j + 1) = (R(j,i) + R(i,j)) * t;
        quat_wxyz(k + 1) = (R(k,i) + R(i,k)) * t;
    }
    // Check that the w element is positive
    if(quat_wxyz(0)<0)
        quat_wxyz *= -1;    // quat and -quat represent the same rotation, but to make quaternion comparison easier, we always use the one with positive w
    return quat_wxyz;
}

cv::Matx<double,4,1> apply_quaternion_trick(const unsigned int item_permuts[4], const int sign_flips[4], const cv::Matx<double,4,1>& quat_wxyz)
{
    // Flip the sign of the x and z components
    cv::Matx<double,4,1> quat_flipped(sign_flips[0]*quat_wxyz(item_permuts[0]),sign_flips[1]*quat_wxyz(item_permuts[1]),sign_flips[2]*quat_wxyz(item_permuts[2]),sign_flips[3]*quat_wxyz(item_permuts[3]));
    // Check that the w element is positive
    if(quat_flipped(0)<0)
        quat_flipped *= -1; // quat and -quat represent the same rotation, but to make quaternion comparison easier, we always use the one with positive w
    return quat_flipped;
}

void detect_quaternion_trick(const cv::Matx<double,4,1> &quat_regular, const cv::Matx<double,4,1> &quat_flipped, unsigned int item_permuts[4], int sign_flips[4])
{
    if(abs(quat_regular(0))==abs(quat_flipped(0))) {
        item_permuts[0]=0;
        sign_flips[0] = (quat_regular(0)/quat_flipped(0)>0 ? 1 : -1);
    }
    else if(abs(quat_regular(0))==abs(quat_flipped(1))) {
        item_permuts[1]=0;
        sign_flips[1] = (quat_regular(0)/quat_flipped(1)>0 ? 1 : -1);
    }
    else if(abs(quat_regular(0))==abs(quat_flipped(2))) {
        item_permuts[2]=0;
        sign_flips[2] = (quat_regular(0)/quat_flipped(2)>0 ? 1 : -1);
    }
    else if(abs(quat_regular(0))==abs(quat_flipped(3))) {
        item_permuts[3]=0;
        sign_flips[3] = (quat_regular(0)/quat_flipped(3)>0 ? 1 : -1);
    }
    if(abs(quat_regular(1))==abs(quat_flipped(0))) {
        item_permuts[0]=1;
        sign_flips[0] = (quat_regular(1)/quat_flipped(0)>0 ? 1 : -1);
    }
    else if(abs(quat_regular(1))==abs(quat_flipped(1))) {
        item_permuts[1]=1;
        sign_flips[1] = (quat_regular(1)/quat_flipped(1)>0 ? 1 : -1);
    }
    else if(abs(quat_regular(1))==abs(quat_flipped(2))) {
        item_permuts[2]=1;
        sign_flips[2] = (quat_regular(1)/quat_flipped(2)>0 ? 1 : -1);
    }
    else if(abs(quat_regular(1))==abs(quat_flipped(3))) {
        item_permuts[3]=1;
        sign_flips[3] = (quat_regular(1)/quat_flipped(3)>0 ? 1 : -1);
    }
    if(abs(quat_regular(2))==abs(quat_flipped(0))) {
        item_permuts[0]=2;
        sign_flips[0] = (quat_regular(2)/quat_flipped(0)>0 ? 1 : -1);
    }
    else if(abs(quat_regular(2))==abs(quat_flipped(1))) {
        item_permuts[1]=2;
        sign_flips[1] = (quat_regular(2)/quat_flipped(1)>0 ? 1 : -1);
    }
    else if(abs(quat_regular(2))==abs(quat_flipped(2))) {
        item_permuts[2]=2;
        sign_flips[2] = (quat_regular(2)/quat_flipped(2)>0 ? 1 : -1);
    }
    else if(abs(quat_regular(2))==abs(quat_flipped(3))) {
        item_permuts[3]=2;
        sign_flips[3] = (quat_regular(2)/quat_flipped(3)>0 ? 1 : -1);
    }
    if(abs(quat_regular(3))==abs(quat_flipped(0))) {
        item_permuts[0]=3;
        sign_flips[0] = (quat_regular(3)/quat_flipped(0)>0 ? 1 : -1);
    }
    else if(abs(quat_regular(3))==abs(quat_flipped(1))) {
        item_permuts[1]=3;
        sign_flips[1] = (quat_regular(3)/quat_flipped(1)>0 ? 1 : -1);
    }
    else if(abs(quat_regular(3))==abs(quat_flipped(2))) {
        item_permuts[2]=3;
        sign_flips[2] = (quat_regular(3)/quat_flipped(2)>0 ? 1 : -1);
    }
    else if(abs(quat_regular(3))==abs(quat_flipped(3))) {
        item_permuts[3]=3;
        sign_flips[3] = (quat_regular(3)/quat_flipped(3)>0 ? 1 : -1);
    }
}

int main(int argc, char **argv)
{
    cv::Matx<double,3,3> M_xflip(-1,0,0,0,1,0,0,0,1);
    cv::Matx<double,3,3> M_yflip(1,0,0,0,-1,0,0,0,1);
    cv::Matx<double,3,3> M_zflip(1,0,0,0,1,0,0,0,-1);

    // Let the user choose the configuration
    char im,om;
    std::cout << "Enter the axis (x,y,z) along which input ref is flipped:" << std::endl;
    std::cin >> im;
    std::cout << "Enter the axis (x,y,z) along which output ref is flipped:" << std::endl;
    std::cin >> om;
    cv::Matx<double,3,3> M_iflip,M_oflip;
    if(im=='x') M_iflip=M_xflip;
    else if(im=='y') M_iflip=M_yflip;
    else if(im=='z') M_iflip=M_zflip;
    if(om=='x') M_oflip=M_xflip;
    else if(om=='y') M_oflip=M_yflip;
    else if(om=='z') M_oflip=M_zflip;

    // Generate random quaternions until we find one where no two elements are equal
    cv::Matx<double,3,3> R;
    cv::Matx<double,4,1> quat_regular,quat_flipped;
    do {
        R = get_random_rotmat();
        quat_regular = rotmat2quatwxyz(R);
    } while(quat_regular(0)==quat_regular(1) || quat_regular(0)==quat_regular(2) || quat_regular(0)==quat_regular(3) ||
            quat_regular(1)==quat_regular(2) || quat_regular(1)==quat_regular(3) ||
            quat_regular(2)==quat_regular(3));

    // Determine and display the appropriate quaternion trick
    quat_flipped = rotmat2quatwxyz(M_oflip*R*M_iflip);
    unsigned int item_permuts[4]={0,1,2,3};
    int sign_flips[4]={1,1,1,1};
    detect_quaternion_trick(quat_regular,quat_flipped,item_permuts,sign_flips);
    char str_quat[4]={'w','x','y','z'};
    std::cout << std::endl << "When iref is flipped along the " << im << "-axis and oref along the " << om << "-axis:" << std::endl;
    std::cout << "resulting_quat=[" << (sign_flips[0]>0?"":"-") << str_quat[item_permuts[0]] << ","
                                    << (sign_flips[1]>0?"":"-") << str_quat[item_permuts[1]] << ","
                                    << (sign_flips[2]>0?"":"-") << str_quat[item_permuts[2]] << ","
                                    << (sign_flips[3]>0?"":"-") << str_quat[item_permuts[3]] << "], where initial_quat=[w,x,y,z]" << std::endl;

    // Test this trick on several random rotation matrices
    unsigned int n_errors = 0, n_tests = 10000;
    std::cout << std::endl << "Performing " << n_tests << " tests on random rotation matrices:" << std::endl;
    for(unsigned int i=0; i<n_tests; ++i) {

        // Get a random rotation matrix and the corresponding quaternion
        cv::Matx<double,3,3> R = get_random_rotmat();
        cv::Matx<double,4,1> quat_regular = rotmat2quatwxyz(R);
        // Get the quaternion corresponding to the flipped coordinate frames, via the sign trick and via computation on rotation matrices
        cv::Matx<double,4,1> quat_tricked = apply_quaternion_trick(item_permuts,sign_flips,quat_regular);
        cv::Matx<double,4,1> quat_flipped = rotmat2quatwxyz(M_oflip*R*M_iflip);
        // Check that both results are identical
        if(cv::norm(quat_tricked-quat_flipped,cv::NORM_INF)>1e-6) {
            std::cout << "Error (idx=" << i << ")!"
                      << "\n   quat_regular=" << quat_regular.t()
                      << "\n   quat_tricked=" << quat_tricked.t()
                      << "\n   quat_flipped=" << quat_flipped.t() << std::endl;
            ++n_errors;
        }
    }
    std::cout << n_errors << " errors on " << n_tests << " tests." << std::endl;
    system("pause");
    return 0;
}

答案 1 :(得分:1)

异常是由于获取一个数字的两次读取操作,例如 将输入视为

1

2

3

END

调试:

while循环条件input.nextLine()将获取1 然后input.nextInt()将获取2 while循环条件input.nextLine()将获取3 然后input.nextInt()将获取END - &gt;这将抛出InputMismatchException

希望波纹管代码能够正常工作,但任何非int输入都会破坏循环的部分

public static int scanaverage()
{
System.out.println("Enter any number, type 'END' to exit");
Scanner input = new Scanner(System.in);
int total=0; 
int count = 0;

while (input.hasNextInt()))
{
total += input.nextInt();
count += 1;
}
return total / count;
}

答案 2 :(得分:0)

您可以按如下方式添加try catch块。

public static int scanaverage()
{
  System.out.println("Enter any number, type 'END' to exit");
  Scanner input = new Scanner(System.in);
  int total=0; 
  int count = 0;

  while (!(input.nextLine().equals("END")))
  {
   try{
    total += input.nextInt();
    count += 1;
    }catch(InputMismatchException e){

    }
  }
  return total / count;
}

我没有测试过。