Last output not appearing - java

I'm just getting back on the programming horse so I'm doing some basic problems in Java on CodeAbbey.com. I am given a standard input where the first integer in the input is the number of pairs followed by all subsequent inputs being pairs of numbers. I input this by just running the code and pasting it then using Scanner to read it. My code is supposed to add together each of those pairs of numbers individually then output each answer separated with a space. For example:
data:
3
100 8
15 245
1945 54
answer:
108 260 1999
Here is my attempt:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
for (int i = 1; i <= size; i++) {
int sum = in.nextInt() + in.nextInt();
System.out.print(sum);
if (i < size) {
System.out.print(" ");
}
}
}
}
The code actually works, but the issue is that it is not initially outputting the last sum. It prints all the sums up to the last one, but I have to press enter again for the last sum to print, and it prints one line down from all the others. This happens no matter the number of pairs or the platform I'm using; the last sum never prints until I once again hit enter. Any idea as to why this is occurring?

The Scanner won't receive any input until Enter is pressed.
When you press Enter, the line of text, e.g. "1945 54", is entered into the scanner. Now it can return the next int. The Scanner will block until it can read sufficient input, and if you don't press Enter yet, it will remain blocked. That is why pressing Enter allows the program to print the sum.

Until you hit enter, it is hanging on the input routine, because you might actually be preparing to add a more scannable data (or another digit to the last number) you typed.

You should split the printing out part in a seperate loop not in that for loop that also asks for value inputs.
So with the code you have currently modified would be:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
for (int i = 1; i <= size; i++) {
int sum = in.nextInt() + in.nextInt();
System.out.print(sum);
}
for (int i = 1; i <= size; i++){
if (i < size)
System.out.print(" ");
}
}
}
}
splitting it should stop you needing to press enter before it prints the last value

Related

How can I terminate user input without using zero?

Basically I'm trying to make an method that would return an array so that I can use this list later down the line, only problem is I cant find a way to terminate user input other than using 0. I've tried to take in user input using a string then parsing it into an int but that only results in an error when a non-number character is used.
public static double[] input()
{
double[] arr = new double[100];
//int count = 1;
for(int i = 0; i < arr.length; i++)
{
System.out.print("Insert a number or Zero to stop: ");
double input = scan.nextDouble();
arr[i] = input;
if(input == 0)
{
break;
}
count++;
}
return arr;
}
I think that instead of the condition for(int i = 0; i < arr.length; i++) you could simply ask the user how many digits he/she wishes to enter and then pass that value to the for loop to execute lie for(int i = 0; i < length; i++) where length is the user desired size of array.
If you do not want to ask the user then do this accept the numbers as single characters instead of a string then before parsing it into int just check if the entered character is an escape sequence(\n or \r) arr[index]='\n' or'\r' then you can terminate the input process.
Note: this process is only for integer input if the user enters a character it accepts it just make sure that the entered character is a number.
I suggest you put the print statement out of the for loop as it will be repeated as long as the for loop runs, it is not nice to have those instructions displayed again and again.

Enter a number n, then prints all even squares between 1 and n

I need help figuring out on how to output even numbers between 1 and N (n is a number entered by the user).
Here is what I have so far.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
int n;
int i = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a Number");
n = scan.nextInt();
for(i=1; i<n; i++){
if(i%2==0)
i = i*i;
System.out.println(i);
}
}
}
Now that prints out the wrong output. I would like to know how it gets from 4 to 16 and to 36.
Sample Input: 45
Expected Output:
4
16
36
What is it that I'm doing wrong?
You are already increasing the variable i in the for definition, you don't need to increase again inside for block. Also start from 2 and move on by adding 2 on each step for a more efficient implementation.
for(i=2; i*i<n; i+=2){
System.out.println(i*i);
}
First, don't change the value of i inside the for loop. Instead of changing i to equal i*i, just print out i*i using the statement System.out.println(i*i);
Secondly, you also forgot the curly brackets after your if statement.

How to use Ctrl+Z to stop asking for input?

I am writing a program that takes integers from the user and stores them in an array, then calculates the arrays average.
The array can hold at maximum 100 integers. If the user wants to do less than 100, they hit CTRL+Z (or Command+D) to stop prompting for numbers.
Here is my main method:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int [] array = new int[100];
System.out.printf("Enter a stream of numbers: ");
readIntoArray(input, array);
for (int i = 0; i<=array.length;i++) {
array[i] = input.nextInt();
}
}
And here is the method that reads into the array.
public static int readIntoArray(Scanner input, int[] nums) {
int count = 0; //number of elements entered into the array
while (count <= nums.length && input.hasNextInt()) {
nums[count]=input.nextInt();
count++;
}
return count;
}
And here is the average method.
public static void printAboveAverage(int[] nums, int size) {
double average;
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum =+ nums[i];
}
average = sum/size;
System.out.print(average);
What am I doing wrong?
I keep getting a NoSuchElementException immediately after hitting CTRL+Z.
Here:
while (count <= nums.length && input.hasNextInt()) {
This loop will probably stop when you hit ctrl-z and there is no more int. But next statement is:
array[i] = input.nextInt();
In other words: your read method seems to correctly check if enough numbers are in, or if the scanner stopped having input.
But your main method ignores that, and just asks for another number from the scanner.
So it could be as simple as: just drop that for loop within your main method that wants more numbers.
I suggest you have a try and catch if it gives you an Exception, maybe use it to get unlimited numbers (dont use the max 100 numbers) and when he finds the exception he counts the average?
Not the best solution, excpetion are not meant to always be used, Thanks to domsson for the reminder
something like:
try{
//Get the numbers
}
catch(Exception e){
//Calculate the average
}
Just thinking out loud, it may help you.

How do you count the amount of numbers when the input is given separated by spaces, ended with a letter?

I'm quite new to java.
I'm trying out some things for a project but I don't get why this does not work.
The goal here is to let the user input numbers separated by spaces and end with a letter. The program then needs to count the even and odd indexed numbers and output which sum is larger.
I already made this successfully when the amount of numbers given was a constant, but now I want to make it adapt to the user input.
Because I want to put the numbers in an array I need to know the length of this array. To get this I want to count the amount of numbers the user puts in so I can create the appropriate length array.
For some reason the while loop does not end and keeps running. How do I count the amount of numbers put in?
EDIT
I've added in.next(); in the first while loop so it is not stuck at the first input element. This brings me to a further problem however of having two while loops trying to loop through the same input. I have tried to create a second scanner and resetting the first one, but it does not get the second loop to start at the first element. Previous answers show that this is not possible, is there a way to put this in one while loop while still using arrays to store the values?
P.S. The input values should be able to be any positive or negative integer.
Here is my complete code:
import java.util.Scanner;
public class LargerArraySum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int length = 0;
System.out.println("Enter your numbers seperated by spaces, end with a letter");
while(in.hasNextInt()) {
length++;
in.next();
}
System.out.println(length);
int arra[] = new int[length];
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
int evenSum = EvenArraySum(arra);
int oddSum = OddArraySum(arra);
if(evenSum<oddSum) {
System.out.println("The sum of the odd indexed elements is bigger");
} else if(oddSum<evenSum) {
System.out.println("The sum of the even indexed elements is bigger");
} else {
System.out.println("The sum of the odd and even indexed elements is equal");
}
}
public static int EvenArraySum(int[] a) {
int sum = 0;
for(int i=1;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the even indexed elements is: " + sum);
return sum;
}
public static int OddArraySum(int[] a) {
int sum = 0;
for(int i=0;i<a.length;i+=2) {
sum += a[i];
}
System.out.println("The sum of the odd indexed elements is: " + sum);
return sum;
}
}
add in.next(); in the loop. Actually you don't need array. You can sum even and odd indexed numbers while reading without saving them.
1) Your first while-loop does not work because the iterator is always checking for further numbers in from the same position.
Example:
Position 0 1 2 3 4 5
Value 1 3 5 7 9 0
At start the iterator points to position 0. If you call hasNextInt() it will check if position 1 is available, in this case it will be true. At this moment the interator still points to position 0. So you increase your length and do the same thing again, so you have an infinite loop.
To move the iterator to the next position you need to call nextInt().
2) You can't iterate over the same Scanner with a second while-loop in that way. If you would correct you first while-loop the iterator would point to position 5 (it reached the end of the scanner). So the check for hasNextInt() will be false and the second while-loop will not be entered.
3) The comments already mentioned it, you could use an ArrayList for this use case like so:
final ArrayList<Integer> input = new ArrayList<>();
while ( in.hasNextInt() ) {
input.add( in.nextInt() );
}
System.out.println( input.size() );
( or like kitxuli mentioned in his answer, dont even store the values, just count them in the first while-loop)
Your code has 2 major problems . The first and the second while loops lets take a look at your first loop .
while(in.hasNextInt()) {
length++;
}
your condition in.hasNextInt() made you insert input because no variable was initialized with in.nextInt but also returns either [true] or [false] so as long as its true it will add to the length variable without prompting you to insert a [new input] .so the code should look like.
Int length = 0;
int k ;
while(in.hasNextInt()) {
length++ ;
k = in.nextInt();
}
you insert the input into an initialized variable k for ex then prompt the user to further input into k after adding to [length] then the loop will check your condition without prompting user for input.
Lets look at your second while loop.
while(in.hasNextInt()) {
for(int i=0;i<length;i++) {
int x = in.nextInt();
arra[i] = x;
}
}
In in.NextInt() you are prompting the user to enter new input once again so you don't need int x.Not even the while loop .However you MUST declare a new scanner in this ex: I call it c .The code should look like this.
int [] a = new int [length];
Scanner c = new Scanner (System.in);
for(int i=0;i<length;i++) {
if (c.hasNextInt()){
a[i] = c.nextInt();
} else
break;
}
You must add the if statement because if you get an alphabet in the int array you will get an exception error .The array a[i] will not prompt the user.
Of course it isn't practical to make the user enter the values twice so a better code to implement without using ArrayList class which I think you may not know very well is by using an empty String .
NEW CODE :-
String g = "";
String j ="";
int y ;
int q=0;
int w = 0;
while (in.hasNextInt())
{
y = in.nextInt();
g =g+y+",";
q++;
}
int arra [] = new int [q];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(',')){
arra[w]=Integer.parseInt(j);
System.out.println(arra[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
Another even better code :-You just insert your numbers separated by spaces without a letter ,hit enter and the array is filled.
Scanner in = new Scanner (System.in);
String g = "";
String j ="";
int y ;
int q=0;
int i=0;
int w = 0;
System.out.println("inset your input separated by spaces");
g = in.nextLine();
while(i<g.length()){
if((g.charAt(i))==(' ')){
q++;
}
i++;
}
int a [] = new int [q+1];
for(int r =0;r<g.length();r++) {
if(g.charAt(r)==(' ')){
a[w]=Integer.parseInt(j);
System.out.println(a[w]);
w++;
j="";
}else{
j=j+g.charAt(r);
}
}
a[w]=Integer.parseInt(j);
System.out.println(a[w]);

Taking the average of an Array

I'm trying to put together a java program to do the following:
Prompt for and read in a number of integers to read
Create an array that can hold that many integers
Use a loop to read in integer values to fill the array
Calculate the average value in the array (as an integer)
This is what I have so far (although I'm pretty sure this is wrong):
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
//I don't know if I should use a while loop here or what the arguments should be
}
What should the conditions be, in order to set up the loop?
Let's look at what you need to calculate an average and what you have right now.
What you need
The total number of values
The values
Somewhere to keep the sum of values
What you have
The total number of values
A source from which to get new values
Now, from your code, you don't seem to have a place to add all your numbers. That's easy to fix; you know how to declare a new variable.
You also don't have the values, but you do have somewhere you can get them from. Since you also know how many numbers you need to sum up, you can use a loop to get that many numbers from your source.
All in all, you'll want your loop to run f times. In that loop, you'll want to get new a new number and add it to the rest. At the end, you should be able to derive the average from all that.
The better idea would be to prompt the user to enter all of the values at once, separated by spaces. IE
2 4 1 1 6 4 2 1
You can then call the split() function for Strings to split this into an array of Strings, then use the Integer.parseInt() function to turn this array of Strings into an array of ints.
Once you have your array of ints, it's a simple for loop to add all of the values together and divide by that array's length.
You can put a while loop or a for loop to input the numbers. Along with the input, keep taking the sum of the numbers. Since you have total number of values:
Average= (sum of numbers)/ total numbers.
I will write pseudo code so that it will force you to search more:
//Pseudo code starts after your array declaration
for loop from 0 to f
store it in values Array
save sum of numbers: sum= sum+values[i]
loop ends
calculate Average
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
double avg = 0;
for (int i = 0; i < f; i++)
{
value[i] = keyboard.nextInt();
avg += value[i];
}
avg /= f;
System.out.println("Average is " + avg);
}
I dont see a point of having array value. Or do you want some other kind of average ?
I wrote(with a friend) a code that calculates the average number:
package dingen;
import java.util.Scanner;
public class Gemiddelde {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
float maxCount = 0;
float avgCount = 0;
System.out.println("How many numbers do you want");
int n = sc.nextInt();
for(int i = 0; i < n; i++) {
System.out.println("Number: ");
float number = sc.nextInt();
maxCount = maxCount + number;
}
avgCount = maxCount / n;
System.out.println("maxCount = " + maxCount);
System.out.println("avgCount = " + avgCount);
}
}
the only thing you have to do is replace your class and package.
you wil get the message: How many numbers do you want?:
and then it wil ask you the amount of numbers you inserted.
example:
How many numbers do you want?:6
Number:6
Number:7
Number:8
Number:9
Number:93
Number:94
maxCount = 217.0
avgCount = 36.166668
I have hoped I helped you with your problem :)

Categories