[英]Convert String to Int. String value = scanner input…hard to explain
好吧,我正在嘗試轉換幾件事。
所以我已經將我的Scanner轉換為String,現在我要做的是,獲取他們輸入的值並將其用作其他if語句的整數。 它工作正常!
到目前為止,這是我的代碼:
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner fname = new Scanner(System.in);
Scanner sname = new Scanner(System.in);
Scanner number = new Scanner(System.in);
tuna weight = new tuna();
System.out.println("Enter Your First Name: ");
String fname1 = fname.nextLine();
String fnames = fname1;
System.out.println("Enter Your Last Name: ");
String sname1 = sname.nextLine();
String snames = sname1;
System.out.println("Enter Your Weight (Lbs.) : ");
String num = number.nextLine();
String num1 = num;
System.out.println("Okay " + fname1 + " " + sname1
+ " I can see here that you weigh " + num + "lbs.");
int num2 = num1.parseInt();
if (num1 >= 275)
System.out
.println("You know, you should maybe consider laying off the candy my friend.....");
}
}
您應該在parseInt
使用一個參數:
int num2 = Integer.parseInt(num1);
和
if (num2 >= 275)
...
嘗試這個:
try{
num2 = Integer.parseInt(num1);
}
catch(Exception ex) {
System.out.println("Something went wrong, the string could not be converted to int.");
}
try-catch非常重要,因為該字符串可能包含無法轉換為int的字符,因此您需要比這更好地捕獲它,但請記住
您也可以使用其他類型的掃描儀方法來獲取int值
num = number.nextInt();
這是我所做的:
Scanner input = new Scanner(System.in);
System.out.println("Type number");
int number = input.nextInt();
System.out.println(number);
希望這可以幫助...
我自己不是Java專業人士,但我將您的代碼調整了一個檔次才能使其正常工作。 這里是。 很高興,如果有幫助。
p
ackage APPLE;
import java.util.Scanner;
public class apples {
public static void main(String args[]) {
Scanner fname = new Scanner(System.in);
Scanner sname = new Scanner(System.in);
Scanner number = new Scanner(System.in);
Scanner intScanner = new Scanner(System.in);
System.out.println("Enter Your First Name: ");
String fname1 = fname.nextLine();
String fnames = fname1;
System.out.println("Enter Your Last Name: ");
String sname1 = sname.nextLine();
String snames = sname1;
System.out.println("Enter Your Weight (Lbs.) : ");
int num = intScanner.nextInt();
System.out.println("Okay " + " " + fname1 + " " + sname1
+ " I can see here that you weigh " + num + "lbs.");
if (num > 275){
System.out.println("You know, you should maybe consider laying off the candy my friend.....");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.