从字符串打印数字 [英] Print numbers from string

查看:118
本文介绍了从字符串打印数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打印用户输入的数字的代码,但是当用户输入字符串和数字时,它会给出错误



code that prints the numbers that user enters but when the user enters string and numbers it gives the error

引用:

线程main中的异常java.lang.NumberFormatException:对于输入字符串:java

Exception in thread "main" java.lang.NumberFormatException: For input string: "java"







import java.io.BufferedReader;
import java.io.*; 

// Read a string from console using a BufferedReader. 
 
class StringReader { 
  public static void main(String args[]) throws IOException 
  { 
    // create a BufferedReader using System.in 
    BufferedReader br = new BufferedReader(new 
                            InputStreamReader(System.in));
    
    
    String str;
    System.out.println("Enter lines of text."); 
    System.out.println("Enter 'stop' to quit."); 
    do {       
      str = br.readLine(); 
      int value = Integer.parseInt(str);  
      System.out.println(str); 
      System.out.println(value);
    } while(!str.equals("stop")); 
  } 
}





结果是

输入文字行。

输入'stop'退出。



45

45

number是42

线程main中的异常java.lang.NumberFormatException:对于输入字符串:number is 42

at java.lang.NumberFormatException.forInputString(NumberFormatException。 java:65)

at java.lang.Integer.parseInt(Integer.java:580)

at java.lang.Integer.parseInt(Integer.java:615)

in inout.StringReader.main(StringReader.java:21)

C:\ Users \Admin \ AppData \ Local \ NetBeans \Cache \\ \\ 8..2 \ executor-snippets\run.xml:53:Java返回:1









当用户键入45时程序打印45,当用户输入'数字是42'然后有错误时,会希望它从字符串中取数字并打印数字与

Integer.parseInt(str);



我尝试过:



更改了代码并搜索错误



the result is
Enter lines of text.
Enter 'stop' to quit.
45
45
45
number is 42
Exception in thread "main" java.lang.NumberFormatException: For input string: "number is 42"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at inout.StringReader.main(StringReader.java:21)
C:\Users\Admin\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1




when the user types 45 the program prints 45, when user enters 'number is 42' then there is error, would want it to take number from string and print just the number with
Integer.parseInt(str);

What I have tried:

changed code and searched for errors

推荐答案

这与我昨天在 Java.lang.numberformatesception:输入字符串: [ ^ ]。您不能将非数字字符解析为数字,这没有任何意义。
This is exactly the same issue that I expalined to you yesterday at Java.lang.numberformatesception: for input string: ""[^]. You cannot parse non-numeric characters as a number, it makes no sense.


这篇关于从字符串打印数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆