Enter multiple numbers in console - java

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

Related

i wrote a code using array and methods to display numbers from the smallest o the largest numbers

i wrote a code using array and method that allow the user to enter any number of numbers and
display the numbers sorted from the smallest number to the largest number however the program works but it doesn't show the numbers here is the code that i wrote
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers you want to enter? ");
int size = s.nextInt();
int i;
double[] numbers1 = new double[size];
System.out.println("Enter " + numbers1.length + " numbers: ");
getNumbers(numbers1);
double[] numbers2 = new double[numbers1.length];
for (i = 0; i < numbers1.length; i++) {
numbers2[i] = numbers1[i];
}
displayNumbers(numbers1);
System.out.println("The numbers after sorting are: ");
sortNumbers(numbers2);
displayNumbers(numbers2);
}
public static void getNumbers(double[] numbers) {
Scanner s = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = s.nextDouble();
}
}
public static void sortNumbers(double[] numbers) {
double temp;
double pass;
for (pass = 0; pass < numbers.length; pass++) {
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temp;
}
}
}
}
public static void displayNumbers(double[] numbers) {
Scanner s = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = s.nextDouble();
System.out.print(numbers + " ");
}
System.out.println();
}
}
Your displayNumbers() method is wrong. In the loop you wrote:
numbers[i] = s.nextDouble();
System.out.print(numbers + " " );
You're trying to read again 4 doubles (everytime you call that method) and you're printing the whole array (which doesn't do what you'd expect). What you probably want is this:
System.out.print(numbers[i] + " " );
Your code is inefficient and unclear.
You don't need to create a new Scanner everytime and also why instead of println the array with Arrays.toString(double[]).
You should also make more cleaner instructions and variable names.
Here is an example of how the code should be
public static void main(String[] args)
{
//create a new Scanner with a name that defines it
Scanner scanner = new Scanner(System.in);
//print your instructions
System.out.println("How many numbers would you like to sort?");
//print "> " to let the user to know he should be entering values
System.out.print("> ");
//read the number the user has entered which we will define as how many numbers he would enter next
int totalNumbers = scanner.nextInt();
//create a new array the size of the total numbers
double[] unsortedNumbers = new double[totalNumbers];
//tell the user to enter his unsorted numbers
System.out.println("Enter your unsorted numbers: ");
//loop totalNumbers times until the whole unsortedNumbers is full
for(int index = 0; index < totalNumbers; index++)
{
System.out.print("> ");
unsortedNumbers[index] = scanner.nextDouble();
}
//Print the numbers he entered
System.out.println("You entered: ");
//Arrays.toString prints the array in format [number, number, ...]
System.out.println(Arrays.toString(unsortedNumbers));
//sort the arrays with Arrays.sort which sorts in ascending numerical order
Arrays.sort(unsortedNumbers);
//Print the final result - sorted numbers
System.out.println("Sorted: " + Arrays.toString(unsortedNumbers));
}

How to Get back/Return to a loop after catching a exceptional

I have this code that computes an Exponential example 3⁴ = 81.0 and the codes ask the user on how many numbers and exponent he wants to enter and when the user inputs numbers and exponents and he input an invalid input a letter the code will catch the java.util.InputMismatchException and stop. Are there any codes that can go back to the input numbers and exponent to enter again?
I've tried the boolean thing but it's not working and I'm searching about this thing but no one work.
try {
String[] unicode = {"\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079"};
System.out.print("Enter how many Numbers and Exponent you want to enter: ");
int userNum = new Scanner(System.in).nextInt();
ArrayList<Integer> num = new ArrayList<>();
ArrayList<Integer> nums = new ArrayList<>();
for (int i = 0; i < userNum; i++) {
System.out.print("Enter a Number: ");
int userNumber = new Scanner(System.in).nextInt();
num.add(userNumber);
System.out.print("Enter the exponent: ");
int userExponent = new Scanner(System.in).nextInt();
nums.add(userExponent);
}
for (int i = 0; i < userNum; i++) {
double answer = num.get(i);
for (int x = 0; x < nums.get(i) - 1; x++) {
answer *= num.get(i);
}
System.out.print(num.get(i));
for (int x = 0; x < String.valueOf(nums.get(i)).length(); x++) {
char g = String.valueOf(nums.get(i)).charAt(x);
String h = String.valueOf(g);
System.out.print(unicode[Integer.parseInt(h)]);
}
System.out.println(" = " + answer);
}
} catch (InputMismatchException exception) {
System.out.println(exception+" Invalid Input. Numbers Only.");
}
}
What I expect to this is when the user inputs an invalid input the program will catch java.util.InputMismatchException and print it and go back to inputs to input again
Ex.
Enter Num:12
Enter Exponent:asd
java.util.InputMismatchException
Enter Exponent:123
You should create some validation methods that will return boolean that means the validation was successful. Than you can use do while loop for asking for the input once again in case of a ValidationError. Something like this:
do {
System.out.print("Enter a Number: ");
String userInput = new Scanner(System.in).next();
} while (!validate(userInput));
num.add(Integer.parseInt(userInput));
You can also use the Scanner.hasNextInt() mtehod before trying to read int if the only restriction is to have valid int number.

Java exception error for input string

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

How can I print out the int values from the array?

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

Java using a while loop to load user input into an array

I was wondering how to load up an array (with user input) using a while loop. The code below prints a 0.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = 0;
int n = 0;
int[] myArray = new int[10];
System.out.printf("enter a value>>");
while (scan.nextInt() > 0) {
for (i = 0; i > 0; i++) {
myArray[i] = scan.nextInt();
}
System.out.printf("enter a value>>");
}
System.out.printf("array index 2 is %d", myArray[2]);
}
There are multiple things wrong with your code:
First of all
while(scan.nextInt() > 0){
Scanner.nextInt() returns an int from your standard input so you actually have to pick up that value. You are checking here what the user typed but then not using it at all and storing the next thing that the user types by saying:
myArray[i] = scan.nextInt();
You don't really need the outer while loop, just use the for loop, its enough.
However, your for loop is off as well:
for(i = 0; i > 0; i++){
It starts at i equal to 0 and runs while i is greater than 0. This means it will never actually run the code within the loop because 0 is never greater than 0. And if it did run (you started it at some number < 0), you would end up in an infinite loop because your condition i > 0 is always true for positive numbers.
Change the loop to:
for(i = 0; i < 10; i++){
Now, your loop could look like:
for(i = 0; i < 10; i++){ // do this 10 times
System.out.printf("enter a value>>"); // print a statement to the screen
myArray[i] = scan.nextInt(); // read an integer from the user and store it into the array
}
one other way to do it
Scanner scan = new Scanner(System.in);
List list = new ArrayList();
while(true){
System.out.println("Enter a value to store in list");
list.add(scan.nextInt());
System.out.println("Enter more value y to continue or enter n to exit");
Scanner s = new Scanner(System.in);
String ans = s.nextLine();
if(ans.equals("n"))
break;
}
System.out.println(list);
public static void main(String[] args)
{
Scanner input =new Scanner(System.in);
int[] arr=new int[4];
int i;
for(i=0;i<4;i++)
{
System.out.println("Enter the number: ");
arr[i]=input.nextInt();
}
for(i=0;i<4;i++)
{
System.out.println(arr[i]);
}
}
Hope this code helps.

Categories

Resources