返回

java-嵌套while循环,带有scanner int和sentinel值

发布时间:2022-03-02 00:54:03 373
# php

所以我现在有点纠结于此。我有一个程序,我试图运行两个循环,我运行的第一个循环将尝试一些东西,直到我输入一个“a”;“结束”;除了我的支票条件。

我的下一个循环是尝试读入(扫描仪输入)来检查它们是否有哨兵值(-1),并收集它们并对其进行一些处理。比如添加,然后在我的程序完成后打印出来。以读入的输入为例:尝试1:(-6)5479-1,尝试2:-9694-1。数字之间有空格。

该代码一直工作到第“行”;int UserValue=YN。nextInt()&引用;此时,它会抛出一个错误,比如异常,但不确定原因是什么?我永远无法插入整数。

我试着用不同的名字创建一个内部扫描仪,看看它是否是我的扫描仪,但同样的事情发生了。在网上阅读有关扫描仪的文章时,嵌入式扫描仪是一个大禁忌。

好的,谢谢你的阅读,如果你有任何建议,我会重新考虑,任何意见都将不胜感激!!谢谢

import java.util.Scanner;  // Importing the java package for reading from users (me) 

公共类InputScannerWhile{

public static void main(String args[] ) { 
    
    Scanner  YN = new Scanner(System.in) ; // create new scanner to grab scanner data       
    System.out.println("Retry: Enter Y/N " ); // enter y or n
    String retry = "y" ; // Skip the first run on the code, this will jump right into the while loop    
    
    
    while(retry.equalsIgnoreCase("Y")) { //  loop for retry or not code  
        
            String IntList = " " ;              /// output string is initially empty 
            int SumValues = 0 ;                 /// add positive vales 
                            
            System.out.println("Enter Positive integers (-1 to quit) ") ;   // Print prompt for user to
            int UserValue = YN.nextInt() ; 
            
            while(UserValue != (-1)) {
            
                if(UserValue == (-1)) {
                        break ; 
                                       } // Exit the 1st IF condition for -1 value  
                if(UserValue != (-1) )  {
                    
                    SumValues += UserValue ; 
                    IntList += IntList + UserValue + " " ;  
                    System.out.println("Entered numbers: " + IntList );
                    System.out.println("The Added Values: " +SumValues);
                                        }  
                
            } // Exit the second while loop                 */          
                                            
        System.out.print("Retry: Y/N " ) ;                              // enter y or n to continue 
        retry = YN.next() ;                                             // Retry variable
        
                                            } // Exit the Outside while loop
    System.out.println("!!! Program terminated !!!") ; 
                                        }
                        } //public class bracket
error details below***
    Retry: Enter Y/N 
    y
    Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at  java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at InputScannerWhile.main(InputScannerWhile.java:18)
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像