Last iteration of for loop not outputting - java

Forgive me if this is not formatted properly, this is my first post. I looked to see if this issue has been found before and I cannot find anyone who has had the same problem I am having.
I am trying to learn Java and cannot for the life of me figure out why my for loops are not outputting the last iteration. I am going through codeabbey's exercises and completed the first two relatively easily. However on the third and fourth problems, I cant get my for loop to output during the last iteration.
I began looking on google and thought I would compare my answer to someone else's. I couldn't see why mine wouldn't work when my code was almost identical to the person I found. So I copied their code and to my surprise I had the same problem when this code also would not output on the last iteration.
So, here is the context.
The website gives you a single number first which is the number of sets of the following numbers. For the third problem, you are to add the sets of two, output the sum followed by a space and loop through the entire batch. For the fourth problem, it is similar where the first number is the number of sets in the batch but you are to compare the two numbers and output the lower number. I will copy my code here for the third problem because the code is simpler.
Here is the code:
import java.util.Scanner;
public class Summation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i = 0; i < n;i++){
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a + b + " ");
}
}
}
Here is the input you are to copy and paste:
3
100 8
15 245
1945 54
and this is my output:
108 260
So, as you can see we are missing the last output here. I tried changing the for loop to (i < (n+1) ) which still didn't change anything. Any help would be GREATLY appreciated!

Ok so I tested it, and with your numbers, typing them in one by one it works. Copy pasting them, press enter one more time at the end of the copy. If you don't press enter, the scanner thinks you're still adding to the second number so it won't continue until enter is pressed.

I would try using println() as someone else suggested, or calling flush() at the end of the program to make sure something isn't being held in a buffer and not being written.

Related

Check input continuously on one line?

I am trying to make a simple code which continously checks the user input on if the number is positive or negative and that it would all be on 2 lines.
First line being the user input and the second line being the output.
I am a beginner in coding and am not such a professional, but I have right now put the Scanner object in a while loop and it checks if the user input is positive. If it's negative then it would stop the program.
import java.util.Scanner;
public class basic {
public static void main(String[] args){
int numb;
Scanner scanner = new Scanner(System.in);
System.out.println("Fill in a random number which ain't negative!");
while((numb = scanner.nextInt()) > 0) {
System.out.println("Again!");
}
{
System.out.println("This is a negative!");
System.exit(1);
}
}
}
What I want to do is that I get this as an output and only on 2 lines:
1 2 3 4 5
Again!
And if I input a negative number on the line that it changes the 'Again!' to 'This is a negative!'
1 2 3 4 5 6 -8
This is a negative!
But with the code I have now I can only get this as an output and would get much more than just 2 lines:
1
Again!
2
Again!
-3
This is a negative!
This is console output so cannot be overwritten.
But if you are really looking to the getting required o/p printed on the console, you can use list and keep pushing digits to it and print all the items of the list.
You could use \r to rewrite the last line. Consider that:
System.out.println("\r"+yourOutput+" > ")
It replaces the last line in the console with this one, that's how loading bars in linux are done by the way :D. Use this method to display your previous inputs/numbers. User input will be in the second line. When user has pressed enter and your program has gotten the user input as string, process it and do the same thing again, this time with yourOutput updated with new info:
System.out.println("\r"+yourOutput+" > ")
Let me welcome you to your first post on StackOverflow!
It is unusual to have java applications clearing the console output. That being said, it is possible, but not without calling OS commands. As mentioned in comments, this is a little beyond beginner material if you do this.
If you want to try it though, as seen here, you can clear the console by executing a native OS command. If you use the below code (copied from the link with a minor edit)
public static void clrscr(){
//Clears Screen in java
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (Exception e) {}
}
you can call this with clrscr() in your code and you should be able to clear the screen.
Now looking at your code, you won't just be able to slip this in as you will clear the output, thus clearing the past numbers. If you want it the way that you described where you have all the user's output displayed in succession, you'll need to re-print all their entries each time you clear the screen. Thus each time you get a user's input:
You'll want to take that input and add it to a list of numbers
Clear the screen
Output that entire list
Output your evaluation
Let me know if you have questions. :-)

Coding Mastermind in Java

I was wondering how to code the game, Mastermind, in Java, but with things up a notch (I want to inform the user not only how many pegs they got right or wrong, but also how many they guessed correctly in the wrong slots).
For instance, say the RNG answer of 5 digits of numbers 1-6 is:
22354
... and the user's guess is:
32624
Resulting in:
two guessed correctly (2 and 4)
two guessed partially correct (2 and 3)
one guessed incorrectly (6).
Here's my code for informing the user what they got correct:
String answer = "22354";
String guess = "32624";
int correctPegs = 0;
for (int i = 0; i < 5; i++) {
char a = answer.charAt(i);
char g = guess.charAt(i);
if (a == g) {
correctPegs++;
}
}
System.out.println(correctPegs);
How would I find the partially correct ones?
... and for calculating how many the user guessed incorrectly, I was thinking of using basic algebra to find the remaining characters after finding the correct and partially correct ones.
I would put '0' into the strings where they match. Then for every char that is not a zero, I would look through the answer string again. If any character in the answer string matches, I would make them both zero, and increment outOfPlacePegs.
This guards against two corner cases I am assuming you do not want:
One is when you have '323' as the answer and '223' as the input. You don't want the first '2' to be recorded as out of place.
Second is when you have '223' as the answer and '442' as the input. You don't want this recorded as two numbers out of place.

Eclipse reading StdIn(System.in) from console, but will not give any output

My problem is that Eclipse's console is taking input in the console, but it never stops taking input and will not give me any output. I created a method called histogram() that takes an integer M and an array a of integers as input. My code to read input and produce output looks like
int M = StdIn.readInt();
int[] a = StdIn.readAllInts();
int[] mossah = histogram(M, a);
for (int z = 0; z < M; z++) {
StdOut.printf("%d", mossah[z]);
}
I am not allowed to use other libraries, so please do not suggest one. I was thinking that maybe there's some kind of keyboard shortcut that will make the console stop taking input but I'm not sure. I also tried using StdIn.readInts(), which gave me an error that it was depreciated, for array a's input, but it also did not work. If I assign values to array a in the code, I get my desired output, so there is nothing wrong with my method, just that code snippet I put for you guys. Any help is greatly appreciated.
Assuming you are on windows hit Ctrl-Z to send the EOF character

Clarification on Mystery

I have just started taking a Computer Science class online and I am quite new to Programming(a couple of week's worth of experience). I am working on an assignment, but I do not understand what a mystery method is. I have yet to find an answer that I can wrap my head around online, in my textbook, or from my professor. Any explanation using this code as an example would also be greatly appreciated!
This is the equation where I saw it in:
public static void mystery1(int n) {
System.out.print(n + " ");
if (n > 0) {
n = n - 5;
}
if (n < 0) {
n = n + 7;
} else {
n = n * 2;
}
System.out.println(n);
}
If anybody can help, that would be amazing! Thank you!
First of all, I voted your question up because I think it's a valid question for someone who is just beginning in computer programming, and I think that some people fail to understand the significance and purpose of Stack Overflow, which is to help programmers in times of need.
Secondly, I think that the couple of users that have commented on your post are on the right track. I have personally never heard of a mystery method, so I think the goal here is for you to simply figure out what the method does. In this case, the method takes a parameter for int 'n'. This means that if, at any point in the application, the 'mystery1()' method is called, an integer will have to be passed as the variable.
Let's say that a user enters the number '9'. The method would be called by the code mystery1(9). This would then run the first part of the 'if' statement, because n is greater than 0. So, n would be equal to n - 5, or 9 - 5, which is 4. (So, n=4.)
I hope my answer was somewhat helpful to you. Take care.
Your assignment is probably to figure out what this method does. More specifically, what does it print to the screen. I'll walk you through how to figure this out.
You have a function, also called a methood, called mystery1. A function is just a named block of code that you can use throughout other pieces of code. This function takes an integer argument called n. Let's assume n=12 for this example.
The first thing that happens in your function when it is called is that n is printed out via the System.out.print method. Notice that it prints a blank space after it. Notice also at the end it prints another value of n that gets assigned within the method. So the method is going to print "12 ?" without the double quotes. The question mark is what we have to figure out. The code says if n > 0 then n = n-5. Since 12 is greater than 0, n gets the new value of 7. The next if statement says if n is less than 0, n gets assigned n+7. But it is not less than zero, it is 7 at this point, so we move to the else statement. In this statement n gets multiplied by 2 which is 14. So the last statement prints 14.
So for an input value of 12 this method prints:
12 14
I hope this helps. If not, please give more detail about your assignment and what you don't understand about my explanation.
The point of this kind of exercise is that you are given a method, but they don't tell you what it does (hence the "mystery"). You are supposed to figure out what it does on your own (like "solving the mystery"). It doesn't mean that the method is special in any way.
Say I give you a "mystery" method like this:
public static void mystery(int n) {
System.out.println(n+1);
}
You would "solve the mystery" by telling me that this method prints out the number that comes after n. Nothing else is special here.
In the example you gave, your job would be to tell me why the method prints out 0 0 when n = 0, or 6 2 when n = 6.
I think the usage of the term "mystery method" is rather misleading, as it has clearly made you (and many, many, many others) believe that something about these methods is special and something that you need to learn about. There isn't anything special about them, and there's nothing to learn.
I think a lot of people would understand this better if instructors just said "tell me what this method does" instead of trying treat students like 5 year olds by saying "Here's a mystery method (ooh, fancy and entertaining). Can you play detective and solve the mystery for me?"

I'm having trouble with a codeabbey assignment, just need a push on how to start

I don't want the answer, I just don't understand how to scan the first number to tell the program how many pairs there are. If you could nudge me in the right direction I would greatly appreciate it.
"Most programs should be able to make some choices and decisions. And we are going to practice conditional programming now.
This is usually done by a kind of if ... else statements which may look like:
IF some_condition THEN
do_something
ELSE
do_other_thing
ENDIF
Depending on your programming language syntax could be different and else part is almost always optional. You can read more in wikipedia article on Conditional statements.
Of two numbers, please, select one with minimum value. Here are several pairs of numbers for thorough testing.
Input data will contain number of test-cases in the first line.
Following lines will contain a pair of numbers to compare each.
For Answer please enter the same amount of minimums separated by space, for example:
data:
3
5 3
2 8
100 15
answer:
3 2 15 "
Firstly, you might want to format your example data a bit. I understood it, but mostly only because I've seen that question format before.
Well, to answer your question but not the question's question (heh), note this:
Following lines will contain a pair of numbers to compare each.
Note the "lines" (plural) and the "each." We're going to need a loop.
We also know each line is a test case.
So modify the instructions:
Loop over the following test cases, comparing each pair
But how many times do we loop?
Input data will contain number of test-cases in the first line
That's the first number.
So here's our code skeleton:
//We can use a Scanner for convenience, it has a readInt() method
Scanner input = new Scanner(/*your input*/);
int numCases = input.readInt();
for(int i = 0; i < numCases; i++) {
int first = input.readInt(); //readInt() will also skip newlines, just a tip.
int second = input.readInt();
/* Compare two inputs, do stuff*/
}
For the record, you could also simply ignore the first input and just loop until there is no more input, but that's sloppy.
First you need to create a Scanner. If you're reading from the console, then this will work:
Scanner scan = new Scanner(System.in);
If you need to read from a file, then you can add this line as well.
System.setIn(new FileInputStream("inputFileName"));
For your specific case, you can do something like:
int numPairs = scan.nextInt();
You can find out more about Scanner and its methods from the Oracle documentation here.

Categories

Resources