I want to write a simple program that reads an array from the keyboard and paste it on the screen. When I compile it, I get the following error:
Keyboard cannot be resolved
Here's my code:
import java.util.*;
import java.io.*;
public class Test2
{
public static void main (String args[])
{
int i, n;
int[] myList= new int[100];
System.out.println ("n= "); Keyboard.getInt(n);
for (i=1; i<=n; i++)
{
System.out.println ("myList[" + i + "]= ");
Keyboard.getInt(myList[i]);
}
for (i=1; i<=n; i++)
System.out.println (myList[i]);
}
}
I'm working with Eclipse Luna. Do I need to download any package to use the function Keyboard.getInt?
Thank you!
You forgot to create the keyboard variable of type Scanner.
Add this at the beginning:
Scanner keyboard = new Scanner(System.in);
Some things to keep in mind:
variable names start in lowercase so change your Keyboard to keyboard. see the Oracle naming convention
Scanner has the nextInt method which returns int.
you should close the Scanner at the end.
arrays are zero based, you should begin from 0 up to n - 1
So you will get:
import java.util.*;
import java.io.*;
public class Test2
{
public static void main (String args[])
{
int i, n;
int[] myList= new int[100];
Scanner keyboard = new Scanner(System.in);
System.out.println ("n= ");
n = keyboard.nextInt();
for (i=0; i<n; i++)
{
System.out.println ("myList[" + i + "]= ");
myList[i] = keyboard.nextInt();
}
for (i=0; i<n; i++)
System.out.println (myList[i]);
keyboard.close();
}
}
use scanner class like this
Scanner keyboard = new Scanner(System.in)
and in your loop put keyboard.next() instead Keyboard.getInt()
here is sample code:
public static void main (String args[])
{
int i, n;
int[] myList= new int[100];
Scanner keyboard = new Scanner();
System.out.println ("n= ");
n = keyboard.next();
for (i=1; i<=n; i++)
{
System.out.println ("myList[" + i + "]= ");
mylist[i] = keyboard.next();
}
for (i=1; i<=n; i++)
System.out.println ("list values" + myList[i]);
}
Classes like Scanner or Console are probably what you want (see other answers for details). If you need low level access to key events, I do not know of any cross platform library, but under Linux evdev-java works fairly well.
Related
RightTriangle.java: Write code that reads in a number R from the user, and displays a figure with R rows of "$" characters as the following pattern. For instance, if the user enters a 4 for R, your program should display:
$$$$
$$$
$$
$
Heres my code currently.
import java.util.Scanner;
public class RightTriangle {
public static void main(String[] args) {
int R;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
R = sc.nextInt($);
System.out.println(R);
}
}
You could solve this task like so:
import java.util.Scanner;
public class triangle{
public static void main(String[] args){
int R;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
R = sc.nextInt();
int k = R;
for(int i=0; i<R; i++){
for(int j=k; j>0; j--){
System.out.print('$');
}
k = k - 1;
System.out.print('\n');
}
}
}
We use two for loops. The first for loop is used to print a newline after the nested for loop printed the correct amount of $ for that line. Note how we decrease the value of the inner loop counter inside the outer for loop to decrease the amount of $ printed each line.
Use a descending for-loop with the input as the index.
In each iteration, print the $ symbol i times. You could do this using a loop or using another way.
EDIT:
import java.util.Scanner;
public class RightTriangle {
public static void main(String[] args) {
int R;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
R = sc.nextInt(10);
for (int i = R; i >0; i--) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < i; j++) {
sb.append("$");
}
System.out.println(sb.toString());
}
}
}
A little late, but here it is anyway :)
package Exercises;
import java.util.Scanner;
public class ArrayPlusN {
public static void createArray(int indeces){
Scanner in = new Scanner(System.in);
int valueAdded, y = 0;
int[] arraySet = new int[indeces];
for(int i = 0; i < arraySet.length; i++){
System.out.printf("Enter element #%s: ",i+1);
arraySet[i] = in.nextInt();
}
System.out.println("These are the elements in your array: ");
for(int i:arraySet){
System.out.printf("%s ", i);
}
System.out.println("");
System.out.print("Enter a number to add in each of your Array's element: ");
valueAdded = in.nextInt();
System.out.println("These are the elements in your array when we added "+ valueAdded + " to each: ");
for(int i:arraySet){
arraySet[y]=i+valueAdded;
System.out.printf("%s ", i+valueAdded);
y++;
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int indeces;
System.out.print("Enter how many array index/indeces you want: ");
indeces = in.nextInt();
createArray(indeces);
}
}
Well to start things up, i'm trying to make a program where it will add a value on each element in the array, by getting user input of how many index that user wants to make, elements of the said array and the value to be added on the said array. There's no error in this code though you can copy paste it but im asking if i can do it as OOP. i don't think that this is OOP, anybody can help? I mean i wanted to seperate all those functions on each methods, is that possible? i tried it but i can't seem to know on how to call another variable from another method. i wanted to make createArray, fillArray and addElement methods to make it look more OOP rather than just making 1 createArray with all the functions in it.
Here's the code defining the main(), createArray(), fillArray() and addElement() methods; calls the methods in the order needed and accomplishes the task in the manner you want.
package Exercises;
import java.util.Scanner;
public class ArrayPlusN {
static int arraySet[];
public void createArray(int indeces){
Scanner in = new Scanner(System.in);
int valueAdded, y = 0;
arraySet = new int[indeces];
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
ArrayPlusN object=new ArrayPlusN();
int indeces;
System.out.print("Enter how many array index/indeces you want: ");
indeces = in.nextInt();
object.createArray(indeces);
object.fillArray();
object.addElement();
}
public void fillArray(){
Scanner in=new Scanner(System.in);
for(int i=0;i<arraySet.length;i++){
System.out.println("Enter element number "+(i+1));
arraySet[i]=in.nextInt();
}
System.out.println("The elements of your array are");
for(int i:arraySet)
System.out.print(i+" ");
System.out.println();
}
public void addElement(){
Scanner in=new Scanner(System.in);
System.out.println("Enter value to be added to each element");
int valueAdded = in.nextInt();
int y=0;
System.out.println("These are the elements in your array when we added "+ valueAdded + " to each: ");
for(int i:arraySet){
arraySet[y]=i+valueAdded;
System.out.printf("%s ", i+valueAdded);
y++;
}
}
}
The arraySet array is declared as a global static one. All the methods are declared as public void. The arrays are called in the main() method with the object object of class ArrayPlusN in order and gets the job done. Hope it helps you.
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT.
int a,b,n;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
Scanner sv=new Scanner(System.in);
b=sv.nextInt();
Scanner st=new Scanner(System.in);
n=st.nextInt();
for(int i=0;i<n;i++)
{
int c=0;
c=2*c*b;
int result=a+c;
System.out.print(result+ " ");
}
}
}
I tried using scanner class but it is not executed by eclipse as it only shows sc,sv and st objects of scanner class is resource leaked and never closed.
Well, it appears you have some configs that keep your program from compiling and running based on the resource leaking (not an Eclipse user). Your code compiles and runs with Intellij on my machine so you have a few choices.
Change your configuration to ignore the warning/error. (not recommended)
Close the one Scanner you need. (scanner.close()) You can get more than one value from the single scanner. So, ditch the other ones.
To accomplish (2) another way you could use try-with-resources block and it will be closed automatically at the end of the try.
try (Scanner sc = new Scanner(System.in)) {
// put your code to get input here
} catch (IOException ioe) { ... }
In addition to the scanner issues you're asking about, you have a significant error in your code that will make it impossible to get any meaningful/accurate output. Consider...
for (int i = 0; i < n; i++) {
int c = 0;
c = 2 * c * b;
int result = a + c;
System.out.print(result + " ");
}
c is made anew on each loop and assigned a value of 0 and so c = 2 * c * b; will equal 0 always; and a + c will then always just equal a.
Dont need to create a new Scanner Object...
just do:
int a, b, n;
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
b = sc.nextInt();
n = sc.nextInt();
for (int i = 0; i < n; i++) {
int c = 0;
c = 2 * c * b;
final int result = a + c;
System.out.print(result + " ");
}
I was typing this out when #Xoce was posting his answer, so it's exactly the same as his :)
The only other thing that I'd like to add is that if you're using IntelliJ, try pressing control-alt-i to auto-indent your code.
public static void main(String[] args) {
//Enter your code here. Read input from STDIN. Print output to STDOUT.
int a,b,n;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
b=sc.nextInt();
n=sc.nextInt();
for(int i=0;i<n;i++)
{
int c=0;
c=2*c*b;
int result=a+c;
System.out.print(result+ " ");
}
}
I'm making a simple program in java .. So that as I give input:
2 2 4 5
And output will be:
2 2 4 5
Whatever I give input it prints the same output.
But before it must ask to input the number of elements first.
EDITED MY QUESTION
Okay, so I tried this
package com.logical01;
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args){
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter your number elements: ");
int n_Elements=in.nextInt();
System.out.println("Enter your number now: ");
for(int i=0; i<=n_Elements; i++){
array[i]=in.nextInt();
}
int i = 0;
System.out.println(array[i]);
}
}
Output
Enter your number elements:
5
Enter your number now:
6
2
1
3
5
6
and it prints..
6
Move this line:
System.out.println(array[i]);
into the for loop just above it.
The reason this program compiles at all is because you have declared int i; at the top of the loop.
If instead you moved the declaration inside the declaration of the for loop, then it wouldn't compile when you try and do the wrong thing.
for(int i=0; i<=n_Elements; i++) {
This is an example of defensive coding, which protects you against mistakes that might be made elsewhere.
This is what you want :
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args){
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter your number elements: ");
int n_Elements=in.nextInt();
System.out.println("Enter your number now: ");
for(int i=0; i<n_Elements; i++){
array[i]=in.nextInt();
}
for(int i = 0; i<n_Elements; i++){ //you need to loop to get all the values in an array
System.out.print(array[i]);
}
}
just think about your last line.
What is the value of i?
What is array[0];
What is array[1];
..
What are you printing really - and what do you want to print?
after initializing your array (int[] array = new int[100]), every entry is 0.
try this for debugging and understanding:
public static void main(String[] args) {
int[] array = new int[100];
int i;
Scanner in = new Scanner(System.in);
System.out.println("Enter your number elements: ");
int n_Elements = in.nextInt();
System.out.println("Enter your number now: ");
for (i = 0; i < n_Elements; i++) {
array[i] = in.nextInt();
System.out.println("input: array[" + i + "]= " + array[i]);
}
System.out.println("printing: i=" + i + " and array[" + i + "]="
+ array[i]);
}
how to take user input in Array using Java?
i.e we are not initializing it by ourself in our program but the user is going to give its value..
please guide!!
Here's a simple code that reads strings from stdin, adds them into List<String>, and then uses toArray to convert it to String[] (if you really need to work with arrays).
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
See also:
Why is it preferred to use Lists instead of Arrays in Java?
Fill a array with List data
package userinput;
import java.util.Scanner;
public class USERINPUT {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//allow user input;
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
//you notice that now the elements have been stored in the array .. array[]
System.out.println("These are the numbers you have entered.");
printArray(array);
input.close();
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
import java.util.Scanner;
class bigest {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println ("how many number you want to put in the pot?");
int num = input.nextInt();
int numbers[] = new int[num];
for (int i = 0; i < num; i++) {
System.out.println ("number" + i + ":");
numbers[i] = input.nextInt();
}
for (int temp : numbers){
System.out.print (temp + "\t");
}
input.close();
}
}
You can do the following:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int arr[];
Scanner scan = new Scanner(System.in);
// If you want to take 5 numbers for user and store it in an int array
for(int i=0; i<5; i++) {
System.out.print("Enter number " + (i+1) + ": ");
arr[i] = scan.nextInt(); // Taking user input
}
// For printing those numbers
for(int i=0; i<5; i++)
System.out.println("Number " + (i+1) + ": " + arr[i]);
}
}
It vastly depends on how you intend to take this input, i.e. how your program is intending to interact with the user.
The simplest example is if you're bundling an executable - in this case the user can just provide the array elements on the command-line and the corresponding array will be accessible from your application's main method.
Alternatively, if you're writing some kind of webapp, you'd want to accept values in the doGet/doPost method of your application, either by manually parsing query parameters, or by serving the user with an HTML form that submits to your parsing page.
If it's a Swing application you would probably want to pop up a text box for the user to enter input. And in other contexts you may read the values from a database/file, where they have previously been deposited by the user.
Basically, reading input as arrays is quite easy, once you have worked out a way to get input. You need to think about the context in which your application will run, and how your users would likely expect to interact with this type of application, then decide on an I/O architecture that makes sense.
**How to accept array by user Input
Answer:-
import java.io.*;
import java.lang.*;
class Reverse1 {
public static void main(String args[]) throws IOException {
int a[]=new int[25];
int num=0,i=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number of element");
num=Integer.parseInt(br.readLine());
System.out.println("Enter the array");
for(i=1;i<=num;i++) {
a[i]=Integer.parseInt(br.readLine());
}
for(i=num;i>=1;i--) {
System.out.println(a[i]);
}
}
}
import java.util.Scanner;
class Example{
//Checks to see if a string is consider an integer.
public static boolean isInteger(String s){
if(s.isEmpty())return false;
for (int i = 0; i <s.length();++i){
char c = s.charAt(i);
if(!Character.isDigit(c) && c !='-')
return false;
}
return true;
}
//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.
public static int getInteger(String prompt){
Scanner input = new Scanner(System.in);
String in = "";
System.out.println(prompt);
in = input.nextLine();
while(!isInteger(in)){
System.out.println(prompt);
in = input.nextLine();
}
input.close();
return Integer.parseInt(in);
}
public static void main(String[] args){
int [] a = new int[6];
for (int i = 0; i < a.length;++i){
int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
a[i] = tmp;
}
}
}
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many numbers you wanna enter?");
length = input.nextInt();
System.out.println("Enter " + length + " numbers, one by one...");
int[] arr = new int[length];
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter the number " + (i + 1) + ": ");
//Below is the way to collect the element from the user
arr[i] = input.nextInt();
// auto generate the elements
//arr[i] = (int)(Math.random()*100);
}
input.close();
System.out.println(Arrays.toString(arr));
This is my solution if you want to input array in java and no. of input is unknown to you and you don't want to use List<> you can do this.
but be sure user input all those no. in one line seperated by space
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = Arrays.stream(br.readLine().trim().split(" ")).mapToInt(Integer::parseInt).toArray();