Mutliple lines of a while loop printing in gui dialog (Java) - java

I want to print multiple lines of a while loop in 1 gui dialog box.
This is the code I have currently
package Tempconv1;
import javax.swing.JOptionPane;
public class TimesTables
{
public static void main(String[] args)
{
int num1 = 0, counter = 0, total = 0; //Declaring Variables
String str; //String for ShowInputDialog
str = JOptionPane.showInputDialog("Insert a number"); //Asks user to input number
num1 = Integer.parseInt(str);
//Calculating number inputs
while (counter <12)
{
counter = counter + 1;
total = counter * num1;
String multimsg = ("The calculation is " + num1 + " x " + counter + "=" + total);
JOptionPane.showMessageDialog(null, multimsg);
}
JOptionPane.showMessageDialog(null, "All Done");
}
}
It works but prints out "The calculation is 5x1 = 5" and then opens a new message box to show "The calculation is 5x2 = 10".
I want it to print out
The Calculation is 5x1 = 5
The Calculation is 5x2 = 10
etc
All inside 1 textbox

What you are telling your program to do is create a string of the individual calculation, and then create a dialog box. Then do it again for each loop.
You will want to build all of the messages into one string inside your loop, and then create the dialog box outside the loop.
String multimsg = "";
while (counter <12)
{
counter = counter + 1;
total = counter * num1;
multimsg += ("The calculation is " + num1 + " x " + counter + "=" + total);
}
JOptionPane.showMessageDialog(null, multimsg);
you might want to look into using stringbuilder or similar to be more efficient about building the message string. (https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html)

The problem is that you are showing the message inside the while loop. The syntax with the while loop can be a little bit confusing.
If you are using java 8 you can replace the while/counter with an IntStream and you can compose the message by joining the Strings in the collector:
String message = IntStream.rangeClosed(1, 12)
.mapToObj(i -> "The calculation is " + num1 + "x" + i + " = " + i * num1)
.collect(Collectors.joining(", "));
The first line creates a stream of integers from 1 to 12. The second line maps every number to an individual textmessage. The last line concatenates all the individual messages by joining them with a ,
Your main method would look something like this:
public static void main(String[] args){
int num1 = 0, counter = 0, total = 0; //Declaring Variables
String str; //String for ShowInputDialog
str = JOptionPane.showInputDialog("Insert a number"); //Asks user to input number
num1 = Integer.parseInt(str);
//Calculating number inputs
String message = IntStream.rangeClosed(1, 12)
.mapToObj(i -> "The calculation is " + num1 + "x" + i + " = " + i * num1)
.collect(Collectors.joining(", "));
JOptionPane.showMessageDialog(null, message);
JOptionPane.showMessageDialog(null, "All Done");
}

before loop:String multimsg = "";
in loop after the maths:multimsg=multimsg+"The calculation is " + num1 + " x " + counter + "=" + total;
and after while loop JOptionPane.showMessageDialog(null, multimsg);

Build only the msg inside the loop and save it to StringBuilder.
public static void main(String[] args)
{
int num1 = 0, counter = 0, total = 0; //Declaring Variables
String str; //String for ShowInputDialog
str = JOptionPane.showInputDialog("Insert a number"); //Asks user to input number
num1 = Integer.parseInt(str);
StringBuilder sb = new StringBuilder();
//Calculating number inputs
while (counter <12)
{
counter = counter + 1;
total = counter * num1;
sb.append("The calculation is ").append(num1).append(" x ").append(counter).append("=").append(total).append(" ");
}
JOptionPane.showMessageDialog(null, sb.toString());
JOptionPane.showMessageDialog(null, "All Done");
}

Related

How do i put the total sum of my input on top of my codes?

First of all here is my code
import java.util.Scanner;
public class Pengulangan {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int i, number, line, total;
int even, b = 0;
double rat;
System.out.print("Input number: ");
number = sc.nextInt();
even = number/2;
System.out.print("Total sum of number from 1 to number " + number + " is " + even + "\n");
i = 2;
line = 1;
while (i <= number) {
System.out.println("Even number-" + line + " is " +i);
line = line+1;
i = i +2;
}
total = ((number/2) * (even+1));
System.out.printf("Total sum of even number from the number " + number + " = " + total + "\n");
rat = 2*(total/number);
System.out.printf("Sum of average number from the number " + number + " = " + rat + "\n");
}
}
On this specific line on top of the second S.O.P
even = number/2;
i would like to put a loop there to find out how many Even numbers are on the input (ex- 10)
So i tried this code
int i = 1;
while (i <= number) {
if (i%2 == 0)
even = even + 1;
else
odd = odd + 1; //Not going to use this..
i++;
}
System.out.println("Total sum of even number is : ")
I tried putting that code in but i can't make it work, i tried it myself with only the code above and the results are exactly what im looking for but i can't put that in my first code ( the top one ), so i ended up using a sneaky way to get the even numbers.
I need help putting that total sum code to my main code
Sounds like a homework. You don't need loops or anything fancy, if you just want to get the sum of even numbers up to the number you input. Let n be the input number from your program and
class Main {
public static void main(String[] args) {
int n = 10;
//This is the math forumla
int total_sum_math = (((n/2)*((n/2)+1)));
System.out.println("Total sum of even number is : "+total_sum_math+"");
}
}
Reference: https://math.stackexchange.com/questions/3285727/sum-of-even-numbers-n

Adding numbers 1 to n with a loop

So the code posted works and seems to give correct values. The only problem is that it prints every line in the loop instead of just the answer. How can I make it just print the answer instead of every line leading up to it?
import java.util.Scanner;
public class CountLoop{
public static void main (String[] args){
Scanner in = new Scanner (System.in);
int i = -1;
int limit = 0;
System.out.println("Please enter a number");
String end1 = in.nextLine();
int end = Integer.parseInt(end1);
while (i < end){
i++;
limit = (i + limit);
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
}
}
}
I'm fine with using other types of loops as well, as I'll need to show an example with all the different types of loops being used anyway, so any help is appreciated.
Move your system.out.println outside of your while loop
while (i < end){
i++;
limit = (i + limit);
}
System.out.println("The sum of the numbers in between 0 and " + end + " is i = " + limit);
Or the modern version in Java 8:
int sum = IntStream.range(startInclusive,endExclusive).sum();
System.out.println("The sum of the numbers in between " + startInclusive +
" and " + (endExclusive -1) + " is sum = " + sum);
Renamed variables ;-)
limit -> sum
0 -> startInclusive
end -> endExclusive - 1

Concat String in a for loop

I'm trying to create a program that takes each number typed in by the user and sort them out as even, odd and the number zero values.
The result should look like something like this:
User Input: 14005
Output:
Even Numbers: 4
Odd Numbers: 1, 5
Zero's: 0, 0
This is the code I've written, I thought of using string concatination in order to add a new value each time the loop checks for the next character, don't know whether I'm thinking right or not though, would appriciate if someone could tell me where I'm thinking in the wrong way.
package com.craydesign;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
String number = JOptionPane.showInputDialog("Please enter a number: ");
String evenNumbers = "";
String oddNumbers = "";
String numberZero = "";
for(int i = 0; i < number.length(); i++) {
if(number.charAt(i) % 2 == 0) {
evenNumbers.concat(Integer.toString(i) + ", ");
} else if(number.charAt(i) % 2 != 0) {
oddNumbers.concat(Integer.toString(i) + ", ");
} else if (number.charAt(i) == 0){
numberZero.concat(Integer.toString(i) + ", ");
}
}
JOptionPane.showMessageDialog(null, "Even numbers: " + evenNumbers + "\n" + "Odd numbers: " + oddNumbers + "\n" + "Zero's: " + numberZero);
}
}
use Character.getNumericValue() instead of charAt(i)
public static void main(String[] args) throws IOException
{
String number = JOptionPane.showInputDialog("Please enter a number: ");
StringBuffer evenNumbers = new StringBuffer();
StringBuffer oddNumbers =new StringBuffer();
StringBuffer numberZero =new StringBuffer();
for(int i = 0; i < number.length(); i++) {
int value=Character.getNumericValue(number.charAt(i));
if(value!=0 && value % 2 == 0) {
evenNumbers.append(value).append(',');
} else if(value % 2 != 0) {
oddNumbers.append(value).append(',');
} else if (value == 0){
numberZero.append(value).append(',');
}
}
JOptionPane.showMessageDialog(null, "Even numbers: " + evenNumbers + "\n" + "Odd numbers: " + oddNumbers + "\n" + "Zero's: " + numberZero);
}
EDIT:(displaying numbers in sorted order)
String evenNo[]=evenNumbers.toString().split(",");
String oddNo[]=oddNumbers.toString().split(",");
Arrays.sort(evenNo);
Arrays.sort(oddNo);
JOptionPane.showMessageDialog(null, "Even numbers: " + Arrays.toString(evenNo) + "\n" + "Odd numbers: " + Arrays.toString(oddNo) + "\n" + "Zero's: " + Arrays.toString(numberZero.toString().substring(0,
numberZero.length()-1).split(",")));
You are using String for output and appending the output in the string.
Its a bad idea. as String class is immutable so if you do change anything in String it will create a new Object in memory.
So your solution will take extra memory.
Accroding to me you can solve this problem in two ways
Use StringBuffer class instead of String class for appending
Use ArrayList to Store your result. and iterate over the arraylist and show the output as you want.
Thanks,
Aman

Java Powers display table

I need to display an output like this:
Enter an integer: 3
Number Squared Cubed
====== ======= =====
1 1 1
2 4 8
3 9 27
But instead, when I run the code, I get this output:
Number Squared Cubed
====== ======= =====
3 9 27
In other words, I need to display the powers of an integer,including the powers of the numbers less than or equal to the integer. The numbers of the lesser integers need to be listed but are not displayed along with the integer being entered. How do I fix the code to make sure it outputs all of the integers that are less than or equal to the integer being entered? There are no errors (i.e. red exclamation mark circles) but I need to figure out the proper calculation.
Here is the code:
====================
import java.util.Scanner;
public class Powers
{
public static void main(String[] args)
{
System.out.println("Welcome to the Squares and Cubes Table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
// get the input from the user
System.out.println("Enter an Integer: ");
int integerNext = sc.nextInt();
System.out.println("Number" + " " + "Squared" + " " + "Cubed");
System.out.println("======" + " " + "======" + " " + "======");
for(int i = 1; i <= integerNext; i++)
{
i = integerNext;
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow (i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.println(message);
System.out.println();
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
}
Help is always appreciated. Thanks.
Firstly, as Nikhil said: "Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed".
Secondly, move the first closing curly brace to before getting user input - you want to run the loop, and only ask about continuing when that's finished, if I understand correctly.
Remove the line i = integerNext; It is resetting the value of I and therefore only last row is printed
Your are almost there. Since you are looping from 1 to integerNext (which is 3 in your text), the looping variable i will get the values [1,2,3] each iteration, so you don't have to set i manually. When you do:
i = integerNext;
you are setting i to 3, so the loop will finish when it reaches the loop condition.
You may also want to put the "Continue?" check outside the loop:
for (int i = 1; i <= integerNext; i++) {
int numberSquared = (int) Math.pow(i, 2);
int numberCubed = (int) Math.pow(i, 3);
String message = "\n" + i + " " + numberSquared + " " + numberCubed;
System.out.print(message);
}
// see if the user wants to continue
System.out.print("\nContinue? (y/n): ");
choice = sc.next();
System.out.println();
import java.util.Scanner;
public class SquaresAndCubes {
public static void main(String[] args)
{
// Welcome the user
System.out.println("Welcome to the Squares and Cubes table");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
do
{
// Get input from the user
System.out.print("Enter an integer: ");
int integer = sc.nextInt();
// Create a header
String header = "Number " + "Squared " + "Cubed " + "\n"
+ "====== " + "======= " + "===== ";
System.out.println(header);
int square = 0;
int cube = 0;
String row = "";
for (int i = 1; i <= integer; i++)
{
square = i * i;
cube = i * i * i;
row = i + " " + square + " " + cube;
System.out.println(row);
}
// See if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
while (!choice.equalsIgnoreCase("n"));
}
}
Basic way to do it with foor loop and some printlines
Scanner sc = new Scanner(System.in);
System.out.print("What number would you like to go up to? ");
int userInt = sc.nextInt();
System.out.println("");
System.out.println("Here is your table!");
System.out.println("");
System.out.println("number | squared | cubed");
System.out.println("------ | ------- | -----");
for (int i = 1; i <= userInt; i++){
System.out.println(i + " | " + (i * i) + " |" + " " +(i * i * i));
}

Need help for my raffle program in java netbeans

I'm new to java programming and currently making this raffle program. Here is the sample output of the program.
Welcome to raffle 2013!
The Prize is <10 million - 100 million> //this is random. I already made.
Ticket number: <Generating unique 10 digits numbers>
//these are the required information for the user.
Name:
Address:
Contact:
Birthday:
//The final output
The winner of <PRIZE> is <NAME>, Ticket number.
I already have written some source code and I think I'm almost there. Unfortunately, I encountered a problem with the ticket number. The ticket number must generate 5 times with 10 digits number. The output must show the winner name together with his/her ticket number but the ticket number wasn't show and state that it is null. Here are the syntax I already made.
public class raffle2013 {
//Title: Raffle 2013
public static final int SIZE = 5;
public static final int SIZE1 = 5;
private static short x;
private static String randomNumber;
public static void main(String[] args) {
String[] names;
names = new String[SIZE];
String[] winner;
winner = new String[SIZE1];
System.out.println("Welcome To Raffle 2013");
long Low = 10000000;
long High = 100000000;
long randomPrize = (long) (Math.random() * High - Low) + Low;
System.out.println("The Prize is " + " " + randomPrize);
for (int a = 0; a < winner.length; a++) {
long randomNumber = (long) (Math.random() * 9000000000L);
System.out.println("Ticket number: " + randomNumber);
Scanner scan = new Scanner(System.in);
System.out.print("Name " + ":");
winner[a] = scan.nextLine();
Scanner scan2 = new Scanner(System.in);
System.out.print("Address" + ":");
names[x] = scan.nextLine();
Scanner scan3 = new Scanner(System.in);
System.out.print("Contact" + ":");
names[x] = scan.nextLine();
Scanner scan4 = new Scanner(System.in);
System.out.print("Birthday" + ":");
names[x] = scan.nextLine();
System.out.println(" ");
}
Random random = new Random();
int w = random.nextInt(SIZE1);
System.out.println("The winner of" + " " + randomPrize + " " + "Million Peso(s)" + "is" + " " + winner[w] + "," + " " + "Ticket Number:" + " " + randomNumber);
}
}
Note: the program can generate 10 digits unique numbers for the ticket number and generate it 5 times together with the names, however I have a problem of choosing the ticket number winner.
Here is the output in java netbeans:
run:
Welcome To Raffle 2013
The Prize is 38375493
Ticket number: 1991318978
Name :a
Address:a
Contact:a
Birthday:a
Ticket number: 194313423
Name :b
Address:b
Contact:b
Birthday:b
Ticket number: 6017170047
Name :c
Address:c
Contact:c
Birthday:c
Ticket number: 274411236
Name :d
Address:d
Contact:d
Birthday:d
Ticket number: 6183250376
Name :e
Address:e
Contact:e
Birthday:e
The winner of 38375493 Million Peso(s)is a, Ticket Number: null<--- bug
BUILD SUCCESSFUL (total time: 18 seconds)
the last output must show the winner name together with his/her ticket number. I hope you could help me. Please :)
Actually you have created randomNumber of String type outside the loop , while inside you have created randomNumber of type long...this long type is only accessible within the loop and the randomNumber you are calling is the one which is string type and it is null because you havent assigned any value to it..
What you have to do is to have an array of the randomNumber and save the ticket numbers as well and in the last as you are getting the winner[w] the same way you get randomNumber[w]
Looks like you're running into an issue with scope. You may also be slightly confused about data types, but let's see...
randomNumber is assigned as a long inside of your loop, but it is declared as a static String inside your class. The declaration inside of the loop is not applicable when coming to a wider scope (that is, inside of your main method), so you won't get any pertinent values from randomNumber.
That's weird in and of itself - the different data types don't make sense to me. You also don't need the static declaration of randomNumber either - it's only ever used in main, so you could just declare it there.
To get around that, you have to wrap the output from your random input instead, and drop the declaration:
randomNumber = Long.toString(Double.valueOf(Math.random() * 9000000000L).longValue());
Also, as a code smell, you've got too many Scanner instances; you should only really need one. I leave that as an exercise to the reader to clean up and refactor.
Similar to storing the winner, the ticket number has to be stored as well, and recalled when the output is printed
import java.util.Random;
import java.util.Scanner;
public class raffle2013 {
// Title: Raffle 2013
public static final int SIZE = 5;
public static final int SIZE1 = 5;
private static short x;
private static String randomNumber;
public static void main(String[] args) {
String[] names;
names = new String[SIZE];
String[] winner;
winner = new String[SIZE1];
long[] ticketNumber = new long[SIZE1];
System.out.println("Welcome To Raffle 2013");
long Low = 10000000;
long High = 100000000;
long randomPrize = (long) (Math.random() * High - Low) + Low;
System.out.println("The Prize is " + " " + randomPrize);
for (int a = 0; a < winner.length; a++) {
long randomNumber = (long) (Math.random() * 9000000000L);
System.out.println("Ticket number: " + randomNumber);
Scanner scan = new Scanner(System.in);
System.out.print("Name " + ":");
winner[a] = scan.nextLine();
ticketNumber[a] = randomNumber;
Scanner scan2 = new Scanner(System.in);
System.out.print("Address" + ":");
names[x] = scan.nextLine();
Scanner scan3 = new Scanner(System.in);
System.out.print("Contact" + ":");
names[x] = scan.nextLine();
Scanner scan4 = new Scanner(System.in);
System.out.print("Birthday" + ":");
names[x] = scan.nextLine();
System.out.println(" ");
}
Random random = new Random();
int w = random.nextInt(SIZE1);
System.out.println("The winner of" + " " + randomPrize + " "
+ "Million Peso(s)" + "is" + " " + winner[w] + "," + " "
+ "Ticket Number:" + " " + Long.toString(ticketNumber[w]));
}
}

Categories

Resources