Compiling problem - Why doesn't Int work on my age variable?

103 views Asked by At

Picture of error

First program I make after hello world. Firstname, lastname and age. When using String on age, everything works as expected. I was told to use Int on age instead of String, but when I changed to Int and try to compile, I get this error: "cannot find symbol". I guess I have to do something completely different if I want age as an Int. What am I doing wrong?

import java.util.Scanner;

public class Oppgave2 {

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);


    System.out.println("Skriv inn fornavn: ");
    String fornavn = scanner.nextLine();



    System.out.println("Skriv inn etternavn: ");
    String etternavn = scanner.nextLine();



    System.out.println("Skriv inn alder: ");
    int alder = scanner.nextLine();

    System.out.println("Ditt navn er: " + fornavn + " " + etternavn);
    System.out.println("Din alder er: " + alder);
}

}

3

There are 3 answers

0
Olf On

nextLine() returns a String, as said in the javadoc of Scanner. Use nextInt() if you want to get and store a int.

2
Romeo Bahoumda On

In the Scanner class, you use nextInt() when expecting the token to be an integer.

Int alder = scanner.nextInt()

0
Joakim Danielson On

Read string using nextLine and then convert to int

String reply = sc.nextLine();
int alder = Integer.valueOf(reply).intValue;