简体   繁体   中英

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

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

}

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

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

Int alder = scanner.nextInt()

Read string using nextLine and then convert to int

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM