String输入到整数字段的InputMismatchException

时间:2015-08-27 21:07:57

标签: java java.util.scanner inputmismatchexception

我在将非整数输入整数字段时遇到问题。我只是采取预防措施,以便如果另一个人使用/工作我的计划他们不会得到这个InputMismatchException

当我在input变量中输入一个非数字字符时,我收到上述错误。有没有什么方法可以弥补这个问题,就像字符串中NullPointerException可以做的那样?

此代码经过编辑,只是为了包含导致问题的相关部分。

import java.util.Scanner;

class MyWorld {

public static void main(String[] args) {

   Scanner user_input = new Scanner(System.in);

   int input = 0;   

   System.out.println("What is your age? : ");
   input = user_input.nextInt();
   System.out.println("You are: " +input+ " years old");

  }

}

4 个答案:

答案 0 :(得分:0)

您可以添加try-catch块:

class theTableView(generic.TemplateView):
    template_name = 'adminTable.html'

    def get_template_names(self):
        if self.request.user.is_superuser:
            template_name = 'goodAdminTable.html'
        elif self.request.user.is_authenticated:
            template_name = 'goodUserTable'
        else:
            template_name = self.template_name
        return [template_name]

如果您想要让用户输入另一个try { input = user_input.nextInt(); } catch (InputMismatchException exception) { //here you can catch that exception, so program will not stop System.out.println("Integers only, please."); //this is a comment scanner.nextLine(); //gives a possibility to try giving an input again } ,您可以创建一个布尔变量并进行NSString *yourFileURL=@"http://yourFileURL.zip"; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:yourFileURL]]; AFURLConnectionOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; NSString *cacheDir = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *filePath = [cacheDir stringByAppendingPathComponent: @"youFile.zip"]; operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO]; [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { //show here your downloading progress if needed }]; [operation setCompletionBlock:^{ NSLog(@"File successfully downloaded"); }]; [operation start]; 循环来重复它。如下:

import java.util.Scanner;

class MyWorld {

public static void main(String[] args) {

   Scanner user_input = new Scanner(System.in);

   int input = 0;   

   System.out.println("What is your age? : ");

   try{
       input = user_input.nextInt();
   }catch(InputMisMatchException ex)
       System.out.println("An error ocurred");
   }

   System.out.println("You are: " +input+ " years old");

  }
}

答案 1 :(得分:0)

使用hasNextInt()进行测试。

Scanner user_input = new Scanner(System.in);
System.out.println("What is your age?");
if (user_input.hasNextInt()) {
    int input = user_input.nextInt();
    System.out.println("You are " + input + " years old");
} else {
    System.out.println("You are a baby");
}

答案 2 :(得分:-1)

这是一个try-catch块。如果你想确保不使程序流停止,你需要使用它。

public class BCollectionConverter:IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values == null)
            return null;
        var bCollection = (values[0] as ObservableCollection<String>);
        var aSelectedItem = (values[1] as String);

        if (aSelectedItem == null)
            return null;
        var returnedCollection = new ObservableCollection<String>();
        foreach (var value in bCollection)
        {
            if (value.StartsWith(aSelectedItem))
            {
                returnedCollection.Add(value);
            }
        }
        return returnedCollection;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

答案 3 :(得分:-1)

使用Scanner's next()方法获取数据而不是使用nextInt()。然后使用int input = Integer.parseInt(inputString);将其解析为整数 如果parseInt()方法不是int,则抛出NumberFormatException,你可以相应地处理它。