Displaying loop in JOptionPane - java

I'm a beginner in Java programming, and I have an assignment on while loops.
The assignment was to have windows open up with the numbers 1-10 on display.
The first two, I got down. The third one was to have the user enter a number 'x', and the next window was to show all integers between 1 and 'x' using a while loop.
As I have it coded now, each loop iteration pops up in it's own window, instead of all at once, in one window.
TL;DR I want to have 1 window with 10 loops, not 10 windows with 1 loop each.
JOptionPane and while loops were in the handouts and notes he had us take, but no mention of how to combine them.
import javax.swing.JOptionPane;
public class Pr27
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
JOptionPane.showMessageDialog(null, "1 2 3 4 5 6 7 8 9 10");
String text;
text=JOptionPane.showInputDialog("Please enter a number: ");
int f,x;
f=0;
x=Integer.parseInt(text);
while (f<=x)
{//What am I doing wrong between here
JOptionPane.showMessageDialog(null, f);
f++;
}//and here?
}
}

I believe that you wish to print out all numbers from x that are less than or equal to f in a single DialogBox and not every time the loop iterates.
import javax.swing.JOptionPane;
public class Pr27
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10");
JOptionPane.showMessageDialog(null, "1 2 3 4 5 6 7 8 9 10");
String text;
text = JOptionPane.showInputDialog("Please enter a number: ");
int f, x;
//if you wish to loop from 1 to x then f must start at 1 and not 0 because in your loop you print out f before it increases thus it would be 0.
f = 1;
x = Integer.parseInt(text);
StringBuilder sb = new StringBuilder();
while (f <= x)
{
//rather than show a message dialog every iteration append f and a new line to a StringBuilder for later use.
sb.append(f).append("\n");
//JOptionPane.showMessageDialog(null, f);
f++;
}
//string builder has a "\n" at the end so lets get rid of it by getting a substring
String out = sb.substring(0, sb.length() - 1);
JOptionPane.showMessageDialog(null, out);
}
}

Related

Java - Have Loop Repeat if Value is > 10

first question here.
So for both of these loops I am looking for the user to input a value less than 10 for loop 1 and less than 200 for loop 2. It is almost working to my liking however when a user enters an incorrect number the loop just exits where it should repeat and ask the user for another digit smaller than 10/200.
Any assistance is greatly appreciated.
public class Main {
public static int numberOfStars;
public static void main(String[ ] args){
//ask for number of stars (user-input)
System.out.println("Enter the number of stars in your constellation");
Scanner stars = new Scanner(System.in);
if (numberOfStars <= 10) {
numberOfStars = stars.nextInt();
}do{
System.out.println("The number of stars is : " + numberOfStars);
} while (numberOfStars <= 10);
//ask for location of stars (user-input)
System.out.println("Enter X and Y co-ordinates for your constellation");
//obj 1
Scanner myObj = new Scanner(System.in);
while(myObj.nextInt() <= 200) {
int location = myObj.nextInt();
System.out.println("X coordinate 1 is : " + location);
} do {
System.out.println("Please enter a Number Less than 200");
} while (myObj.nextInt() > 200 );
You could put all the code in your main mathod in a while(true) loop as you are invoking a blocking method. If you succeed (if the value is correct) you can just break the main loop (e.g. by marking it with a label). Otherwise continue the main loop which makes the input prompt appear again.

Multiple values with only one scanner method?

I have an assignment where I need to do certain calculations in separate methods using data entered by the user. My problem is with the user input. It is supposed to be done with a separate method (I do not think I am allowed to use arrays for storing the inputs). The user should be able to enter as many values they want and then exit with "q". The program should then take the first two numbers, calculate e.g. an area and volume with those (with other methods I did not include here), present the result, take the next two numbers the user entered, calculate and present results. This should be repeated until it reaches the "q" value. So for example:
Enter your values: 9 5 3 7 q
radius: 9 height: 5
Area = 254
Volume = 424
radius: 3 height: 7
Area = 28
Volume = 65
A problem I am having is that only the first value is assigned to a variable and then the user has to enter data again for the next variable, even though there's still more numbers left from the first time.
import java.util.Scanner;
public class Stack {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int radie, height;
radie = userInput("");
height = userInput("");
}
public static int userInput(String message) {
int number = Integer.MAX_VALUE;
while (number == Integer.MAX_VALUE) {
System.out.print(message);
if (input.hasNextInt()) {
number = input.nextInt();
}
input.nextLine();
}
return number;
}
}
I understand there are massive flaws in my code here, I'm very lost and not sure where to even start with solving the problem. Any help or tips are very welcome! Thanks in advance!
Did you read 'Scanner.hasNextInt()' method documentation?
There is written:
Returns:
true if and only if this scanner's next token is a valid int value
So question if
number == Integer.MAX_VALUE
doesn't make sens.
Try to ask if hasNextInt()
returns true or false
Edit: Also
Why do you assume that after number is always 'q'?
Change condition in while statement
Don't really understand your mean, but i did some changes:
import java.util.Scanner;
public class stack {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
userInput();
}
public static void userInput() {
while (true) {
System.out.println("Enter your values:");
String message = input.nextLine();
//Split data with space
String[] data = message.split(" ");
int pointer = 2;
for (String i : data) {
if (i.equals("q")) {
System.out.println("Stopped.");
System.exit(0);
}
if (pointer % 2 == 0) {
System.out.println("radius: " + i);
}
if (pointer % 2 == 1) {
System.out.println("height: " + i);
}
pointer++;
}
}
}
}
Affect:
Enter your values:
1 2 3 4 5 6 7 8
radius: 1
height: 2
radius: 3
height: 4
radius: 5
height: 6
radius: 7
height: 8
Enter your values:
1 q
radius: 1
Stopped.
Process finished with exit code 0

How to number each line in the output using a for loop?

import java.util.Scanner;
public class LoveCS
{
public static void main(String[] args)
{
int noTimesPrinted;
Scanner scan = new Scanner(System.in);
System.out.print("How many times should the message be printed: ");
noTimesPrinted = scan.nextInt();
int count = 1;
while (count <= noTimesPrinted)
{
System.out.println(" I love Computer Science!!");
count++;
}
}
}
Instead of using constant LIMIT, ask the user how many times the message should be printed. You will need to declare a variable to store the user’s response and use that variable to control the loop. (Remember that all caps is used only for constants!)
I HAVE COMPLETED PART1. I AM STUCK ON PART2. How do I get the number sequence??
Number each line in the output, and add a message at the end of the loop that says how many times the message was printed. So if the user enters 3, your program should print this:
1 I love Computer Science!!
2 I love Computer Science!!
3 I love Computer Science!!
Printed this message 3 times.
If the message is printed N times, compute and print the sum of the numbers from 1 to N.
So for the example above, the last line would now read:
Printed this message 3 times. The sum of the numbers from 1 to 3 is 6.
Note that you will need to add a variable to hold the sum.
You have a few choices. You could use String concatenation,
int count = 1;
while (count <= noTimesPrinted)
{
System.out.println(Integer.toString(count) + " I love Computer Science!!");
count++;
}
System.out.println("Printed this message " + noTimesPrinted + " times");
Or with printf and (since you said you wanted a for loop) something like
for (int count = 1; count <= noTimesPrinted; count++) {
System.out.printf("%d I love Computer Science!!%n", count);
}
System.out.printf("Printed this message %d times%n", noTimesPrinted);

Unknown runtime error in java

I want to create a class that simulates registers of a market and the project requires that after the user gives us how many registers he wants , he must give a string in the form below:
for exaple : 0 0 0 1 1 1 2 2 2 3 3 5 5 6 6
which means that 3 customers entered the store at monent 0 , 3 customers entered the store at moment 1 etc.
Here is my code:
import java.util.Scanner;
import java.io.*;
public class QueueSimulation
{
public static void main(String[] args)
{
int a;
int i = 0;
String input;
Scanner s = new Scanner(System.in);
int A[] = new int[10000];
System.out.println("This programs simulates a queue of customers at registers.");
System.out.println("Enter the number of registers you want to simulate:");
a = s.nextInt();
while(a==0 || a <0){
System.out.println("0 registers or no registers is invalid. Enter again: ");
a = s.nextInt();
}
int fifo[] = new int[a];
System.out.println("Enter how many customers enter per second.For example: 0 0 1 1 2 2 2 3 3.
Enter : ");
input = s.nextLine();
while(s.hasNext()){
while(s.hasNextInt()){
A[i] = s.nextInt();
i++;
}
s.close();
}
s.close();
}
}
The code compiles fine , but when i run it, something goes very wrong with the 2 while loops and the programs nevers end or stop. Complile if you have the time and you will understand. I dont know maybe i placed the close() method somewhere wrong? Please help.
You are missing a s.next(); in the given code.
while(s.hasNext()){
while(s.hasNextInt()){
A[i] = s.nextInt();
i++;
}
// here s.next() is missing...
s.close();
}
Please add the s.next(); statement before the end of second-while loop of your program for proper iteration of your program...

Showing process completed but no output is coming up

I am trying to create a program that accepts two numbers and outputs the smallest digit in one number that is larger than the other number(for example, given 4687 and 5, the program should output 6).
The problem that I'm having is that when I compile the program, even though I'm getting no errors, after inputting the two numbers, no output is being shown. The cursor just continues blinking where it is. This is the code:
import java.io.*;
import java.util.*;
public class Numbers {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int smallest = 10;
int num;
System.out.printf("Enter a value for n: \n");
int n = in.nextInt();
System.out.printf("Enter a value for num: \n");
num = in.nextInt();
int ch = System.in.read();
while (ch>n && ch<smallest) {
smallest=ch;
ch = System.in.read();
}
System.out.printf("Smallest number that is larger is %d", smallest);
}
}
I ran your program just fine. What you are experiencing is probably just that the program is waiting on input from you that you do not expect to enter.
It's expecting three inputs from the user, is that how you ran it?
Did you remember to hit the enter button on your keyboard after you input the numbers?
Here's a sample output from your program:
Enter a value for n:
100
Enter a value for num:
2
0 // <-- This value corresponds to your program prompting for int ch = System.in.read();
Smallest number that is larger is 10D
HINT: You probably want to convert the value entered for n to a String, then use the toCharrArray() method on String so you can traverse each character, like what you're doing in the while loop.
Try something like:
for(char ch : Integer.toString(n).toCharArray()) {
// rest of your while loop logic
}

Categories