2
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:");
    }
}

I dont know why im getting 2 errors on strings cannot converted to int.

SergGr
  • 23,570
  • 2
  • 30
  • 51
Rino
  • 81
  • 6
  • 1
    Please [edit] your question to be on-topic: include a [mcve] that duplicates the problem. Questions seeking debugging help ("why isn't this code working the way I want?") must include: (1) the desired behavior, (2) a specific problem or error and (3) the shortest code necessary to reproduce it *in the question itself*. Please also see: [What topics can I ask about here?](http://stackoverflow.com/help/on-topic), and [ask]. If the code provided duplicates the problem , you still need to include the *exact* errors which you are getting, along with the expected behavior. – Makyen Apr 01 '17 at 23:28
  • Duplicate? [How to convert a String to an int in Java](http://stackoverflow.com/questions/5585779/how-to-convert-a-string-to-an-int-in-java) – David Rawson Apr 02 '17 at 01:31
  • any update for this ? – John Joe Jul 16 '18 at 09:48

14 Answers14

12
keyboard.nextInt(); 

instead of

keyboard.next();

If you want to use keyboard.next();, then change int first to String first.

Modify your code to this:

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));
    }
}

Change your class name to another instead of string.

catch23
  • 17,519
  • 42
  • 144
  • 217
John Joe
  • 12,412
  • 16
  • 70
  • 135
  • Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/139096/discussion-on-answer-by-john-joe-not-compling-in-java-vim-editor). – Bhargav Rao Mar 26 '17 at 19:47
2

There are multiple ways to do this, depending on how much validation you want to do.

In the solution below first number is obtained using .nextInt(). Note that if it is not an integer we need to clear the stream input, so in catching of InputMismatchException we do call .next(). Otherwise the same exception would keep occurring since the input has not been cleared

The second number is obtained using .next() which returns a string and we cast that string to the integer. Note that here we catch a different exception NumberFormatException to ensure that the input is still good. (we do not call .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));
    }
}

One last thing I did was try on the resource, this way the input stream will be closed regardless if the program exits normally or throws an exception.

Bojan Petkovic
  • 2,406
  • 15
  • 26
2

Scanner class next() method returns String value. You can do anyone of the following steps to solve the compilation error.

  1. You need to convert the String value to int.

    int first = Integer.parseInt(keyboard.next());
    
  2. You can use nextInt() method to get int value directly from the user.

Gourav Joshi
  • 2,419
  • 2
  • 27
  • 45
Ram
  • 56
  • 5
2

This will read the whole line then convert it to an Integer

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

or

If you are sure input is in digit

int first = keyboard.nextInt();

2

I have three solutions for this problem :

First

In your code you are using keyboard.next() which will return a string that you have to convert it into Integer. For that you can use keyboard.nextInt(), it will directly convert the 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 = 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));
    }
}

Second

or you can convert the string into Integer by using Integer.parseInt(**String to be converted to Integer**), this will convert the 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));
    }
}

Third

or you can convert the string into Integer by using Integer.valueOf(**String to be converted to Integer**), this will convert the 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));
    }
}
Anuj Teotia
  • 1,303
  • 1
  • 15
  • 21
  • If you found this (or any) answer helpful, please upvote it. If this answered your question, please mark it as the accepted answer. Thanks! – Anuj Teotia Apr 03 '17 at 10:26
  • Although you provided code examples, you didn't provide any explanation on how you solved the issue or the problem with the original posters code snippet. As a result, your answer isn't of very good quality. – pczeus Apr 03 '17 at 13:06
1

You can use scanner.nextLine() (reads the input till end of the line) which gives String output and convert it to int using Integer.parseInt as shown below:

          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();
          }

Also, try to close the resources (inside finally block, shown above) as a practice.

Vasu
  • 21,832
  • 11
  • 51
  • 67
1

You are using next() method from Scanner class. This method return String and you cannot store string at int type variable. So you can use nextInt() method for int type input or you can just Store the value at String variable and after that you can convert the String variable to int.

Please follow this code:

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));
    }
}

or Follow this code

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));
    }
}
Shekhar
  • 54
  • 5
1

As others have stated you can use

int first = keyboard.nextInt();

but you can also use the next() method along with a parseInt, which can have the handy benefit of showing an error message if you'd like.

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);
 }
}
1

Change your first and second variables from

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

to

int first = keyboard.nextInt();
int second = keyboard.nextInt();
Khaled
  • 644
  • 1
  • 8
  • 14
0

you should replace next with nextInt, like this

int first = keyboard.nextInt();

From the API, you can see that the return type of next is String,while nextInt() is int.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
刘思凡
  • 423
  • 2
  • 14
0

Problem is here:

int first = keyboard.next();

Scanner.next returns String, and you are expecting int, so you need to replace it with

int first = keyboard.nextInt();

As well

  int second = keyboard.nextInt();
Ruslan Akhundov
  • 2,178
  • 4
  • 20
  • 38
0

Try using

keyboard.nextInt();

not

keyboard.next();

it displays that it cannot convert because .next is for strings, but for other data types is .next and then the data types with a capital. For example:

long l=keyboard.nextLong(); 

and boolean b=keyboard.nextBoolean();

0

keyboard.next() will return the next complete token from the scanner ,i think of string type so it needs to be typecast to integer and better option is to use keyboard.nextInt() method to take the integer input .

0

you have change your code to this:

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));
    }
}