Learn Java - Exercise 03x - Use Scanner to Read Keyboard Integers & Double Data Types

preview_player
Показать описание

Learn how to use the scanner() method to read integers, doubles, and floats in from the keyboard.
Рекомендации по теме
Комментарии
Автор

I find it much easier this way

public class Age {

public static void main(String[] args)

{
Scanner scan = new Scanner(System.in);

int age, newAge;

System.out.println("Enter your age: ");

age = scan.nextInt();

newAge = age + 14;

System.out.println("You are now " + age);



System.out.println("In 14 years, you will be " +newAge+ " years old.");

newAge = scan.nextInt();



}

}

raymondRodriguez
Автор

public static void main(String[] args)
{

Scanner userInput = new Scanner(System.in);

int age;
int years = 14;


System.out.println("Please enter your age: ");
if (userInput.hasNextInt() == true) {
age = userInput.nextInt();


age+=years; //( age = age + 14) => this is optional. I used 'age+=years' within System.out.println()


System.out.println("You are now " + age + " years old.");
System.out.println("In " + years + " years you will be " + (age+=years) + " years old.");
}


}




// Note: Notice the curly brackets used after " if (userInput.hasNextInt() == true) { }"
If your script is added within these there will be no error if the expected 'int" input for "age = userInput.nextInt();" is not a valid integer. Your program will just stop. You also don't need to declare age=1 if your code is within these brackets. If you don't use these { } brackets, java will say: " variable may not have been initialized"

hendrecarstens
Автор

Here it's my version :P


Scanner input = new Scanner(System.in);
int age, ageAfter14Years = 14, answer = 0;
age = input.nextInt();
System.out.println("You are now: " + age + " Years old");
answer = ageAfter14Years + age;
System.out.println("In the 14 years, you will be: " + answer + " Years old");
answer = input.nextInt();

paincodename
Автор

my solution, with if functions that outputs an error if the user did not type an integer or a whole number.
import java.util.Scanner;
public class lesson9 {

public static void main(String[] args) {
Scanner object1 = new Scanner(System.in);
int arf, meow;

System.out.println("Enter your age:");
{
arf = object1.nextInt();
meow= arf+14;

System.out.println("you are now "+arf+" years old"

+ "\nin 14 years, you will be "+meow+" years old");};


Please Type Integer/Whole Number");
};

}
}

vonnuevon
Автор

Hi


After ENTERING the age, I have to press another time, otherwise the "You are now 10 years... " is not appearing.

In the video/excecrcise before there was the same issue.



Why do I have to double-ENTER?


Thank you

nicolasjoye
Автор

why dont this work? do you have to formatt hasNextInt() if statement exactly like you have it?

if(input.hasNextInt() == true && age > 1){
age = input.nextInt();
System.out.println("You are currently " +age+ " years old, in 14 years you will be "+(age+14)+" years old.");
}

SirFency