I am a beginner in Java programming. I am trying to write a simple program to take size of input followed by list of numbers separated by spaces to compute the sum.
The first input is getting in fine for the second one system shows error as it is trying to parse a blank string into integer. Can you please help with the mistake I am making?
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(" Enter size of input ");
int num = scan.nextInt();
System.out.println("Enter data separated by spaces: ");
String line = scan.nextLine();
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}
The reason you get an exception in your code is because int num = scan.nextInt(); does not process the newline character after the number.
So when the statement String line = scan.nextLine(); is used, it processes the newline character and hence you get an empty string ""
You can either fetch the entire line and parse it to Integer, like this:
int num = Integer.parseInt(scan.nextLine());
or you can go with using nextInt() and then use a blank scan.nextLine() to process the new line after the number, like this:
int num = scan.nextInt();
scan.nextLine();
Your Program has only one error that you were making only one scan object of scanner class, you have to make two scanner class object one will help in getting array size while another will help in getting array element.
import java.util.Scanner;
public class InputStringforarray {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scan1 = new Scanner(System.in); // change 1
System.out.print(" Enter size of input ");
int num = scan.nextInt();`enter code here`
System.out.println("Enter data separated by spaces: ");
String line = scan1.nextLine();// change 2
String[] str = line.split(" ");
int[] A = new int[num];
int sum = 0;
for (int i = 0; i < num; i++)
A[i] =Integer.parseInt(str[i]);
for (int i = 0; i < num; i++)
sum = sum + A[i];
System.out.println("Sum is " + sum);
}
}
Related
import java.util.Scanner;
import java.util.Arrays;
public class searchSorting
{
public static void main (String[]args)
{
String line;
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to input?: ");
line = in.nextLine();
System.out.print("Input Number 1: " );
line = in.nextLine();
System.out.print("Input Number 2: ");
line = in.nextLine();
System.out.print("Input Number 3: " );
line = in.nextLine();
System.out.print("Input Number 4: ");
line = in.nextLine();
System.out.print("Input Number 5: " );
line = in.nextLine();
}
public static void sortAscending (double[]arr)
{
Arrays.sort(arr);
System.out.printf("Sorted arr[] = %s",
Arrays.toString(arr));
}}
I am stuck on what the code is for putting the what the user inputs in ascending order. I have looked up and tried multiple resources on ascending order but nothing seems to work. I tried:
System.out.print("Input number 1: "+(i+1+":");
to try and add the inputs instead of writing all of them out but i was an unknown variable.
You should use an array to store input and a loop to read input.
System.out.print("How many numbers you want to input?: ");
int num = in.nextInt();
double[] arr = new double[num];
for(int i = 0; i < num; i++){
arr[i] = in.nextDouble();
}
sortAscending(arr);
You have to create an array. Then put the stuff you are reading into the array and after that call your method.
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
sortAscending(values);
Note that the name sortAscending is not accurate, it is not just sorting (and then returning the result or in-place), but also printing. So maybe you should rename it to sortAndPrintAscending. Or just sort it and let your main method to the printing.
Or drop it completely, the method does not really serve any purpose as it is just calling Arrays.sort, might as well do that in main:
System.out.print("How many numbers you want to input?: ");
int amount = Integer.parseInt(in.nextLine());
double[] values = new double[amount];
for (int i = 0; i < values.length; i++) {
System.out.print("Input Number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
Arrays.sort(values);
System.out.println("Sorted: " + Arrays.toString(values));
I need to read user inputs line by line (may be included spaces). I had already read Scanner doesn't see after space question. So I used with scanner.nextLine() but this method does not help my program. Below is my sample program ....
public class TestingScanner {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many friends do you have ?");
int size = sc.nextInt();
String[] names = new String[size];
for (int i = 0; i < size; i++) {
System.out.println("Enter your name of friend" + (i + 1));
names[i] = sc.nextLine();
}
System.out.println("*****************************");
System.out.println("Your friends are : ");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
System.out.println("*****************************");
}
}
While runnig my program , after inserted no: of friend , my program produces two lines as below. How can I solve it ? Thanks.
After int size = sc.nextInt(); use sc.nextLine() to consume the newline characters, otherwise, they will be consumed by nextLine() in your loop and that is not what you want.
Solution
int size = sc.nextInt();
sc.nextLine();
So i have the following chuckj of code and what i want it do is for the user to enter 5 numbers in the netbeans console.The way i want to do it is he either can enter some by being separting the numbers with a space or line by line for exmaple like the following
But what i want is to "Enter a string of numbers" to be only visiable when it is needed to, for example when he needs to enter the next number. Is it possible to do this?
The following is done by the following code
Scanner reader = new Scanner(System.in);
int number;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 5; i++) {
System.out.println("Enter a string of numbers");
number = reader.nextInt();
numbers.add(number);
}
System.out.println("size" + numbers.size());
for(int takenNumber : numbers){
System.out.println(takenNumber);
}
You could do something like this:
Scanner reader = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();
int numbersEntered = 0; // Stores how many numbers the user has entered so far
while (numbersEntered < 5) { // Keep asking if they have not entered 5 numbers yet
System.out.println("Enter a string of numbers");
String[] input = reader.nextLine().split(" "); // Split the input by spaces into an array
numbersEntered += input.length; // Add the number of numbers they entered to the variable
for (int i = 0; i < input.length; i++) {
if (numbers.size() < 5) { // Only add the numbers if the list is not full
numbers.add(Integer.parseInt(input[i])); // Add each number they entered to the numbers list
}
}
}
You can use the hasNext() function of Scanner to keep reading while there is more input without doing another prompt. Try:
Scanner reader = new Scanner(System.in);
int number;
ArrayList<Integer> numbers = new ArrayList<Integer>();
int i = 0;
while((i < 5))
{
System.out.println("Enter a string of numbers:");
if(reader.hasNextLine())
{
String[] numbersRead = reader.nextLine().split("\\s");
System.out.print("Read:");
for(int n = 0; n < numbersRead.length; n++)
{
numbers.add(Integer.parseInt(numbersRead[n]));
i++;
}
System.out.println();
}
}
The code below shows my progress, but I cannot print the numbers that were entered. I don't know where to put println("you entered the following numbers") in the loop so that it'll show up when the loop stops.
import java.util.Scanner;
public class aufgabe5 {
public static void main(String[] args) {
int x;
Scanner input = new Scanner(System.in);
System.out.println("How much numbers do you want to enter?");
x = input.nextInt();
int j = 1;
Scanner scanner = new Scanner(System.in);
int[] numbers = new int[x];
for (int i = 0; i < numbers.length; i++) {
System.out.println("Enter the " + j++ + ". number:");
numbers[i] = scanner.nextInt();
}
System.out.println("You entered following numbers");
System.out.println(x);
}
}
Change x like
System.out.println(x);
to Arrays.toString(int[]) like
System.out.println(Arrays.toString(numbers));
Edit
To print the array reversed,
String str = Arrays.toString(numbers).replace(", ", " ,");
str = str.substring(1, str.length() - 1);
System.out.println(new StringBuilder(str).reverse().insert(0, "[")
.append("]"));
Intialize the String before the loop, then keep adding the values to it.
After the loop finishes you can print the whole thing.
String someVar="You entered following numbers: ";
for(int 1=0;i<array.length;i++)
{
someVar=someVar+numbers[i]+",";
}
System.out.println(someVar);
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();