How to use java Scanner

Asked 2 years ago, Updated 2 years ago, 27 views

We are having a hard time using Java scanner.

Other examples work fine when solving this problem An error occurs when you enter Example 3. What is the cause of the error?

Example 3 Error message when typing... Can anyone tell me how to solve it?ㅜㅜ/

java

2022-09-22 20:42

1 Answers

You used the substring function incorrectly.

Below is a string function circle, but if endIndex is not given, the string from beginindex to the end of the original string is extracted.

public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)

If you give the endIndex as shown below, it will work as you intended.

Scanner sc = new Scanner(System.in);

int n,i,sum=0;
String str,ch;

n=sc.nextInt();
str=sc.next();
System.out.println(str);
for(i=0;i<n;i++)
{
    ch=str.substring(i, i+1);
    System.out.println(ch);
    sum+=Integer.parseInt(ch);          
}
sc.close();
System.out.println(sum);

And if possible, please upload the source code in text form, not capture.


2022-09-22 20:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.