Scanner Input

+1 Neeraj Tandel · February 10, 2016
Hey Bucky, If we were to use Scanner inp how would we do that ??

Post a Reply

Replies

Oldest  Newest  Rating
0 Tomb Raider(fake) · February 11, 2016
i think you can do in this way
import java.util.Scanner;
public class Apples {
public static void main(String[] args) {
Scanner inp=new Scanner(System.in)
int sum=0;
int a[]=new int[5];
for(int i=0; i<5; i++)
{
a=inp.nextInt();
sum=sum+a;
}
int avg=sum/5;
System.out.println("Avg"+avg);
}
}
0 Neeraj Tandel · February 11, 2016
Thanks for the reply Gary. 
My Actual question was how to use Scanner Input in Tutorial 35: Variable Length Argument where we can input few numbers and when the inp is equal to done it will give the Average.
0 Gary Whitney · February 10, 2016
It has been years since I went thru Buckys Java tutorials, but #6 was the one on using the scanner.
Here are some of my notes:
·         Introduced importing the Scanner class from the java.util library.
·         Imported Scanner
·         Make Scanner class object e.g. Scanner input = new Scanner(System.in).
·         Make a variable that holds a reference to a Scanner object.
·         The Scanner object has the methods nextLine(), that waits for a enter key before returning a String from the keyboard.
 Here is a sample code::
import java.util.Scanner;
public class Apples {
   public static void main(String[] args) {
      Scanner bucky = new Scanner(System.in);
      System.out.println(bucky.nextLine());
   }
}

Here is my caution!
You have to validate the input before you use it, or the program will crash.
  • 1

Java / Android Development

106,950 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator