java hasNext()使用实例解析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java hasNext()使用实例解析

  2021-04-02 我要评论

这篇文章主要介绍了java hasNext()使用实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

编写一段程序实现如果输入的一组数中含非整数数字,输出数字相加的和以及"attention"字符,如果全部是数字便输出数字的和。

程序1:

package mian;
import java.util.Scanner;
public class mian {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);
    int s=0;
    String str=null;
    while(sc.hasNext()){
      if(sc.hasNextInt()){//判断是否是数字
      s+=sc.nextInt();
        
      }else{
        str=sc.next();//不写这句话会导致只会加非数字前数字的和,必须将这个非数字字符串吸收了
      }
        
    }
    System.out.println(s);
    if(str!=null){
      System.out.println("attention");
    }sc.close();
  }

}

程序2:

import java.util.Scanner;
public class Main{
  //return -1: -10(带负号)
  //return 1: +10(带正号)
  //return 0  非数字字符串
  //return 2: 10(不带正负号)

  public static int checkNum(String str){//判断是否是数字串
    if(str.charAt(0)=='-'){
      for(int i=1;i<str.length();i++){
        if(str.charAt(i)-'0'>9||str.charAt(i)-'0'<0){
           return 0;
        }
      }return -1;
         
    }else if(str.charAt(0)=='+'){
      for(int i=1;i<str.length();i++){
        if(str.charAt(i)-'0'>9||str.charAt(i)-'0'<0){
           return 0;
        }
      }return 1;  
    }else{
      for(int i=0;i<str.length();i++){
        if(str.charAt(i)-'0'>9||str.charAt(i)-'0'<0){
           return 0;
        }
      }return 2;    
      
      
    }

}
public static void main(String []args){
  int flag=0,s=0,sum=0;
  Scanner sc = new Scanner(System.in);
  while(sc.hasNext()){
    
   String a=sc.next();
   if(checkNum(a) == 1){
   for(int i=1;i<a.length();i++){
    s=s*10+a.charAt(i)-'0';
   }sum+=s;s=0;
    }else if(checkNum(a) == -1){
      for(int i=1;i<a.length();i++){
        s=s*10+a.charAt(i)-'0';
      }sum+=-s;s=0;
        
    }else if(checkNum(a) == 2){
      for(int i=0;i<a.length();i++){
        s=s*10+a.charAt(i)-'0';       
      }sum+=s;s=0;
        
    }else{
      flag=1;
      //continue;
    }
  }
if(flag==0){
System.out.println(sum);
}else{
System.out.println(sum);
System.out.println("attention");
}

sc.close();

}

}
您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们