在JAVA中以字符串作为输入时的问题。

huangapple go评论72阅读模式
英文:

Problem in taking a string as an Input in JAVA

问题

以下是翻译好的代码部分:

import java.util.*;

public class cnPrac6 {
    static String classFromDecimal(String str) {

        int index = str.indexOf('.');
        String ipsub = str.substring(0, index);
        int ip = Integer.parseInt(ipsub);
        if (ip >= 1 && ip <= 126)
            return "A";
        else if (ip >= 128 && ip <= 191)
            return "B";
        else if (ip >= 192 && ip <= 223)
            return "C";
        else if (ip >= 224 && ip <= 239)
            return "D";
        else
            return "E";
    }

    static String classFromBinary(String str) {

        if (str.charAt(0) == '0')
            return "A";
        else if (str.charAt(0) == '1' && str.charAt(1) == '0')
            return "B";
        else if (str.charAt(0) == '1' && str.charAt(1) == '1' && str.charAt(2) == '0')
            return "C";
        else if (str.charAt(0) == '1' && str.charAt(1) == '1' && str.charAt(2) == '1' && str.charAt(3) == '0')
            return "D";
        else if (str.charAt(0) == '1' && str.charAt(1) == '1' && str.charAt(2) == '1' && str.charAt(3) == '1' && str.charAt(4) == '1')
            return "E";
        else
            return "Error wrong address";
    }

    static void seprate(String str, String ipClass) {
        String network = "", host = "";

        if (ipClass.equals("A")) {
            int index = str.indexOf('.');
            network = str.substring(0, index);
            host = str.substring(index + 1, str.length());
        } else if (ipClass.equals("B")) {
            int index = -1;
            int dot = 0;
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == '.') {
                    dot += 1;
                    if (dot == 2) {
                        index = i;
                        break;
                    }
                }
            }
            network = str.substring(0, index);
            host = str.substring(index + 1, str.length());
        } else if (ipClass.equals("C")) {
            int index = -1;
            int dot = 0;
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == '.') {
                    dot += 1;
                    if (dot == 3) {
                        index = i;
                        break;
                    }
                }
            }
            network = str.substring(0, index);
            host = str.substring(index + 1, str.length());
        } else if (ipClass.equals("D") || ipClass.equals("E")) {
            System.out.println("No network or host ID");
            return;
        }
        System.out.println("Network ID is " + network);
        System.out.println("Host ID is " + host);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String ipClassD = "";
        String ipClassB = "";
        System.out.print("In which category you address is: \n 1. Decimal \n 2. Binary \n");
        int choice = sc.nextInt();
        sc.nextLine(); // Consume newline
        System.out.print("Enter your address: ");
        String str = sc.nextLine();
        System.out.print("\n");

        switch (choice) {
            case 1:
                ipClassD = classFromDecimal(str);
                System.out.println("Given IP address belongs to Class " + ipClassD);
                seprate(str, ipClassD);
                break;
            case 2:
                ipClassB = classFromBinary(str);
                System.out.println("Given IP address belongs to Class " + ipClassB);
                seprate(str, ipClassB);
                break;
            default:
                System.out.println("Enter correct option");
        }
    }
}

以上是你提供的代码的翻译部分,已经从英文翻译成中文。如果有其他需要翻译的部分,请继续提供。

英文:

I am trying to create a program for taking ad IP address as input and give Class, netID, and hostID as output.
I am having a problem in taking IP address as String input in the program.

This is the snap of the error i am getting

Error:

Exception in thread &quot;main&quot; java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 0
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3756)
at java.base/java.lang.String.substring(String.java:1902)
at cnPrac6.classFromDecimal(cnPrac6.java:7)
at cnPrac6.main(cnPrac6.java:94)

Given below is the part of code i am getting error in:

public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
String ipClassD = &quot;&quot;;
String ipClassB = &quot;&quot;;
System.out.print(&quot;In which category you address is: \n 1. Decimal \n 2. Binary \n&quot;);
int choice = sc.nextInt();
System.out.print(&quot;Enter your address: &quot;);  
String str= sc.nextLine();
System.out.print(&quot;\n&quot;);
switch (choice) {
case 1:
ipClassD = classFromDecimal(str); 
System.out.println(&quot;Given IP address belings to Class &quot;+ipClassD);
seprate(str,ipClassD);
break;

Following the the full code

import java.util.*;

public class cnPrac6 {
	    static String classFromDecimal(String str){ 

	        int index = str.indexOf(&#39;.&#39;);
	        String ipsub = str.substring(0,index); 
	        int ip = Integer.parseInt(ipsub); 
	        if (ip&gt;=1 &amp;&amp; ip&lt;=126) 
	            return &quot;A&quot;; 
	        else if (ip&gt;=128 &amp;&amp; ip&lt;=191) 
	            return &quot;B&quot;; 
	        else if (ip&gt;=192 &amp;&amp; ip&lt;223) 
	            return &quot;C&quot;; 
	        else if (ip &gt;=224 &amp;&amp; ip&lt;=239) 
	            return &quot;D&quot;; 
	        else
	            return &quot;E&quot;; 
	    } 

	    static String classFromBinary(String str){ 
 
	        if (str.charAt(0)==&#39;0&#39;) 
	            return &quot;A&quot;; 
	        else if (str.charAt(0)==&#39;1&#39; &amp;&amp; str.charAt(1)==&#39;0&#39;) 
	            return &quot;B&quot;; 
	        else if (str.charAt(0)==&#39;1&#39; &amp;&amp; str.charAt(1)==&#39;1&#39; &amp;&amp; str.charAt(2)==&#39;0&#39;) 
	            return &quot;C&quot;;
	        else if (str.charAt(0)==&#39;1&#39; &amp;&amp; str.charAt(1)==&#39;1&#39; &amp;&amp; str.charAt(2)==&#39;1&#39; &amp;&amp; str.charAt(3)==&#39;0&#39;) 
	            return &quot;D&quot;;
	        else if (str.charAt(0)==&#39;1&#39; &amp;&amp; str.charAt(1)==&#39;1&#39; &amp;&amp; str.charAt(2)==&#39;1&#39; &amp;&amp; str.charAt(3)==&#39;1&#39; &amp;&amp; str.charAt(4)==&#39;1&#39;) 
	            return &quot;E&quot;;
	        else return &quot;Error wrong address&quot;;
	    }
	    
	    static void seprate(String str, String ipClass){  
	        String network = &quot;&quot;, host = &quot;&quot;; 
	  
	        if(ipClass == &quot;A&quot;){ 
	            int index = str.indexOf(&#39;.&#39;); 
	            network = str.substring(0,index); 
	            host = str.substring(index+1,str.length()); 
	        }
	        else if(ipClass == &quot;B&quot;){      
	            int index = -1;  
	            int dot = 0;  
	            for(int i=0;i&lt;str.length();i++){ 
	                if(str.charAt(i)==&#39;.&#39;){ 
	                    dot +=1; 
	                    if(dot==2){ 
	                        index = i; 
	                        break; 
	                    } 
	                } 
	            } 
	            network = str.substring(0,index); 
	            host = str.substring(index+1,str.length()); 
	        }
	        else if(ipClass == &quot;C&quot;){ 
	            int index = -1;  
	            int dot = 0;  
	            for(int i=0;i&lt;str.length();i++){ 
	                if(str.charAt(i)==&#39;.&#39;){ 
	                    dot +=1; 
	                    if(dot==3){ 
	                        index = i; 
	                        break;                      
	                    } 
	                } 
	            } 
	            network = str.substring(0,index); 
	            host = str.substring(index+1,str.length()); 
	        }
	        else if(ipClass == &quot;D&quot; || ipClass == &quot;E&quot;){ 
	            System.out.println(&quot;No network or host ID&quot;); 
	            return; 
	        } 
	        System.out.println(&quot;Network ID is &quot;+network); 
	        System.out.println(&quot;Host ID is &quot;+host); 
	    } 
	    
	    public static void main(String[] args) {
	    	Scanner sc= new Scanner(System.in);
	    	String ipClassD = &quot;&quot;;
	    	String ipClassB = &quot;&quot;;
	    	System.out.print(&quot;In which category you address is: \n 1. Decimal \n 2. Binary \n&quot;);
	    	int choice = sc.nextInt();
	    	System.out.print(&quot;Enter your address: &quot;);  
	    	String str= sc.nextLine();
	    	System.out.print(&quot;\n&quot;);
	    	
	    	switch (choice) {
	    	  case 1:
	  	    	  ipClassD = classFromDecimal(str); 
		          System.out.println(&quot;Given IP address belings to Class &quot;+ipClassD);
		          seprate(str,ipClassD);
	    	    break;
	    	  case 2:
	    		  ipClassB = classFromBinary(str); 
		          System.out.println(&quot;Given IP address belings to Class &quot;+ipClassB);
		          seprate(str,ipClassB);
		        break; 
	    	  default:
	    	    System.out.println(&quot;Enter correct option&quot;);
	    	}
	    } 
	} 

答案1

得分: 1

问题在于获取输入。当你使用 sc.nextInt() 时,它会获取一个整数输入,直到遇到一个空格为止。如果遇到空格,它会停止扫描输入。

在扫描整数之后,扫描器仍然在同一行,直到我们读取整行为止,它不会跳到下一行。

因此,在获取整数输入后,使用 sc.nextLine() 扫描整行。

这里是代码示例:

int choice = sc.nextInt();                 // 获取整数
sc.nextLine();                             // 跳过这一行
System.out.print("请输入你的地址:");  // 扫描器在下一行
String str = sc.nextLine();                 // 读取IP地址
英文:

The problem is in getting input.When you are using sc.nextInt(),it takes an integer input until encountering a space.If it encounters space,it stops scanning input.

After scanning integer , still scanner is in same line ,it will not go to next line until we read the entire line.

So, scan the entire line using sc.nextLine() after getting integer input.

Here, you can find code.

int choice = sc.nextInt();                 // getting integer
sc.nextLine();                             // passing this line
System.out.print(&quot;Enter your address: &quot;);  // scanner is in next Line
String str= sc.nextLine();                 // reading the ip address

答案2

得分: 0

失败的原因是代码 String str= sc.nextLine() 正在消耗前一个输入中挂起的换行符(当您按下<kbd>Enter</kbd>)。对于前一个输入,您正在使用 sc.nextInt(),它会消耗整数值而不是换行符。

int choice = sc.nextInt();

替换为

int choice = Integer.parseInt(sc.nextLine());
英文:

The reason why it is failing is that the code, String str= sc.nextLine() is consuming the dangling new line character (when you press <kbd>Enter</kbd>) from the previous input. For the previous input, you are using sc.nextInt() which is consuming the integer value but not newline character.

Replace

int choice = sc.nextInt();

with

int choice = Integer.parseInt(sc.nextLine());

huangapple
  • 本文由 发表于 2020年9月19日 16:17:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63966695.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定