My assignment asks to print all values from 1-10 using while loops in one output dialog box, with each number appearing on a separate line. So far I have:
int i=1;
while (i <= 10)
{
System.out.println(i);
i++;
}
and it displays 1-10 on separate lines but that's in the command prompt window. I need it to be displayed on one output box. How would I do that?
Forgot to mention, I know how to display the output in a dialog box, however it displays it one by one in separate boxes rather than in just one. How would I make it display in only one and not 10 different boxes?
What you are looking for can be found in the Java Docs. The classes, as well as how to use them can be found here:
http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
Be sure to import this:
import javax.swing.JOptionPane
When you're just printing to the console, all you have to do is change System.out.println to System.out.print:
int i = 1;
while (i <= 10)
{
System.out.print(i);
i++;
}
An alternative way to do it is this:
String s = "";
int i = 1;
while (i <= 10) {
s += i;
i++;
}
System.out.println(s);
Related
I'm writing a selenium test script for my student management system. I have a situation where I need to enter values and click the same button 15 times. So, I used a for loops for the scenario.
Here is the screen I need to test.
So, I need to add two values to mark range text boxes and select grade from the drop down list and click add button. I need to do this scenario for 15 times.
Here are the values I need to enter
Here is the drop down list.
I tried following scenario for this.
for(int x=95; x<=11; x=x-6){
driver.findElement(By.xpath("//input[#type='number']")).sendKeys(""+x);
for(int y=100; y<=16; y=y-6){
driver.findElement(By.xpath("(//input[#type='number'])[2]")).sendKeys(""+y);
for(int z=1; z<=15; z++){
Select mark2 = new Select(driver.findElement(By.xpath("//select[#id='gradeSelector']")));
mark2.selectByValue(""+z);
driver.findElement(By.xpath("//input[#value='Add']")).click();
}
}
}
but, nothing happens.
Thanks in advance. :)
Try following:
int x=95, y=100;
for(int z=1; z <=15; z++){
driver.findElement(By.xpath("//input[#type='number']")).sendKeys(""+x);
driver.findElement(By.xpath("(//input[#type='number'])[2]")).sendKeys(""+y);
Select mark2 = new Select(driver.findElement(By.xpath("//select[#id='gradeSelector']")));
//mark2.selectByValue(""+z);
mark2.selectByIndex(z);
driver.findElement(By.xpath("//input[#value='Add']")).click();
x=x-6;
y=y-6;
}
It's just the for loop logic is incorrect - the x<=11 condition never evaluates to true, replace:
for(int x=95; x<=11; x=x-6) {
with:
for(int x=95; x>=11; x=x-6) {
due to a complex issue which I do not want to enter here, I am not able to count a number of created objects(let's say apples) in a complex Java class, using a simple counter as soon as an apple is created. Therefore I was thinking of an alternativ but do not know how to realize it; if it is at all an option:
A for-loop connected to System.out.println("Apples:" + apples) gives me as many outputs as there are apples. - Which is fine. Now I have to store the number of outputs in a variable - how would you do this - is it possible at all, as the output is displayed in the console?
Thanks in advance!
you can wrap System.out.println() with your own println method that in addition to printing will count, and use that one instead of println in your loop:
private static int counter = 0;
public static void myPrintln(String str) {
counter++;
System.out.println(str);
}
I'm having problems tyring to keep score in my "guessing" game. I have to use a for loop or while loop. I have it so 10 random numbers are created in a text file called mystery.txt and a file reader reads these numbers from the text file.
Your score starts at 0. If the user guesses the correct number from the text file they get -10 points. If they get the number wrong they add the the absolute value difference of the number they guessed from a number in the file. The lower the score in the end the better.
When I only run my if else statement once, it works correctly. Once I loop it more than once it starts to act up.
I have to use an if else statement and a for or while loop. Thanks!
Edit- Turns out I have to use a for loop not a while loop, I'm completely lost now.
How it should work:
When you run the program a text file gets generated with 10 different numbers (I already have the code for that ready) The user gets asked to enter a number, the number the user enters gets compared to the first file on the text file. If it is the same never they get -10 points to their score. If they get it wrong they get the difference of the number the guessed and the number in the text file added to the score. This is suppose to repeat ten times.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class lab4Fall15 {
public static void numberGuessingGame() throws IOException {
Scanner myscnr = new Scanner (System.in);
PrintWriter mywriter = new PrintWriter("mysteryNumber.txt");
int randomNumber;
int i = 0;
i=1;
while (i<=10) {
Random randomGen = new Random();
randomNumber= randomGen.nextInt(11);
// then store (write) it in the file
mywriter.println(randomNumber);
i = i + 1;
}
//Decided to use a loop to generate the numbers-------
mywriter.close();
FileReader fr = new FileReader("./mysteryNumber.txt");
BufferedReader textReader = new BufferedReader(fr);
int numberInFile;
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
int score= 0;
int a = 1;
while (a<=10) {
a=a+1;
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber= myscnr.nextInt();
if (userNumber==numberInFile){
score = score-10;
}
else{
score = score + Math.abs(userNumber-numberInFile);
}
System.out.println ("current score is: "+score);
}
System.out.println ("your score is "+score);
textReader.close();
}
public static void main(String[] args) throws IOException {
// ...
numberGuessingGame();
}
}
if (userNumber==numberInFile){
score = score-10;
}
I don't understand what you going to mean. but I can guess this. your above code not show any error. normally , you check your , above part of code. you take variable 'numberInFile'. sometime , your file reader take this with 'whitespace or String or e.t.c' . first you check this out put .you put manual data to this variable and check out put. if it work fine , you correct that function.
OK, first, let's just go over for loops, since that's what your question was asking about. From the code you provided, it seems that you already understand while loops, and that's good, because in Java, for loops are (usually) just while loops in disguise. In general, if you have this while loop,
int a = 0;
while (a < 10) {
// do stuff with a
a = a + 1; // or ++a or a++
}
You can always rewrite it like this:
for (int a = 0; a < 10; a = a + 1) {
// do stuff with a
}
By convention (and this convention is useful when you study arrays and Collection types) you'll want to index your loops from 0 rather than 1. Since you're just learning, take my word for it for now. Loop from 0 to n-1, not from 1 to n.
With that out of the way, let's tackle why you're getting the wrong answer (which, incidentally, has nothing at all to do with loops). Rewritten as a for loop, the ask-and-score part of your program looks like this.
for (int a = 0; a < 10; ++a) {
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber = myscnr.nextInt();
if (userNumber == numberInFile){
score = score - 10;
} else {
score = score + Math.abs(userNumber - numberInFile);
}
System.out.println ("current score is: "+score);
}
You will note that nowhere in this section do you update the value of numberInFile. That means that every run of this loop is still looking at whatever value that variable had at the beginning of the loop. That value came from this line:
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
That line is executed exactly once, before the loop runs. If you want to load the next number every time the user guesses a number, you'll need to move it inside the loop. I'll leave that as an exercise to the reader.
You are not actually capturing the number the user is entering. Try this:
int userNumber = Integer.parseInt(KeyIn.readLine());
I am sure this is a pretty easy question, but I am pretty rusty on my programming. I need to write code that will show all numbers between 14859 - 26551 in sets of 13.
So far I just have the normal for loop to show all the numbers, no sure how to get sets of 13.
for(i=14859; i < 26551; i++){
System.out.println(i);
}
Assuming you want to display your numbers as Jukka said in comments:
for(i=14859; i < 26551; i++){
if((i-14858)%13==0)
System.out.println(); // or anything delimiting your sets
System.out.println(i);
}
Or if you want to display only one number every 13:
for(i=14859; i < 26551; i+=13){
System.out.println(i);
}
You can't just type i+13 as you said you tried in comments: 3rd argument in a for loop is an assignment, so you have to assign something to a variable.
for(int i=14859; i < 26551; i++)
System.out.print(((i % 13 != 0) ? ", " + i : "\n"));
I have a for loop that asks the user to input a number and then does something with it 10 times
I want a check built in that, if the user enters a non accepted input, the loop should restart its current iteration
For example if the user enters something wrong in round 3, round 3 should be restarted.
How do i do that? is there something like a REDO statement in java?
something like this ?
for(int i=0; i<10; i++){
if(input wrong){
i=i-1;
}
}
You have a couple of choices here.
Continue
The continue statement in Java tells a loop to go back to its starting point. If you're using a for loop, however, this will continue on to the next iteration which is probably not what you want, so this works better with a while loop implementation:
int successfulTries = 0;
while(successfulTries < 10)
{
String s = getUserInput();
if(isInvalid(s))
continue;
successfulTries++;
}
Decrement
This approach seems ugly to me, but if you want to accomplish your task using a for loop, you can instead just decrement the counter in your for loop (essentially, 'redo') when you detect bad input.
for(int i = 0; i < 10; i++)
{
String s = getUserInput();
if(isInvalid(s))
{
i--;
continue;
}
}
I recommend you use a while loop.
Prefer avoiding to reassign the i variable, this may lead to confusion.
for(int i=0; i<10; i++){
String command = null;
do{
command = takeCommandFromInput();
} while(isNotValid(command));
process(command);
}