I am writing a small program that reads the input and sets an array size, fills in the array and adds the numbers. My problem is that while I don't get any errors the program stops after the while. Any pointers as to what I am doing wrong would be very appreciated.
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] numbers = new int[in.nextInt()];
int sum = 0;
System.out.println("\n" + "numbers: " + numbers.length);
while (in.hasNextLine()) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = in.nextInt();
// System.out.println(numbers[i]);
}
}
for (int i = 0; i <= numbers.length; i++) {
sum += numbers[i];
}
System.out.println(sum);
}
}
As the JavaDoc for Scanner.hashNextLine() states:
Returns true if there is another line in the input of this scanner.
This method may block while waiting for input. The scanner does not
advance past any input.
So your while loop will never finish:
while (in.hasNextLine())
Just remove this loop, your for loop inside is already doing the right job.
PS: And as jipr311 stated fix your second for loop or you will face an ArrayIndexOutOfBoundsException:
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
the while loop is not needed
for (int i = 0; i < numbers.length; i++) {
if(in.hasNextInt())
numbers[i] = in.nextInt();
// System.out.println(numbers[i]);
}
There is no use of while loop. Remove that.
And edit the for loop like
for (int i = 0; i < numbers.length; i++)
This should work:
public static void main(String[] args) {
Scanner in = null;
try{
in = new Scanner(System.in);
int[] numbers = new int[in.nextInt()];
int sum = 0;
System.out.println("\n" + "numbers: " + numbers.length);
int count = 0;
while (count < numbers.length) {
numbers[count] = in.nextInt();
count++;
}
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
System.out.println(sum);
}finally{
if(null != in){
in.close();
}
}
}
There also was a resource leak in the program as scanner object was not closed. I have corrected it.
Related
I am writing code to display an array of numbers in ascending order. I have completed the first part which is the actual commands to get the array. The second part is that I have to make the program initialize after it has arranged an array of numbers. Here is my code.
package ascendingorder;
import java.util.Scanner;
public class Ascending_Order
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
When the code is compiled and executed, the program prompts the user to enter the array size and on entering it, the program then asks the user to enter the elements of the array. After that, the user presses enter and the program displays the result in ascending order.
After that the program is supposed to loop back and prompt the user to enter arrays size, followed by elements and so on. Also, the program is supposed to terminate when the user enters a value like 'n' or 'x'. Kindly help me with this part as I don't have any idea or how to place the for loop in order to loop the block of code from 'System.out.print("Enter no. of elements you want in array:");'. Thank you.
May be the below link can be helpful
[java program to loop back to start
boolean isRunning = true;
String tryAgain = "";
while (isRunning) {
// All your code you have in your example.
// Ask user if he wants to retry with a scanner.
tryAgain = <use scanner here>;
if (tryAgain.equals("no") || tryAgain.equals("No") ) isRunning = false;
}
Or
String tryAgain = "";
while (true) {
// All your code you have in your example.
// Ask user if he wants to retry with a scanner.
tryAgain = <use scanner here>;
if (tryAgain.equals("no") || tryAgain.equals("No") ) break;
}
First you have the program taking nextInt so if you entered the chars it would create an exception, you should instead use nextLine and then check/parse it.
As for the loop, a simple while loop would work, and don't forget to close the scanner at the end.
public static void main(String[] args) {
String in;
int temp, n;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
in = s.nextLine();
while (!in.equals("x") || !in.equals("n")) {
n = Integer.parseInt(in);
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++) {
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
in = s.nextLine();
}
s.close();
}
I don't understand why this runs but does not print anything. (I am new to coding altogether, so any advice is great.)
import java.util.Scanner;
import java.util.Random;
public class ArrayDoubleValues{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
// Length input
System.out.println("Length: ");
int length = scan.nextInt();
int[] list = new int[length];
for (int i = 0; i == list.length; i++){
list[i] =(int)(Math.random()+ 1) * 100;
System.out.print(list.length);
}
for(int i = 0; i == list.length; i++){
System.out.println(list[i]);
}
}
}
You have a wrong condition here --
for (int i = 0; i == list.length; i++){
Your program never enters these loops because i is not equal to list.length when you reach them. Instead, it should be
for (int i = 0; i < list.length; i++) { ... }
package test1;
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int traincars;
int maxweight;
int count = 0;
int total = 0;
maxweight = input.nextInt();
traincars = input.nextInt();
int[] trains = new int[traincars];
for(int i = 0; i < traincars; i++)
{
trains[i] = input.nextInt();
}
if (total < maxweight)
{
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
}else
{
count = count + 3;
}
System.out.println("count");
}
}
this is a really simple program but for some reason, the array for the traincars goes out of bounds..
Why is this happening?
The problem is here:
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
When i equals traincars-1 you will be accessing elements i+1, i+2. and i+3 which are out of bounds of your trains array.
If your logic is calling for calculating totals of 4 consecutive elements of the array then your for loop should stop earlier:
for(int i = 0; i < traincars - 3; i++) {...}
In the last iteration of
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
You try to access trains[i+1] and this is bigger than the length of your trains array.
To make this for loop matter you should just do the following:
for(int i = 0; i < traincars; i++)
{
total += trains[i]; //unless of course you need something else...
count++;
}
My question has to do with counting integers in an array. This is my code so far.
import java.util.Scanner;
public class Frequency {
public static void main(String[]args) {
Scanner kbd = new Scanner(System.in);
System.out.print("enter numbers: ");
int[] arr = new int[51];
for(int i = 0; true; i++) {
int in = kbd.nextInt();
if(in < 0)break;
else if(in > 50)break;
else arr[in]++;
}
for(int i = 0; i < arr.length; i++) {
System.out.println(i+" occurrences of "+arr[i]);
}
}
}
The way the problem outputs is correct except I need some way of filtering out all the numbers that have an occurrence of 0 so that only numbers that were in the input show in the output; instead of every number between 0 and 50.
You have already written an if statement, to stop your first loop when user enters a negative number. Simply write the same thing for your second loop:
for(int i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
System.out.println(arr[i]+" occurrences of "+i);
}
}
Side-note: I have also swapped arr[i] and i
for(int i = 0; i < arr.length; i++) {
if(!(i==0 || i%10==0) && arr[i]!=0)
System.out.println(i+" occurrences of "+arr[i]);
}
import java.util.Scanner;
public class diamond {
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer");
int lines = scan.nextInt();
for(int counter = 1; counter <= lines; counter++)
{
if (counter%2 != 0)
{
for(int count2 = 1; count2 <= counter; count2++){
System.out.print("*");
}
System.out.println();
}
}
}
}
I am supposed to ask the user for a number of lines and output a diamond made of asterisks that number of lines tall. I need some help figuring out how to center the asterisks. I know for strings there is some String.utils method or something, but the output comes in pieces based on a for loop, so I don't think that really works here. If it does, by all means let me know though.
You need to print a certain amount of spaces before each line. Then, you would need another for loop for the opposite.
Try this code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer ");
int lines = scan.nextInt();
for (int counter = 1; counter <= lines; counter++) {
if (counter % 2 != 0) {
for (int i = 0; i < lines - (counter / 2) - 3; i++) {
System.out.print(" ");
}
for (int count2 = 1; count2 <= counter; count2++) {
System.out.print("*");
}
System.out.println();
}
}
for (int counter = lines - 1; counter >= 1; counter--) {
if (counter % 2 != 0) {
for (int i = 0; i < lines - (counter / 2) - 3; i++) {
System.out.print(" ");
}
for (int count2 = 1; count2 <= counter; count2++) {
System.out.print("*");
}
System.out.println();
}
}
}
I think you should prepare a string to print out on each line, then you will know exactly how many characters it has, when the line increases, remove the two '*' in center of the string and add one " " in front of it, then print it out again.