如果输入非Int值,如何在循环时退出?

时间:2014-03-27 21:00:10

标签: java while-loop

如果输入非 int 值,如何退出循环?

我应该在主课程中这样做吗?

package testing;

//importing java scanner
import java.util.Scanner;


public class Testing {


public static void main(String[] args) {

    //importing scanner for user input
    Scanner input = new Scanner(System.in);

    //variable for how many positions to shift indexes in array
    int shift;

    //Object for Shifter, passing 20 as parameter
    Shifter numbers = new Shifter(20);

    //Call Display method
    numbers.display();

    //how many positions to shift
    System.out.print("\nYou want to shift how many positions? ");

    //Assigning user input to shift variable
    shift = input.nextLine();

    numbers.shift();
}

现在换班:

package Testing;
import java.util.*;

public class Shifter 
{
private int numbers[]; 

Shifter(int totalSize) 
{   

    int index = 1;  

     numbers = new int[totalSize];            

    //Loop for assigning values to array indexes
    for(int i= 0; i < data.length; i++)
    {   
        data[i]= firstIndex;
        firstIndex++;
    }

}

public void shift(int position) 
{   
    //method variable assigned value of pos parameter
    int shiftNum = position;     
    //Array to hold new arrangement of elements
    int dataHolder[] = new int[numbers.length];

    **//I want to put a while loop here that will exit the loop when a letter is entered**
    **//I tried using .isNaN but can't get it to work

    while()
    {

    if(shiftNum > 0)
        {


         }

    }

}

2 个答案:

答案 0 :(得分:-1)

你试过这个:

while (...) {
    String inputString = "..";
    try {
        int i = Integer.parseInt(inputString);   // try to parse the input string as an integer
    } catch (NumberFormatException e) {
        break;     // not an integer, exiting loop
    }
}

或者您可能也对Scanner.nextInt()感兴趣:

while (...) {
    if (input.hasNextInt()) {
        int i = input.nextInt();
    } else {
        break;     // not an integer, exiting loop
    }
}

答案 1 :(得分:-1)

代码是否有效?根据规范Scanner.nextLine返回一个字符串。

因此,如果您将其更改为shift = input.nextInt();。那应该是为了达到目的