How do I loop nextInt to define variables in an array? - java

the question I've asked isn't too clear but essentially I have been tasked to:
Write a program to read in 5 integer numbers from the user. You
should store the numbers in an array.
Use loops for efficiency.
I would know how to do this if it weren't for loops, however I am unsure how to use loops for this certain task.
What I have is this (I know this is completely wrong I was just trying to base it on the example from the book).
import java.util.Arrays;
import java.util.Scanner;
public class fivenumbersloops {
public static void main(String[] args)throws Exception {
Scanner aids = new Scanner(System.in);
int[] numbers = new int[5];
do
{
System.out.println("Enter a whole number: ");
numbers[0] = aids.nextInt();
numbers[0]++;
}while (numbers[0]==numbers[5]);
}
}
I know it's the bottom bit which is completely wrong, but if someone could help point me in the right direction I would appreciate it.

What you want is a for loop. This for loop initializes the variable i to 0, continues while i is less than 5 and increments i for each iteration. The variable i is used to specify the position to place the input number into the array.
public static void main(String[] args) throws Exception {
Scanner aids = new Scanner(System.in);
int[] numbers = new int[5];
for (int i = 0; i < 5; i++) {
System.out.println("Enter a whole number: ");
numbers[i] = aids.nextInt();
}
}

Related

(Java)Using while function with condition

I am making program that add all the number from user input until 0 comes. when 0 comes as input, I want to show all the numbers that are saved. When I run the program I got the "java.lang.OutOfMemoryError: Java heap space" this error and I want to know what part is wrong.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> myList = new ArrayList<Integer>();
int a = scanner.nextInt();
while(a!=0) {
myList.add(a);
}
for(int i=0;i<myList.size();i++) {
System.out.println(myList.get(i));
}
You need to keep reading a new number from stdin. Otherwise, a will not change value, and will lead to said error:
while (a !=0) {
myList.add(a);
a = scanner.nextInt();
}
IMHO a for loop is more appropriate:
for (int a = scanner.nextInt(); a != 0; a = scanner.nextInt()) {
myList.add(a);
}
This has the desirable effect of limiting the scope of a to the loop (one should always limit the scope of everything as much as possible).

ArrayList Scanner input help Java

I am trying to write a code where you sort a given list of numbers, and I'm trying to do so using ArrayList. I am using a while loop to allow for repeated inputs. This is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class sortinggg {
public static Scanner keyboard = new Scanner(System.in);
public static ArrayList<Integer> number = new ArrayList<Integer>();
public static void main (String [] args) {
int count= 0;
System.out.println("Enter your numbers.");
while (keyboard.hasNextInt()); {
number.add(keyboard.nextInt());
}
The integer count is irrelevant right now, as I only use it when I am sorting the list.
The problem is that after I input my numbers, even if I type in a string (for example), the program doesn't move on to the next line of code. Am i missing anything here?
P.S. I tired looking up questions that have been asked previously on this topic, but none of the solutions suggested worked for me.Thank you for your help in advance!
Try this:
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
ArrayList<Integer> number = new ArrayList<Integer>();
System.out.println("Enter your numbers:");
while (keyboard.hasNextInt()) {
number.add(keyboard.nextInt());
}
}
}
Modifications:
In while (keyboard.hasNextInt()); remove semicolon(;) at the end.
Here while loop will keep adding values to the arraylist until you provide int values.
In the first place the ; just after the while is wrong. It does not let you to execute the body. Then how are you going to skip the loop. You may ask the end user to enter some special value and use it to break the loop. The corrected version is given below.
public static void main(String[] args) {
int count = 0;
System.out.println("Enter your numbers or -1 to skip.");
while (keyboard.hasNextInt()) {
int num = keyboard.nextInt();
if (num == -1) {
break;
}
number.add(num);
}
System.out.println(number);
}

Why is this simple program not working

So I'm doing some random practice for an upcoming exam, and I don't know if it's the fact that I've been reviewing for hours and my brain isn't functioning, or something in this code is wrong.
I'm attempting to make a very simple java program that asks the user for the amount of numbers they wish to enter (totalNum), create an array that long, and then ask the user for each individual value. After it asks the user for each value in the array, it prints the array.
Here is my code:
import java.util.Scanner;
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i>totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++;
}
numbers.toString();
System.out.println(numbers);
}
}
When I run it it asks the user for the numbers I want to store, then prints [I#33909752 and stops. I've done dozens of programs like this and for the life of me I can't figure out where I went wrong.
Any help would be appreciated, thanks!
Your loop test is backwards. This
for (int i = 0; i>totalNum; i++) {
should be
for (int i = 0; i < totalNum; i++) {
as is, the test evaluates to false and the loop isn't entered. And, don't increment i in the loop body (that's what i++ does in the for). Finally,
System.out.println(numbers);
isn't going to print the array correctly, because arrays don't override Object.toString(). You can use Arrays.toString like
System.out.println(Arrays.toString(numbers));
i>totalNum is the problem. The for loop will not execute even once.
The for loop has three parts:
The action to perform before starting the loop
The condition
The action to perform after each loop
Your condition is i>totalNum, which is false for i=0 and totalNum=1. The loop won't execute even once.
The i++ is already mentioned in the loop, you do not need to include it in the loop body anymore.
The unexpected output is the caused by the default toString()-method of Array. Use Arrays.toString() for a readable output.
Your loop condition should be
for (int i = 0; i<totalNum; i++) {
and within loop don't increment variable i
use below for your desired result.
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i<totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++; //remove this
}
numbers.toString();
System.out.println(Arrays.toString(numbers));
}
}

I need to create an array with numbers given by the user, it works but keeps giving me 0

System.out.println("Please enter a coefficients of a polynomial’s terms:");
String coefficents = keyboard.nextLine();
String[] three = coefficents.split(" ");
int[] intArray1 = new int[three.length];
for (int i = 0; i < intArray1.length; i++) {
System.out.print(intArray1[i]);
}
//Does anyone know how i can make this work because right not it builds but when i run it, it gives me 0
//if someone could show me or explain to me what's wrong that would help
The problem was that you created the array intArray1 and you printed it without adding any elements to it. That's why it gives 0 as the result.
Instead of creating intArray1, print out the array three in the following way:
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner user_input = new Scanner(System.in);
System.out.println("Please enter the coefficients of a polynomial’s terms:");
String coefficents = user_input.nextLine();
String[] three = coefficents.split(" ");
for (String i: three) {
System.out.print(i);
}
}
}

how to read integers and store them in an array in java

Sorry if this is an obvious problem.
I'm trying to read integers from users and store them in an array.
The thing is that I want to use arraylist, because the size of the input is not for sure
If I know the size then I know a way to do that, which is
class Test1
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
System.out.println("Please input your numbers");
int num; // integer will be stored in this variable
ArrayList<Integer> List = new ArrayList<Integer>();
// for example if I know the size of the input is 5,
// then I read one single number and put it into the arraylist.
for (int i = 0; i <= 4; i++)
{
num = reader.nextInt();
List.add(num);
}
System.out.println(List);
}
}
How to do this if I don't know the size?
Except for reading one number in each loop, is there any better way to do that?
Can I use BufferedReader instead of Scanner?
Thanks a lot for any help!
You could change this
for (int i = 0; i <= 4; i++)
{
num = reader.nextInt();
List.add(num);
}
to use Scanner.hasNextInt() with something like
while (reader.hasNextInt())
{
num = reader.nextInt();
List.add(num);
}
You cannot instanciate an array if you do not know its size.
Therefore your approach is the correct one: start with an ArrayList and when done adding to it, you can convert it to an array.
You can use the hasNextInt() in a while loop to keep going until there are no more numbers to read.
while (reader.hasNextInt()) {
List.add(reader.nextInt());
}

Categories