(Java)Using while function with condition - java

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

Related

Mooc.fi Part 3 Help,

Confused on this exercise, its asking me to create a loop which remembers multiple integers that the user inputted, and prints them out the exact same way. I'm confused on how to print the input without making it a list and not using any methods. I tried making input equal to i, but that doesn't output anything.
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
int i = 0;
int i2 = 0;
ArrayList <Integer> name_input = new ArrayList<>();
while(true) {
System.out.print("print number:");
int input = Integer.valueOf(scanner.nextLine());
name_input.add(input);
if (input == -1) {
break;
}
i++;
}
while(i2 < i){
System.out.println(i);
i2++;
}
}
Original question: The exercise template contains a base that reads numbers from the user and adds them to a list. Reading is stopped once the user enters the number -1.
Expand the functionality of the program so that after reading the numbers, it prints all the numbers received from the user. The number used to indicate stopping should not be printed.

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

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

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

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

Java while(input.hasnextline) loop not exiting?

SO I'm supposed to determine the number of lines in a text file (a 100 lines containg numbers) and then create an array with the the number of lines, but the first while loop used to find out the number of lines in the text file never exits. The second loop which is the exacts same one works just fine. Please help me out!
static void main(String[] args) throws Exception{
java.io.File file = new java.io.File("seriesOfNumbers.txt"); //file instance
Scanner input = new Scanner(file); //Scanner
int M =0 ;
while (input.hasNextLine() && !input.equals(null))// ** Loop never exits, tried almost everything
{
k++;
}
double[] numberArray = new double[k];
int V = 0;
while (input.hasNextLine())// When I exit the first loop this one exits just fine
{
numberArray[j] = (double) input.nextInt();
j++;
}
You are never consuming your input in the first loop, do that with input.nextLine().
You are now looping until input.hasNextLine() becomes false, but that never happens, because you do not consume the input.
Use input.next() to move to next line. In While condition you are checking the has next line and not null. Thats y it is in infinite loop.
In this below code,
this is initialising
Scanner input = new Scanner(file); //Scanner
This is reading
int M =0 ;
while (input.hasNextLine() && !input.equals(null))
{
input.nextLine(); // Use this to advance the lines from scanner
k++;
}
It seems to me that you could use FileUtils class from apache.commons.io project to do the trick.
static void main(String[] args) throws Exception{
List<String> lines = FileUtils.readLines(new File("..."));
Now, if you really need the numberArray for some other computation, you can
double[] d = new double[lines.size()];
Or you can use the Collection to iterate
for (String line : lines) {
double n = Double.parseDouble(line);
To use FileUtils, take a look at http://commons.apache.org/proper/commons-io/
But, iof all that you want is to know what is wrong with your code, you should call the method Scanner.nextLine() inside your first while loop.
In order to stop the infinite looping of the while loop even after consuming the required inputs, we can use a break statement.
Here is an example,
while (scanner.hasNextLine()) {
String[] arr = scanner.nextLine().split(" ");
long[] ar = new long[n];
for (int i = 0; i < n; i++) {
ar[i] = Long.parseLong(arr[i]);
}
long result = sum(ar);
System.out.println(result);
break;
}

Categories