簡體   English   中英

使用Scanner在簡單Java程序中編譯錯誤

[英]Compilation errors in simple Java program with Scanner

import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}

我不知道為什么我在字符串上得到2個錯誤無法轉換為int。

keyboard.nextInt(); 

代替

keyboard.next();

如果你想使用keyboard.next(); ,然后int firstint first更改為String first

將代碼修改為:

import java.util.*;
public class Demo {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.nextInt();

        System.out.print("Type your seconds integer : ");
        int second = keyboard.nextInt();

        System.out.print("The sum of your two integers are:" +(first+second));
    }
}

將您的類名更改為另一個而不是string

有多種方法可以執行此操作,具體取決於您要執行的驗證量。

在下面的解決方案中,使用.nextInt()獲得第一個數字。 注意,如果它不是整數,我們需要清除流輸入,所以在捕獲InputMismatchException時我們會調用.next()。 否則,由於尚未清除輸入,因此將繼續發生相同的異常

第二個數字是使用.next()獲得的,它返回一個字符串,然后我們將該字符串轉換為整數。 請注意,這里我們捕獲一個不同的異常NumberFormatException以確保輸入仍然良好。 (我們不會調用.next())

 public static void main (String [] args) {
    try (Scanner keyboard = new Scanner(System.in)) {
        System.out.print("Type your first integer: ");
        int first;
        do {
            try {
                first = keyboard.nextInt();
                break;
            } catch (InputMismatchException e) {
                keyboard.next();
                System.out.print("Invalid first integer, try again: ");
            }
        } while (true);
        System.out.print("Type your seconds integer : ");
        int second;
        do {
            try {
                second = Integer.valueOf(keyboard.next());
                break;
            } catch (NumberFormatException e) {
                System.out.print("Invalid seconds integer, try again: ");
            }
        } while (true);
        System.out.print("The sum of your two integers are: " + (first + second));
    }
}

我做的最后一件事是嘗試使用資源,這樣輸入流將被關閉,無論程序是否正常退出或拋出異常。

Scanner類next()方法返回String值。 您可以執行以下任何步驟來解決編譯錯誤。

  1. 您需要將String值轉換為int。

     int first = Integer.parseInt(keyboard.next()); 
  2. 您可以使用nextInt()方法直接從用戶獲取int值。

這將讀取整行,然后將其轉換為整數

int first = Integer.paresInt(keyboard.nextLine());

要么

如果您確定輸入數字

int first = keyboard.nextInt();

我有三個解決這個問題的方法:

第一

在您的代碼中,您使用的是keyboard.next() ,它將返回一個您必須將其轉換為Integer的字符串。 為此您可以使用keyboard.nextInt() ,它將直接將字符串轉換為整數。

import java.util.Scanner;

public class strings {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.nextInt();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.nextInt();
        System.out.print("The sum of your two integers are:"+(first+second));
    }
}

第二

或者你可以使用Integer.parseInt(**String to be converted to Integer**)string into Integer Integer.parseInt(**String to be converted to Integer**) ,這會將string into Integer

import java.util.Scanner;

public class strings {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = Integer.parseInt(keyboard.next());
        System.out.print("Type your seconds integer : ");
        int second = Integer.parseInt(keyboard.next());
        System.out.print("The sum of your two integers are:"+(first+second));
    }
}

第三

或者你可以使用Integer.valueOf(**String to be converted to Integer**)string into Integer Integer.valueOf(**String to be converted to Integer**) ,這會將string into Integer

import java.util.Scanner;

public class strings {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = Integer.valueOf(keyboard.next());
        System.out.print("Type your seconds integer : ");
        int second = Integer.valueOf(keyboard.next());
        System.out.print("The sum of your two integers are:"+(first+second));
    }
}

您可以使用scanner.nextLine() (讀取輸入直到行的末尾),它給出String輸出並使用Integer.parseInt將其轉換為int ,如下所示:

          Scanner keyboard = new Scanner(System.in);
          try {
              System.out.print("Type your first integer: ");
              int first = Integer.parseInt(keyboard.nextLine());
              System.out.print("Type your seconds integer : ");
              int second = Integer.parseInt(keyboard.nextLine());
              int sum  =first+second;
              System.out.print("The sum of your two integers are:"+sum);
          } catch(Exception exe) {
              System.out.println(" Error!!!! Please try again !!!! ");
          } finally {
              keyboard.close();
          }

此外,嘗試close資源(在finally塊中,如上所示)作為練習。

您正在使用Scanner類中的next()方法。 此方法返回String,您不能將字符串存儲在int類型變量中。 因此,您可以對int類型輸入使用nextInt()方法,或者您可以將值存儲在String變量中,之后可以將String變量轉換為int。

請遵循以下代碼:

import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.nextInt();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.nextInt();
        System.out.print("The sum of your two integers are:" +(first+second));
    }
}

或遵循此代碼

import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        //Get String input and stroe at String variable
        String firstString = keyboard.next();
        //Convert the String variable to int 
        int first=Integer.parseInt(firstString);
        System.out.print("Type your seconds integer : ");
        //Get String input and stroe at String variable
        String secondString = keyboard.next();
        //Convert the String variable to int 
        int second=Integer.parseInt(secondString);
        System.out.print("The sum of your two integers are:" +(first+second));
    }
}

正如其他人所說,你可以使用

int first = keyboard.nextInt();

但你也可以使用next()方法和parseInt,如果你願意,可以有一個顯示錯誤信息的便利。

import java.util.*;
public class myClass {
public static void main (String [] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Type your first integer: ");
    String firstStr = keyboard.next();
    System.out.println("Type your seconds integer : ");
    String secondStr = keyboard.next();
    int first = -1; //assuming only positive integers
    int second = -1;
     do{
      try{
      first = Integer.parseInt(firstStr);
      second = Integer.parseInt(secondStr);
      int sum = first + second;
      System.out.println("The sum of your two integers are: " + sum);
     } catch (NumberFormatException exception) {
      System.out.println("Integers only.");
     }
  } while (first=-1 && second=-1);
 }
}

更改您的firstsecond變量

int first = keyboard.next();  
int second = keyboard.next();

int first = keyboard.nextInt();
int second = keyboard.nextInt();

你應該用nextInt替換next,就像這樣

int first = keyboard.nextInt();

從API中,您可以看到next的返回類型是String,而nextInt()是int。

問題在這里:

int first = keyboard.next();

Scanner.next返回String,你期望int,所以你需要替換它

int first = keyboard.nextInt();

同樣

  int second = keyboard.nextInt();

嘗試使用

keyboard.nextInt();

keyboard.next();

它顯示它無法轉換,因為.next用於字符串,但對於其他數據類型是.next,然后是帶有大寫的數據類型。 例如:

long l=keyboard.nextLong(); 

boolean b=keyboard.nextBoolean();

keyboard.next()將從掃描程序返回下一個完整的令牌,我想到字符串類型所以需要將其轉換為整數,更好的選擇是使用keyboard.nextInt()方法獲取整數輸入。

你已經將代碼更改為:

import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Type your first integer: ");
        int first = keyboard.nextInt();
        System.out.println("Type your seconds integer : ");
        int second = keyboard.nextInt();
        System.out.print("The sum of your two integers are:"+(first+second));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM