working with variable number of arguments using scanner input class - java

While working with scanner input can we use var.. args with sc.nextInt()??
for example..(below code)
import java.util.Scanner;
class Sample
{
public static void run(int... args){
System.out.println(args[1]);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("please enter values: ");
int values = sc.nextInt();
run(values);
}
}
the output was ArrayIndexOutOfBoundsException:1 can any one explain about this...

values is just one variable, so args's length is 1, which means the only valid index is 0 (arrays are zero-based entities)

Your array size is 1 and trying to access 2nd value so use below code. I have change from args[1] to args[0].
ArrayIndexOutOfBoundsException arise when we try to access index value which is not present in array, not only for integers array but for all types of arrays.
import java.util.Scanner;
class Sample
{
public static void run(int... args){
System.out.println(args[0]);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("please enter values: ");
int values = sc.nextInt();
run(values);
}
}

use args[0] instead args[1] because your value store on

Related

Convert number to reversed array of digits (Scanner + Print-Method)

I want to get an Array with the reversed number when I invoke the method (Given a random non-negative number, you have to return the digits of this number within an array in reverse order.)
I initalised a scanner, but whenever I execute, I only get the address in the heap I suppose (for example: [I#66a29884).
I know this problem also occurs when we have String, which why we have the toString-Method.
Is there a way I can print the array or the reversed numbers out in the console?
public class ConvertNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Long n = Long.parseLong(scanner.nextLine());
digitize(n);
}
public static int[] digitize(long n) {
int[] digitized = new StringBuilder().append(n).reverse().chars().map(Character::getNumericValue).toArray() ;
System.out.println(digitized);
return digitized;
}
}
You have to change Long to String because [I#66a29884) is String. using java stream you can reverse string easily.
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.*;
public class Main
{
public static String digitize(String n) {
return Stream.of(n)
.map(str->new StringBuilder(str).reverse())
.collect(Collectors.joining(" "));
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String n = scanner.next();
System.out.print(digitize(n));
}
}

Scanner as parameter and convert to int? (JAVA)

I have a trouble about usage of the scanner.
The getUserInput takes as an input the scanner instance and initialise the array of specified size which comes from the scanner. For example: if user puts 3 then the method will create an array of the size 3.
However, it keeps saying that scnr can't converted to int....
Any advice?
public static void main(String[] args)
{
Scanner scnr = new Scanner(System.in);
System.out.println("How many orders were placed Saturday?");
int [] userInput = getUserInput(scnr);
System.out.println("How many orders were placed Sunday?");
int [] userInput = getUserInput(scnr);
System.out.println("How many orders were placed Monday?");
int [] userInput = getUserInput(scnr)
return;
}
}
public static int[] getUserInput(Scanner scnr)
{
int[] userInput = new int[scnr];
return userInput;
}
You have to call a method on Scanner. And because you want an int do it like this:
int[] userInput = new int[scnr.nextInt()];
Here you'll find the API documentation: https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
nextInt() method of Java Scanner class is used to scan the next token of the input as an int
public static int[] getUserInput(Scanner scnr)
{
int[] userInput = new int[scnr.nextInt()];
return userInput;
}
Firstly there are 2 mistakes you have done here.
int [] userInput there are 2 duplicates of this userInput variable.
You are passing an instance of Scanner as a parameter in your getUserInput function.
getUserInput FIX
So in order to create we need to follow a syntax i.e
datatype [] vairable_name = new datatype[size];
Here size can be byte short int but what you did is
datatype [] vairable_name = new datatype[Scanner];
Which is just not the Syntax. You can fix it by taking input as int from the user.
A scanner as a method to do that .nextInt() which converts the input of the user to int if it's in numbers.
Solution is
int[] userInput = new int[scnr.nextInt()];
// This is like the syntax
datatype [] vairable_name = new datatype[Scanner];
Duplicate Variable
You should revise scopes in java, and then you will know why it's an error.
You cannot have the same variable name in the same scope or in the child scope
public static void main(String args[]){
int a = 0;
int a = 1; // <- error cuz a is already difined and is duplicate in the same scope.
}
Similarly
public static void main(String args[]){
int a = 0;
if(true){
int a = 1; // <- error cuz a is already difined and is duplicate in child scope.
}
}
The solution is to change the variable name.
//scnr is now globally available in the class so need to pass it as a parameter
Scanner scnr = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("How many orders were placed Saturday?");
int [] saturdayUserInput = getUserInput();
System.out.println("How many orders were placed Sunday?");
int [] sundayUserInput = getUserInput();
System.out.println("How many orders were placed Monday?");
int [] mondayUserInput = getUserInput()
return;
}
}
public static int[] getUserInput()
{
int[] userInput = new int[scnr.nextInt()];
return userInput;
}
scnr is not an int. It's an isntance of the Scanner class. If you want to read an int from it, you'll need to call:
scnr.nextInt();
It's also better not to pass this as a parameter, but to create the Scanner on class level, so you can use it in all the methods.

How do store the data i have input and detected it's data type in Java?

I am making a program that detects the input data type t whether it's integer or double . I have don't the following code so far. But I don't know how to store the data I input.
Code:
import java.io.*;
import java.util.Scanner;
public class HeightCalc {
public static int temp,result;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
if (input.hasNextInt()) {
System.out.println("Integer.");
}
else if (input.hasNextFloat() || input.hasNextDouble()) {
System.out.println("Double.");
}
}
}
If you use the apache commons lib you can use StringUtils and NumberUtils.
In general define a variable for the scanner input and validate its content, validating the input directly is more restrictive.
import java.io.*;
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math;
public class HeightCalc {
public static int temp,result;
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
String input = scanner.nextLine();
if (StringUtils.isNumeric(input))
{
System.out.println("Integer.");
}
else if (NumberUtils.isCreatable(input))
{
System.out.println("Double.");
}
System.out.println("Input:" + input);
}
}
You can store the input in a variable like in the above example.
String myInput = scanner.nextLine();
if I get it right you need to store input number value to one variable?
I would create Number inputValue variable and into it I would store values from scanner.
Number inputValue;
Scanner input = new Scanner (System.in);
if (input.hasNextInt())
{
inputValue = input.nextInt();
System.out.println("int.");
} else if (input.hasNextFloat() || input.hasNextDouble())
{
inputValue = input.nextDouble();
System.out.println("Double.");
}
inputValue will inherit class from .nextInt() or nextDouble().
However I would consider storing input to one variable to get rid of this condition and derivate other number classes from it.
Example for int
inputValue = input.nextDouble();
public int getIntValue(){
return inputValue.intValue();
}

how to stop taking user inputs and print out arraylist

I am trying to create a program that takes user inputs stores them into an Arraylist and the prints the Arraylist out after user inputs a certain string. my current problem is that i cant get the user inputs to stop and print out. i think what i have currently have is a strong base, i cant see what is wrong.
import java.util.ArrayList;
import java.util.Scanner;
public class GroceryArraylist {
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter end to stop ");
while (!input.equals("end")) {
Grocerylist.add(input.next());
if (Grocerylist.equals("end")){
for(String str:Grocerylist)
System.out.println(str);
}
}
}
}
Here is the mistake:
Grocerylist.equals("end")
GroceryList is of type ArrayList and it will never be equal to the string "end". It's like comparing apples with oranges.
You could try this instead:
while (!input.equals("end")) {
String input = input.next();
Grocerylist.add(input);
if ("end".equals(input)){
for(String str:Grocerylist)
System.out.println(str);
}
break;
}
You can use hasNext command to avoid including "end" into the array.
public class GroceryArraylist {
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<String>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter \"end\" to stop ");
while (input.hasNext()) {
Grocerylist.add(input.next());
if(input.hasNext("end")) {
System.out.println(Grocerylist);
break;
}
}
}
}
Or you can use a do-while loop instead of:
public class GroceryArraylist{
public static void main(String[] args) {
ArrayList<String> Grocerylist = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.print("Enter an item, enter \"end\" to stop ");
do {Grocerylist.add(input.next());}
while (!input.hasNext("end"));
System.out.println(Grocerylist);
System.exit(0);
}
}

error: non-static variable scan cannot be referenced from a static context in Java

import java.util.Scanner;
public class CHP4Ex
{
Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("enter a n: ");
int n = scan.nextInt();
int i=10;
while (i<n)
{
System.out.println(i);
i = i + 10;
}
}
}
Why am I getting this error? I'm basically writing a while loop that prints all positive numbers that are divisible by 10 and less than n. For example, if n is 100, enter 10 ... 90.
Put the Scanner class object inside the main function. Basically the problem is that your code violates the static feature. You cannot use non-static members inside a static function, main being static in your case. So it should be :
import java.util.Scanner;
public class CHP4Ex
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("enter a n: ");
int n = scan.nextInt();
int i=10;
while (i<n)
{
System.out.println(i);
i = i + 10;
}
}
}
You can't refer to non static variable in static context, so change
Scanner scan = new Scanner(System.in);
to
private static Scanner scan = new Scanner(System.in); It should work

Categories