How to get consecutive numbers form user in a java program? - java

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

Related

I am not sure why the code will not output any statements. When I run it in my IDE nothing is outputted

package Fall21;
import java.util.Scanner;
public class BalloonRideWeight {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int personWeight = sc.nextInt();
int totalWeight = 0;
for (int i=0; i<n; ++i) {
totalWeight +=personWeight;
personWeight =sc.nextInt();
}
if (totalWeight >500)
System.out.println("Everyone too fat.");
else
System.out.println("Just right.");
sc.close();
}
}
would this be a runtime issue ???
I am just learning basics so any answers with arrays and more complex levels of code are not needed.
It probably doesn't output anything because u are using Scanner which expects input. When I run your program and I enter the following input
1
1
1
I get as output
Just right.
Each of these invocations
sc.nextInt();
expects you to enter an input that gets stored in the declared variable (left hand side of the statement).
So with my first two inputs, the values
n = 1, personWeight = 1
then the loop iterates 1 time, which contains another scanner invocation setting the personWeight. Which I again set to 1.
Only then it reaches the if condition that prints something to the console. See this for more info: https://www.w3schools.com/java/java_user_input.asp
EDIT:
If you want to parse multiple ints from one line, u can do:
String[] arguments = scanner.nextLine().split(" ");
int[] ints = new int[arguments.length];
for (int i = 0; i < ints.length; i++) {
ints[i] = Integer.parseInt(arguments[i]);
}
Or a fancier version:
int[] ints = Arrays
.stream(scanner.nextLine().split(""))
.mapToInt(Integer::parseInt)
.toArray();

Java how to read a certain Number and display it as a figure

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 :)

Java Array get digits and make number from array input

import java.util.Scanner;
public class Tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args) {
int d, i = 0, a = 0, f = 1;
System.out.println("Enter How many Digits you want?");
d = in.nextInt();
int num[] = new int[d];
for(i = 0; i < d; i++) {
System.out.println("Enter Single Digit");
num[i] = in.nextInt();
}
for(i = d; i > 0; i--) {
a = a + (num[i] * f);
f = f * 10;
}
System.out.println("The Number is: " + a);
}
}
Question: User will enter number of digits and the program will make from it a number I have wrote the code by myself but it doesnt seems to work.
When Running the program:
the input seems to work fine. I have tried to test the output of the
array without the second loop with the calculation, seems to work
but with the calculation seems to crush:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at tar0.main(tar0.java:17)
What's the deal?
Java arrays start at 0 and continue up from there. The way your code is formatted right now you are losing a value and therefore your array is too small to hold the values.
One option as outlined above would be to decrement your d value so that we are using a proper array size in the loop. This would be the preferred way so I removed the additional code above for the other option.
import java.util.Scanner;
public class tar0 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args)
{
int d,i=0,a=0,f=1;
System.out.println("Enter How many Digits you want?");
d=in.nextInt();
int num[] = new int[d];
for(i=0;i<d;i++)
{
System.out.println("Enter Single Digit");
num[i]=in.nextInt();
}
for(i = d - 1; i >0 ; i--)
{
a=a+(num[i]*f);
f=f*10;
}
System.out.println("The Number is: "+a);
}
If you have modified the following code it will work.
for(i=d;i>0;i--)
{
a=a+(num[i-1]*f);
f=f*10;
}
Array index value will start at 0. so change array from num[i] to num[i-1]

Error: Keyboard cannot be resolved

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.

how to take user input in Array using java?

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

Categories

Resources