gpt4 book ai didi

java - 在方法java中将字符串转换为int

转载 作者:行者123 更新时间:2023-11-30 11:12:07 25 4
gpt4 key购买 nike

所以我尝试将 int 转换为字符串,然后是 charAt(0)、charAt(1) 和 charAt(2)。我这样做是为了将 3 位整数拆分为 3 个不同的整数。然后我想将这些单独的整数转换为字符串。

我想做的是从 101 及以上获取数字并用文字打印出来。我有数百个,数十个和一个方法。我正在尝试获取第一个整数并将其应用于数百方法,第二个整数并将其应用于十位,第三个整数应用于个位方法。

这是>=101的方法

import java.util.Scanner;


public class rough {

public static void main(String args[]) {
int number = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Please type a number between 0 and 999 OR type -1 to exit: ");
number = scanner.nextInt();
if (number >= 101) {
System.out.println(hundred(first) + " AND" + tens(second) + "" + From1To19(third));
} else {
System.out.println("please input a number from 101: ");
}
//this is what i have so far(might be junk).

public static void From101(int num) {
String SNumber = Integer.toString(num);
char First = SNumber.charAt(0);
char Second = SNumber.charAt(1);
char Third = SNumber.charAt(2);
int num1 = Integer.parseInt(first);
}
}

现在我尝试打印单词,但出现 3 个错误。

System.out.println(hundred(first) + " AND" + tens(second) + "" + From1To19(third));

我在 if/else 语句中添加了这一行,错误是:

 ----jGRASP exec: javac -g rough.java

rough.java:27: error: 'void' type not allowed here
System.out.println(hundred(first) + " AND" + tens(second) + "" + From1To19(third));
^
rough.java:27: error: 'void' type not allowed here
System.out.println(hundred(first) + " AND" + tens(second) + "" + From1To19(third));
^
rough.java:27: error: 'void' type not allowed here
System.out.println(hundred(first) + " AND" + tens(second) + "" + From1To19(third));
^
3 errors

----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.

最佳答案

现在您正在将 int 转换为 String,将 String 转换为 char,以及将 char 返回到 int

你可以跳过所有这些,直接从int -> int,使用modular division .

例如,获取12345的各个数字:

int a = 12345;
int b = a%10; //b = 5
a = a / 10; //now a = 1234
int c = a%10; //c = 4
a = a / 10; //now a = 123
int d = a%10; //d = 3
a = a / 10; //now a = 12
int e = a%10; //e = 2

关于java - 在方法java中将字符串转换为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27054010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com