Program Output Problems (Java) - java

I was given an assignment to write a program which will accept any number of input data until 999 has been read. Then the program should type out total number of zero's and various other requests, but the problem is I don't know the output command to tell it to read the number of zeros. All I have so far is
import java.util.Scanner;
public class MidtermI {
public static void main(String args[]) {
Scanner console = new Scanner(System.in);
int numbers = console.nextInt();
and then from there I'm lost.

Break it down into small steps, and check that each step works before going further:
The first thing you need to sort out is to be able to read multiple inputs, by looping. Your current code only reads a single number from the Scanner.
Next, you need to check for the special value 999, and stop looping when that is received.
When you have got that working, figure out how to count the zeros - either by counting them as they arrive, or collecting all the values and counting them afterwards.
You can then print out the required results using System.out.println() - but you'll probably want to use that for testing and debugging your code as you go along, anyway.

Create ArrayList to hold the zero values the print its size.
ArrayList<Integer> zeroValues = new ArrayList<Integer>();
Then loop n time to input n numbers:
for(int i=0; i<999; i++) {
int numbers = console.nextInt();
if(number == 0) {
zeroValues.add(number);
}
}
Then you could print the total of zero's values like:
System.out.println(zeroValues.size());

Related

JAVA - Program functions as input output, input output; want to make it so program functions as input input, output, output, respectively

I've just started learning Java, and I wanted to overcome a hurdle that showed up when trying to create a Java program for this 'problem'. This is the problem I had to create a program for:
Tandy loves giving out candies, but only has n candies. For the ith person she gives a candy to, she gives i candies to that person. For example, she first gives Randy 1 candy, then gives Pandy 2 candies, then Sandy 3. Given n, how many people can she give candies to?
Input Format
The first line is an integer x, denoting the number of test cases.
The next x lines will contain a single positive integer, n.
SAMPLE INPUT
2
1
5
Output Format
x lines, with each line containing a single integer denoting the number of people Tandy can give candies to.
SAMPLE OUTPUT
1
2
To solve this problem, I created a program, and it functions well, but it doesn't match what the problem is asking for.
The code:
import java.util.Scanner;
public class PRB1CandyGame {
public static void main(String[] args)
{
Scanner cases = new Scanner(System.in);
int repeats = cases.nextInt();
while (repeats > 0)
{
int x = cases.nextInt();
int i = 1;
for(i = 1; x-i>=0; i++)
{
x = x-i;
}
System.out.println(i-1);
repeats--;
}
}
}
(Sorry if the code is messy!)
My code takes in the number of 'cases' and then that's how many times I can enter in a number of candies to get the number of people it can provide. However, my program takes the number of candies and then outputs the number of people right after, while I want it to take in all the inputs (number of inputs is based on what the user enters for the number of cases), and then output all the values, rather than what I have. If you can explain to me how I can do that, it will help a lot.
Thanks!
From my understanding, you want your input to be stored some where first before you start processing answers then output all answers at once.
I Honestly think the question wants you to process each test case as input then output the result. So you're presently on the right track.
But if you want to get all inputs then process each one then output, use an array since you know the size of the test case. You will also need to create an array of same size for output then process each ith item in the input array and store each result in the same ith position in the output array.
Hope this helps

Save Integers with the Scanner class

I have a quick question about the Scanner class.
I had an idea to make a simple program that starts to count all the numbers I write in, but if it goes over a limit it should stop.
This is not the problem....
The problem is that the FIRST number you write in should be the number that tells the program how many numbers it will be counting.
For an example.
When the program starts, I will write in for example :
3
100
234
546
Sum: 880.
and the output should be the sum of 100+234+546.
The number 3 in the beginning just told the program that it is 3 numbers that it should read. I don't understand how to make the first number the number that tells the program how many numbers it should be in the input before it starts to count.
If you are using Java 8, you can do something like this:
Scanner scan = new Scanner(System.in);
int N = scan.nextInt(); //First number is the count of numbers
//line below loops for you and sums at the end
int sum = IntStream.range(0, N).map(i -> scan.nextInt()).sum();
use this code
void yourMethod()
{
int sum=0;
Scanner scan = new Scanner(System.in);
int conut=scan.next();
for(int i=0;i<count;i++)
{
sum=sum+scan.next();
}
}
Store the first number in a variable called counter or similar, and then execute a loop (for, while) for counter times, in each iteration you will read the next number and sum them. The algorithm seems very straightforward to create code from it.
How about:
Scanner scan = new Scanner(System.in);
int count = scan.nextInt();
while(count>0){
//your logic
count--;
}

Adding unknown number of numbers to arraylist

I'm trying to make an Insertion Sort algorithm in Java, and I want it to read user input, and he/she can put however many numbers they wish (We'll say they're all integers for now, but long run it would be nice to be able to do both integers and doubles/floats), and I want the algorithm to sort them all out. My issue is that when I run this code to see if the integers are adding correctly, my loop never stops.
public class InsertionSort {
public static void main(String[] args){
System.out.println("Enter the numbers to be sorted now: ");
ArrayList<Integer> unsortNums = new ArrayList<Integer>();
Scanner usrIn = new Scanner(System.in);
while(usrIn.hasNextInt()) {
unsortNums.add(usrIn.nextInt());
System.out.println(unsortNums); //TODO: Doesn't stop here
}
sortNums(unsortNums);
}
}
Now, I suspect it has something to do with how the scanner is doing the .hasNextInt(), but I cannot for the life of me figure out why it isn't stopping. Could this be an IDE specific thing? I'm using Intellij Idea.
Let me know if I left anything out that I need to include.
Your code will stop as long as you stop adding numbers to your input stream. nextInt() is looking for another integer value, and if it can't find one, it'll stop looping.
Give it a try - enter in any sequence of characters that can't be interpreted as an int, and your loop will stop.
As a for-instance, this sequence will cease iteration: 1 2 3 4 5 6 7 8 9 7/. The reason is that 7/ can't be read as an int, so the condition for hasNextInt fails.
When using a scanner on System.in, it just blocks and waits for the user's next input. A common way of handling this is to tell the user that some magic number, e.g., -999, will stop the input loop:
System.out.println("Enter the numbers to be sorted now (-999 to stop): ");
List<Integer> unsortNums = new ArrayList<Integer>();
Scanner usrIn = new Scanner(System.in);
int i = usrIn.nextInt();
while(i != -999) {
unsortNums.add(i);
i = usrIn.nextInt();
}

Fibonacci sequence with arrays

I have the task of writing a program using the fibonacci sequence and putting them into arrays. It works by getting user input ( how many numbers in the sequence the user wants to print out) and then it implements that into an array and prints out the sequence with the number of 'numbers' the user inputed.
As I missed out on 2 weeks of class I looked online on how to write this program and found a video which the following code was written. So I do not take credit for the following code, I'm merely using it as an example.
Anyway here's the code:
public class Fibonacci
{
public static void main(String[] args)
{
int numToPrint;
//how many numbers to print out
Scanner scan = new Scanner(System.in);
System.out.println("Hvað viltu prenta út margar tölur úr Fibonacci röðinni?");
numToPrint = scan.nextInt();
scan.close();
//prints out the first 2 numbers
int nuverandiT = 1;
int lokaT = 0;
System.out.println(lokaT);
System.out.println(nuverandiT);
//prints out the rest of the sequence
int lokaLokaT;
for(int i = 2; i < numToPrint; i++)
{
lokaLokaT = lokaT;
lokaT = nuverandiT;
nuverandiT = lokaLokaT + lokaT;
System.out.println(nuverandiT);
}
}
}
Now this prints out the fibonacci sequence with input from the user, but I'm not quite sure how to make it print out into an array. Do any of you guys know how to do this?
You have to create an array, for example:
int[] simpleArray;
simpleArray = new int[numToPrint];
At the place of
System.out.println(lokaT);
System.out.println(nuverandiT);
Put:
simpleArray[0] = lokaT;
simpleArray[1] = nuverandiT;
And inside your loop, you put instead this:
System.out.println(nuverandiT);
This:
simpleArray[i] = nuverandiT;
I'm guessing when you say 'print out into an array' you really mean you just want to store the values in an array. In that case,
Before your for loop:
int[] array = new int[numToPrint];
And inside your for loop:
array[i-2] = nuverandiT;
If you wanted to print the numbers once they've been stored in an array, you would probably want to loop through it and print in the same fashion, accessing the elements by index. For more information, the java documentation is very good. I recommend reading up on arrays and counted loops.

Why isn't the nextInt() method working?

I've typed it exactly as shown in Introduction to Java Programming (Comprehensive, 6e). It's pertaining to reading integer input and comparing user input to the integers stored in a text file named "lottery.txt"
An external link of the image: http://imgur.com/wMK2t
Here's my code:
import java.util.Scanner;
public class LotteryNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Defines and initializes an array with 100 double elements called isCovered.
boolean[] isCovered = new boolean[99];
// Prompts user for input and marks typed numbers as covered.
int number = input.nextInt();
while (number != 0) {
isCovered[number - 1] = true;
number = input.nextInt();
}
// Checks whether all numbers are covered.
boolean allCovered = true;
for (int i = 0; i < 99; i++)
if (!isCovered[i]) {
allCovered = false;
break;
}
// Outputs result.
if(allCovered) {
System.out.println("The tickets cover all numbers."); }
else {
System.out.println("The tickets do not cover all numbers."); }
}
}
I suspect the problem lies within the declaration of the array. Since lottery.txt does not have 100 integers, the elements from index 10 to 99 in the array are left blank. Could this be the problem?
Why does the program terminate without asking for user input?
Possible Solution:
After thinking for a while, I believe I understand the problem. The program terminates because it takes the 0 at the EOF when lottery.txt is feed in. Furthermore, the program displays all numbers not to be covered because the elements from 11 to 100 are blank. Is this right?
The program is written to keep reading numbers until a zero is returned by nextInt(). But there is no zero in the input file, so the loop will just keep going to the end of the file ... and then fail when it tries to read an integer at the EOF position.
The solution is to use Scanner.hasNextInt() to test whether you should end the loop.
And, make sure that you redirect standard input from your input file; e.g.
$ java LotteryNumbers < lottery.txt
... 'cos your program expects the input to appear on the standard input stream.

Categories