String output to display message to user - java

When using my code I am receiving an output message stating that each number that I have entered is prime, even if it is not a prime number. How can I change my output message to reflect the correct is or is not prime result? Here is my code:
public static void main (String [] args){
//prompt user to input a number
String input = JOptionPane.showInputDialog("Enter number ");
// change string to int
int number = Integer.parseInt(input);
//display message to user of their results
BigInteger num = new BigInteger(input);
String output = number + " is" + (BigInteger(input) ? " " : " not ") + "a prime number: " + BigInteger(input);
JOptionPane.showMessageDialog (null, output);
}
public static Boolean IsPrime(BigInteger num) {
// check if number is a multiple of 2
if (num.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
return false;
}// if not, then just check the odds
for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(num) <= 0; i =
i.add(new BigInteger("2"))) {
if (num.mod(i).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
return true;
}

I think you're having an issue here -
String output = number + " is"
+ (BigInteger(input) ? " " : " not ") + "a prime number: "
+ BigInteger(input);
And you want something more like this -
String output = num + " is"
+ (IsPrime(num) ? " " : " not ") + "a prime number.";
I tested your IsPrime function, and it correctly identified 5 as prime and 4 as not prime. You should probably rename it isPrime to be inline with Java naming conventions.
EDIT
public static void main(String[] args) {
// prompt user to input a number
String input = JOptionPane.showInputDialog("Enter number ");
// change string to int
int number = Integer.parseInt(input);
// display message to user of their results
BigInteger num = new BigInteger(input);
String output = num + " is" + (IsPrime(num) ? " " : " not ")
+ "a prime number.";
JOptionPane.showMessageDialog(null, output);
}

I guess you simply was wrong in the main code; try with this one;
public static void main (String [] args){
//prompt user to input a number
String input = JOptionPane.showInputDialog("Enter number ");
// change string to int
int number = Integer.parseInt(input);
//display message to user of their results
BigInteger num = new BigInteger(input);
String output = number + " is" + (IsPrime(num) ? " " : " not ") + "a prime number: " + number;
JOptionPane.showMessageDialog (null, output);
}
Angelo

Related

How can I use throw exception in this context?

So for this assignment, it asks the user to enter a phone number, then it splits the number up into a category of each set of integers. What I'm attempting to do is to throw a simple exception that if they do not enter the parenthesis for the area code that it throws the exception but doesn't crash the program and asks them to re-enter using the correct format
public class App{
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
String inputNum;
String token1[];
String token2[];
String areaCode;
String preFix;
String lineNum;
String fullNum;
System.out.print("Enter a phone number in (123) 123-4567 format: ");
inputNum = input.nextLine();
System.out.println();
token1 = inputNum.split(" ");
areaCode = token1[0].substring(1, 4);
if (token1[0].substring(0, 3) != "()"){
throw new Exception("Enter a phone number in (123) 123-4567 format: ");
}
token2 = token1[1].split("-");
preFix = token2[0];
lineNum = token2[1];
fullNum = "(" + areaCode + ")" + " " + preFix + "-" + lineNum ;
System.out.print("Area code: " + areaCode + "\n");
System.out.print("Prefix: " + preFix + "\n");
System.out.print("Line number: " + lineNum + "\n");
System.out.print("Full number: " + fullNum);
}
}
No need to throw. Just keep asking in a loop.
String areaCode;
String preFix;
String lineNum;
while (true) {
System.out.print("Enter a phone number in (123) 123-4567 format: ");
String inputNum = input.nextLine();
System.out.println();
String [] token1 = inputNum.split(" ");
if (token1.length == 2 && token1[0].length() == 5
&& token1[0].charAt(0) == '(' && token1[0].charAt(4) == ')') {
areaCode = token1[0].substring(1, 4);
String [] token2 = token1[1].split("-");
if (token2.length == 2 && token2[0].length() == 3 && token2[1].length() == 4) {
preFix = token2[0];
lineNum = token2[1];
// If we reach this line all is ok. Exit the loop.
break;
}
}
}
String fullNum = "(" + areaCode + ")" + " " + preFix + "-" + lineNum ;
System.out.print("Area code: " + areaCode + "\n");
System.out.print("Prefix: " + preFix + "\n");
System.out.print("Line number: " + lineNum + "\n");
System.out.print("Full number: " + fullNum);

how do I pass a user inputted integer through methods?

Essentially i've isolated the issue, the int numpersons begins as 0. I take a user input to make it a particular number which is the array size, when the second method begins it takes the 0 again and then the array has an out of bounds exception. I want to pass it from one method to the next, or make them more successive, idk how to do this
thanks in advance
import java.util.Scanner;
public class BankApp {
Scanner input = new Scanner(System.in);
int numpersons = 0;
private SavingsAccount[] clients = new SavingsAccount[numpersons];
public BankApp() {
while (numpersons < 1) {
System.out.println("How many people are there?");
numpersons = input.nextInt();
if (numpersons < 1 || 2147483647 < numpersons) {
System.out.println("invalid number, please enter again");
}
}
input.nextLine();
}
public void addClients() {
int i = 0;
while (i < numpersons) {
System.out.println("enter account id " + (i + 1));
String AccountID = input.nextLine();
System.out.println("enter account name " + (i + 1));
String AccountName = input.nextLine();
System.out.println("enter account balance " + (i + 1));
Double AccountBalance = input.nextDouble();
clients[i] = new SavingsAccount(AccountID, AccountName, AccountBalance);
input.nextLine();
i++;
}
}
public void displayClients() {
int i = 0;
while (i < numpersons) {
System.out.println("======================================");
System.out.println("Account ID " + (i + 1) + ": " + clients[i].getID());
System.out.println("Account Name " + (i + 1) + ": " + clients[i].getName());
System.out.println("Account Balance " + (i + 1) + ": " + clients[i].getBalance());
System.out.println("======================================");
i++;
}
}
public static void main(String args[]) {
BankApp ba = new BankApp();
ba.addClients();
ba.displayClients();
}
}

String Method-converting string to char then display the characters with a specified index

I'm trying to make a code regarding string methods that accepts a string and returns the value of getChars. Indexes or indices should be an input from the user. A string should be converted to an array of character which will be used as destination. However, I'm having some confusing errors.
Any help?
Here's the code/.
import java.util.*;
public class Exercise5 {
public static void main(String[] args) {
//Stay Calm and Be Cool!
Scanner a = new Scanner(System.in);
String string = new String();
System.out.print("Enter any String: ");
string = a.nextLine();
System.out.print("Enter source begin index: ");
int begin = a.nextInt();
System.out.print("Enter source end index: ");
int end = a.nextInt();
System.out.print("Enter destination index: ");
int dest = a.nextInt();
char[] sample = string.toCharArray();
System.out.println("The value extracted from " + string + " with indexes "+ begin + " to "+ end + " is: " +
string.getChars(begin, end, sample, dest));
}
}
ERROR: void is not allowed. ---how to get rid of that?
String#getChars do not return any value, it writes the result into dest parameter:
final int length = end - begin;
char[] sample = new char[length];
string.getChars(begin, end, sample, dest);
System.out.println("The value extracted from " + string + " with indexes "+ begin + " to "+ end + " is: " + sample);

java: How Not to save values from the code when looping back again?

How do I not store values from the program when it loops back again. For example, if I plan to enter two families, first I will ask for the details of the first family and display their names, and then I want to use the same variables to collect the next family and display their names without having stored information from the previous family.
public static void main(String[] args) {
// TODO code application logic here
String ans;
String res;
double cont;
int cot;
String name;
String order = "";
do {
ans = JOptionPane.showInputDialog(null,"What is the name of the "
+ "family?" );
res = JOptionPane.showInputDialog(null, "How many member in the " + ans +
" family?");
cot = Integer.parseInt(res); // Converts res String to a number
for (int count = 1; count < cot; count ++) {
name = JOptionPane.showInputDialog(null, " Enter first name: " + count);
order += name + " " + ans + "\n";
}
JOptionPane.showMessageDialog(null, "Members of the " + ans
+ " Family" + "\n" + order);
cont = JOptionPane.showConfirmDialog(null, "Do you want to add another "
+ "family", "Membership", JOptionPane.YES_NO_OPTION);
}while (cont == JOptionPane.YES_OPTION);
if (cont == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null," Come Back Again");
}
}
}
Your order variable is a String that you are adding the names to. Just reset it at the beginning of the loop:
...
do {
order = "";
...

how to store strings in a while loop in java

I am trying to store the data that's created in the while loop in the list variable so that I can use it later with the JOptionPane.INFORMATION_MESSAGE.
I tried using an array to store the data but it would not work.
Please let me know what I am missing.
package loops;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Statistics
{
public static void main(String[] args)
{
int observations = 1,
num = 0,
sum = 0,
max = Integer.MIN_VALUE,
min = Integer.MAX_VALUE;
double mean = 0.0;
String userEntry = "",
result,
list = " ",
seperator = "\n***********\nYou entered the following observations: ";
DecimalFormat twoDigits = new DecimalFormat ("0.00");
userEntry = JOptionPane.showInputDialog ("Enter observation # " + observations +
" (or \"end\" to quit) ");
//num = Integer.parseInt(userEntry);
String[] list2 = new String[num];
while(!userEntry.equalsIgnoreCase("end"))
{
num = Integer.parseInt(userEntry);
observations ++;
userEntry = JOptionPane.showInputDialog ("Enter observation #" + observations +
" (or \"end\" to quit) ");
//num = Integer.parseInt(userEntry);
//num = Integer.parseInt(userEntry);
//list = "\n" + num;
//list = list.toString();
sum += num;
if(num > max)
{
max = num;
}
if(num < min)
{
min = num;
}
//Integer.toString(num);
//ArrayList<String> list = new ArrayList<String>();
//list.add(num);
//list = "\n" + Integer.toString(num);
//String[] list2 = new String[num];
//for(String list1 : list2)
//{
list = "\n" + num;
//}
}
observations --;
mean = sum / (double)observations;
//twoDigits.format(mean);
if(observations == 0)
{
result = "no observations selected";
}
else
{
result = "You entered " + observations +
(observations == 1 ? " observation" : " observations");
result = result + "\nThe minimum is " + min;
result = result + "\nThe maximum is " + max;
result = result + "\nThe sum is " + sum;
result = result + "\nThe mean is " + twoDigits.format(mean);
result = result + seperator;
result = result + list;
}
JOptionPane.showMessageDialog(null, result,
"Results", JOptionPane.INFORMATION_MESSAGE);
//observations --;
System.exit(0);
}
}
Try using ArrayList instead of []. Example based on your code is shown below.
package loops;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Statistics {
public static void main(String[] args) {
// method local variables
int observations = 0;
int num = 0;
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
double mean = 0.0;
String userEntry = "";
String result;
String list = " ";
String seperator = "\n***********\nYou entered the following observations: ";
DecimalFormat twoDigits = new DecimalFormat("0.00");
ArrayList<Integer> intList = new ArrayList<Integer>();
// get user entry from JOptionPane
userEntry = JOptionPane.showInputDialog("Enter observation # " + observations + " (or \"end\" to quit) ");
// iterate until user enters end
while (userEntry.equalsIgnoreCase("end") == false) {
observations++;
num = Integer.parseInt(userEntry);
userEntry = JOptionPane.showInputDialog("Enter observation #" + observations + " (or \"end\" to quit) ");
sum = sum + num;
// change number to max if > max
if (num > max) {
max = num;
}
// change number to min if < min
if (num < min) {
min = num;
}
// add the number to the string and to the list
list = list + "\n" + num;
intList.add(num);
}
echoList(intList);
mean = sum / (double) observations;
if (observations == 0) {
result = "no observations selected";
}
else {
result = "You entered " + observations + (observations == 1 ? " observation" : " observations");
result = result + "\nThe minimum is " + min;
result = result + "\nThe maximum is " + max;
result = result + "\nThe sum is " + sum;
result = result + "\nThe mean is " + twoDigits.format(mean);
result = result + seperator;
result = result + list;
}
// show results and exit
JOptionPane.showMessageDialog(null, result, "Results", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
private static void echoList(ArrayList<Integer> intList) {
System.out.println("------------------------------");
System.out.println("Got " + intList.size() + " integers.");
for(Integer i : intList) {
System.out.println("\t" + i);
}
System.out.println("------------------------------");
}
}
JOptionPane.showInputDialog() will return the string the user has entered if the user hits ok, and returns null otherwise.
Therefore, if the user hits cancel, your while condition (userEntry.equalsIgnoreCase("end") == false) will throw a NullPointerException.
Therefore, it's safer to change the while condition to (userEntry != null).
Now, if you want to store all the user entries, use a list of integers, say List<Integer> userEntries
List<Integer> userEntries = new ArrayList<>();
while (userEntry.equalsIgnoreCase("end") == false)
{
observations++;
num = Integer.parseInt(userEntry);
userEntries.add(num);
...
}

Categories