if else语句中的字符串索引超出范围异常

时间:2016-04-29 08:14:00

标签: java

问题代码如下,如果您需要整个主要方法来帮助我,请询问。代码符合但不按预期运行。如果数字超出边界/大于源文本的最后位置(我是用户输入的字符串),我试图使代码报告返回感叹号,因此无法预定义长度。例外是'StringIndexOutOfBoundsException'

TDLR num是一个int,sourcetext是一个字符串,两者都是输入。例外:当代码输出'!'时代替。

import java.util.Scanner; 

public class Temp {

    public static void main(String[] args) { 

        Scanner sc;
        int  result, num= 0, end = -2, temp, infolost, count;
        String word, sourcetext, answer, space= " ";
        String sourcetext2, temp2;
        char input, result2, chalost;
        sc = new Scanner(System.in);

        System.out.println("please enter sourcetext");
        sourcetext = sc.nextLine(); // user inputs source text
        sourcetext = sourcetext.toLowerCase(); // converts sourcetext into lowercase                      
        System.out.print("Would you like to 1 encrypt, or 2 decrypt?");
        answer = sc.next(); // user inputs choice

        if (answer.equals("1")||(answer.equals("encrypt"))) {

            System.out.println("Please enter at least one word to encrypt");
            word = sc.next();   // user inputs one word

            for (int i= 0; i < word.length(); i++) { 
                temp = sourcetext.indexOf(word.charAt(i)); // uses index to convert char  positions int num
                System.out.print(space + temp + space);          
            }
            System.out.print(space + end); 
        }
        else if (answer.equals("2")||(answer.equals("decrypt"))) {

            System.out.println("Please enter digits, with one space between each. End  with -2");                 
            while (num > -2) {  
                num = sc.nextInt(); // num to decrypt
                if (num > -2) {      
                    result2 = sourcetext.charAt(num); // num converted into characters
                    System.out.print(result2);
                } else if (num > sourcetext.length()) {
                     System.out.print("!");
                } else if (num<0) {
                     System.out.print("end");
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

试试这样:

int stringLength = sourcetext.length();

if (num > stringLength) { 
    System.out.print("!");
} 
else if (num<0) {
    System.out.print("end");
}

答案 1 :(得分:0)

这可能导致<!DOCTYPE html> <html> <head> <script src="http://maps.google.com/maps/api/js?sensor=false&.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> </head> <body> <div id="googleMap" style="width:500px;height:500px;"></div> Lat: <input type="text" id="lat"><br> Lng: <input type="text" id="lng"> <p id="results">result</p> <script type="text/javascript"> function initialize() { var myLatlng = new google.maps.LatLng(41.015137,28.979530); var myOptions = { zoom: 10, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("googleMap"), myOptions); addMarker(myLatlng, 'Default Marker', map); map.addListener('click',function(event) { addMarker(event.latLng, 'Click Generated Marker', map); }); } function addMarker(latlng,title,map) { var coords = []; var marker = new google.maps.Marker({ position: latlng, map: map, title: title, draggable:true }); marker.addListener('drag',function(event) { $('#lat').val(event.latLng.lat()) ; $('#lng').val(event.latLng.lng()) ; }); marker.addListener('dragend',function(event) { $('#lat').val(event.latLng.lat()) ; $('#lng').val(event.latLng.lng()) ; coords.push(event.latLng.lat()); coords.push(event.latLng.lng()); $("#results").append('<div>'+JSON.stringify(coords)+'</div>'); coords = []; }); } initialize(); </script> </body></html> 异常 - 因为IndexOutOfBounds大于-1 - 但仍然超出界限......

-2

编辑:除非用户输入为if (num > -2){ result2 = sourcetext.charAt(num); // num converted into characters System.out.print(sourcetext.indexOf(num)); } - 第一个-2 - 语句将始终运行...您可能需要在那里重新处理逻辑。

Edit2:如果ifnum -1,则会导致sourcetext.charAt(num);。做点什么

IndexOutOfBounds