所以我试图找到用户输入的字符串中的所有大写字母,但我不断收到运行时错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 4
at java.lang.String.charAt(String.java:686)
at P43.main(P43.java:13)
我觉得很愚蠢,但我无法弄清楚这一点,oracle甚至在java.lang.StringIndexOutOfBoundsException
页面上讨论了charAt这是我的代码,用于查找大写字母并打印它们:
import java.io.*;
import java.util.*;
public class P43{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//Uppercase
String isUp = "";
System.out.print("Please give a string: ");
String x = in.next();
int z = x.length();
for(int y = 0; y <= z; y++){
if(Character.isUpperCase(x.charAt(y))){
char w = x.charAt(y);
isUp = isUp + w + " ";
}
}
System.out.println("The uppercase characters are " + isUp);
//Uppercase
}
}
我真的很感激任何意见和帮助。
答案 0 :(得分:15)
for(int y = 0; y <= z; y++){
应该是
for(int y = 0; y < z; y++){
记住数组索引从ZERO开始。
字符串
中的16位Unicode字符数
因为循环从ZERO开始,循环应终止于长度-1。
答案 1 :(得分:7)
数组索引超出范围是因为for循环没有在length - 1
上终止,它终止于length
大多数迭代for循环应采用以下形式:
for (int i = 0; i < array.length; i++) {
// access array[i];
}
字符串也一样。
也许更清洁的方式是:
String inputString; // get user input
String outputString = "";
for (int i = 0; i < inputString.length; i++) {
c = inputString.charAt(i);
outputString += Character.isUpperCase(c) ? c + " " : "";
}
System.out.println(outputString);
编辑:忘了String
没有实现Iterable<Character>
,愚蠢的Java。
答案 2 :(得分:5)
使用Java 8,您也可以使用lambdas。将String
转换为IntStream
,使用过滤器仅获取大写字符,并通过将过滤后的字符附加到String
来创建新的StringBuilder
:
Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
//Uppercase
String isUp = in.next()
.chars()
.filter((c) -> Character.isUpperCase(c))
.collect(StringBuilder::new, // supplier
StringBuilder::appendCodePoint, // accumulator
StringBuilder::append) // combiner
.toString();
System.out.println("The uppercase characters are " + isUp);
//Uppercase
灵感来自:
答案 3 :(得分:2)
试试这个......
方式:强>
public int findUpperChar(String valitateStr) {
for (int i = valitateStr.length() - 1; i >= 0; i--) {
if (Character.isUpperCase(valitateStr.charAt(i))) {
return i;
}
}
return -1;
}
<强>用法:强>
String passwordStr = password.getText().toString();
.......
int len = findUpperChar(passwordStr);
if ( len != -1) {
capitals exist.
} else {
no capitals exist.
}
答案 4 :(得分:1)
您可以在给定字符串中找到大写字符的简单步骤之一...
<强>程序强>
import java.io.*;
public class testUpper
{
public static void main(String args[]) throws IOException
{
String data,answer="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any String : ");
data=br.readLine();
char[] findupper=data.toCharArray();
for(int i=0;i<findupper.length;i++)
{
if(findupper[i]>=65&&findupper[i]<=91) //ascii value in between 65 and 91 is A to Z
{
answer+=findupper[i]; //adding only uppercase
}
}
System.out.println("Answer : "+answer);
}
}
<强>输出强>
输入任何字符串:
欢迎使用String WoRlD
答案:WTHSWRD
答案 5 :(得分:0)
您可以在这里增加代码的可读性,并从现代Java的其他功能中受益。请使用Stream方法解决此问题。另外,我建议将最少数量的库导入到您的类中。导入时请避免使用。*。
import React from 'react';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
export default class Counter extends React.Component {
state = {
num: 0,
}
inp1 = 0;
inp2 = 0;
handleSubtract = () => {
this.setState({
num:this.inp1-this.inp2
})
}
handleAdd = () => {
this.setState({
num: this.inp1 + this.inp2
})
}
handleDivide = () => {
this.setState({
num: this.inp1 / this.inp2
})
}
handleMultiply = () => {
this.setState({
num: this.inp1 * this.inp2
})
}
handleTax = () => {
var newNum = this.num / 100 * 12;
this.setState({
num: newNum
})
}
handleNum1 = (text) => {
this.inp1 = parseInt(text);
}
handleNum2 = (text) => {
this.inp2 = parseInt(text);
}
render() {
return (
<View style={styles.flexBox}>
<Text style={styles.flexTitle}>Hi, welcome to my app!</Text>
<View style={styles.inpBox}>
<TextInput
style={[styles.inps, {marginRight: 10}]}
placeholder="Num1"
keyboardType="phone-pad"
onChangeText={this.handleNum1}
/>
<TextInput
style={styles.inps}
placeholder="Num2"
keyboardType="phone-pad"
onChangeText={this.handleNum2}
/>
</View>
<View style={styles.butBox}>
<View style={styles.button}>
<Button
onPress={this.handleSubtract}
title="Subtract"
/>
</View>
<View style={styles.button}>
<Button
onPress={this.handleAdd}
title="Add"
/>
</View>
<View style={styles.button}>
<Button
onPress={this.handleMultiply}
title="Multiply"
/>
</View>
<View style={styles.button}>
<Button
onPress={this.handleDivide}
title="Divide"
/>
</View>
<View style={[styles.button, {height: 65, width: 65}]}>
<Button
onPress={this.handleTax}
title="Tax"
color="#f00"
/>
</View>
</View>
<Text style={styles.numBox}>
{this.state.num}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
flexBox: {
flex: 1,
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
},
flexTitle: {
padding: 10,
},
inpBox: {
flexDirection: "row",
},
inps: {
width: "20%",
height: 50,
textAlign: "center",
},
butBox: {
flexDirection: "row",
width: "100%",
alignItems: "center",
},
button: {
width: "20%",
height: 50,
},
numBox: {
padding: 20,
fontSize: 32,
}
});
示例输入
:saveChangesInTheEditor
示例输出:
我是
答案 6 :(得分:0)
import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
StringBuilder s=new StringBuilder();
Scanner input = new Scanner(System.in);
System.out.println("Enter your String");
String str= input.nextLine();
for(int i=0; i<str.length(); i++)
{
if(Character.isUpperCase(str.charAt(i)))
{
System.out.print(str.charAt(i)+" ");
}
}
}
}
答案 7 :(得分:0)
我知道的最简单的方法是使用正则表达式替换。
isUp = x.replaceAll("[^A-Z]", "");
简单来说,它使用一个正则表达式来匹配不在A-Z范围内的任何字符,并将其替换为空字符串。
答案 8 :(得分:-1)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number");
String str= input.nextLine();
int ascii;
for(int i=0; i<str.length(); i++) {
ascii = str.charAt(i);
System.out.println(ascii);
if (ascii >= 65 && ascii <= 90) {
System.out.println("captal letter found ::: "+ascii);
}
}
}
答案 9 :(得分:-1)
public class Cama {
public static void main(String[] args) {
String camal = "getStudentByName";
String temp = "";
for (int i = 0; i < camal.length(); i++) {
if (Character.isUpperCase(camal.charAt(i))) {
System.out.print(" " + Character.toLowerCase(camal.charAt(i)));
} else if (i == 0) {
System.out.print(Character.toUpperCase(camal.charAt(i)));
}else{
System.out.print(camal.charAt(i));
}
}
}
}