How to get an InputDialog box to accept two values successively - java

package javaapplication4;
import javax.swing.*;
public class JavaApplication4 {
public static void main(String[] args) {
// TODO code application logic here
int num1;
num1 = Integer.parseInt(JOptionPane.showInputDialog("Please enter a value"));
if(num1<50 && num1>100)
System.out.println("value is correct");
else
System.out.println("value is incorrect");
}
}

Solution 1
You can repeat the operation 2 times like this :
public static void main(String[] args) {
int i = 0, n = 2;//repeat n time
while (i < n) {
// TODO code application logic here
int num1;
num1 = Integer.parseInt(JOptionPane.showInputDialog("Please enter a value"));
if (num1 < 50 && num1 > 100) {
System.out.println("value is correct");
} else {
System.out.println("value is incorrect");
}
i++;
}
}
Solution 2
You can use an array to store your values and check them later for example :
public static void main(String[] args) {
int i = 0, n = 2;
// TODO code application logic here
int num1[] = new int[n];
while (i < n) {
num1[i] = Integer.parseInt(JOptionPane.showInputDialog("Please value " + (i+1)));
i++;
}
if (num1[0] < 50 && num1[1] > 100) {
System.out.println("value is correct");
} else {
System.out.println("value is incorrect");
}
}
This will ask you for the n value, in your case will ask you to enter 2 values so it will stored in your array, then you can check this values of array.
EDIT
You have to use a separator and you can split with this separator for example your input should look like this :
6999,888
--1---2
so when you split with , String[] spl = res.split(","); you will get an array of String like [6999,888], then you can use this two value to make your condition :
int v1 = Integer.parseInt(spl[0]);//convert String to int
int v2 = Integer.parseInt(spl[1]);//convert String to int
So your program should look like this :
public static void main(String[] args) {
String res = JOptionPane.showInputDialog("Please enter a value separated with , :");
String[] spl = res.split(",");
System.out.println(Arrays.toString(spl));
//you have to make some check to avoid any problem
int v1 = Integer.parseInt(spl[0]);
int v2 = Integer.parseInt(spl[1]);
if (v1 < 50 && v2 > 100) {
System.out.println("value is correct");
} else {
System.out.println("value is incorrect");
}
}
Edit2
You can show your result in JOptionPane like this :
if (v1 < 50 && v2 > 100) {
JOptionPane.showMessageDialog(null, "value is correct");
} else {
JOptionPane.showMessageDialog(null, "value is incorrect");
}
EDIT3
To get the max you have to check it like this :
if (v1 > v2) {
JOptionPane.showMessageDialog(null, "larger value is : " + v1);
} else {
JOptionPane.showMessageDialog(null, "larger value is : " + v2);
}
Or in one line you can use :
JOptionPane.showMessageDialog(null, "larger value is : " + (v1 > v2 ? v1 : v2));

Related

Printing Only Filled Array Places | Java in While Loop

I recenlty started to learn JAVA programming. I am using BlueJ compiler.
Can anyone tell me or give me a hint, how to make "System.out.println" not print out empty array values (I mean Null) values if array is not filled compleatly.
static String [] Country = new String [15];
static String [] City = new String [15];
static String [] Region = new String [15];
static Scanner sc = new Scanner(System.in);
static int x = 0, y = 0, z = 0;
static int a = 0, b=0,c=0, t=0;
public static void main (String [] args)
{
String entry = "-1";
while( !entry.equals ("4")){
menu();
entry = sc.nextLine();
if(!entry.equals("1") && (!entry.equals("2")) && (!entry.equals ("3")) && (!entry.equals ("4") && !entry.equals("-1")))
{ JOptionPane.showMessageDialog(null, "Please Enter Numbers as shown in 'MENU LIST'");
}
if (entry.equals ("1")) {
System.out.println("\f");
AddCity();
}
if (entry.equals("2")) {
System.out.println("\f");
Search();
}
if (entry.equals("3")) {
PrintAll();
}
}
JOptionPane.showMessageDialog(null, "Have a nice day");
}
public static void menu()
{
System.out.println(" ---------------- Menu-----------------");
System.out.println(" Please Use Numbers ONLY from 1 - 4 ");
System.out.println(" 1. Add new City");
System.out.println(" 2. Search for a City.");
System.out.println(" 3. Print All Cities.");
System.out.println(" 4. QUIT.");
}
public static void AddCity()
{
if(t >=13) {
JOptionPane.showMessageDialog(null, "Database capacity is almost full.");
PrintAll();
}
System.out.println("Please enter The name of Country.");
Country [x] = sc.nextLine();
x++;
System.out.println("Please enter the name of City.");
City [y] = sc.nextLine();
y++;
System.out.println("Please enter the Region where the city is located.");
Region [z] = sc.nextLine();
z++;
t++;
}
public static void Search()
{
}
public static void PrintAll()
{
while (a <14)
{
if (!Country.equals("Null") ) {
System.out.print("Country: ");
System.out.print(Country[a]+ " | ");
a++;
while(b <(a)) {
System.out.print("City: ");
System.out.print(City[b]+ " | ");
while(c<a) {
System.out.print("Region: ");
System.out.println(Region[c] + " | ");
c++;
}
b++;
}
}
System.out.println("");
}
}
}
Can anyone tell me or give me a hint, how to make "System.out.println"
not print out empty array values
You test, whether the value at the index position is null and only print, if not null. You need to consider, that the rest of your code, especially your counters a, b and c are outside of this condition.
while (a <14)
{
if (!Country.equals("Null") && country[a] != null) {
System.out.print("Country: ");
System.out.print(Country[a]+ " | ");
a++;
while(b <(a)) {
if(City[b]!=null) {
System.out.print("City: ");
System.out.print(City[b]+ " | ");
}
while(c<a) {
if(Region[c]!=null) {
System.out.print("Region: ");
System.out.println(Region[c] + " | ");
}
c++;
}
b++;
}
}
System.out.println("");
}
I am not sure where in your code you want to use this but is like this, in side you loop just check if you loop variable is not equal to null.
Ex:
if(variable != null) {
//do something
}

Java multiplication using Recursion

I am writing a simple code in Java that is using recursion. I want to show the product of two numbers that a user will enter. I managed to do that using recursion, but stuck at the point where I want to show that the product could be written as (example) 10*5 = 5+5+5+5+5+5+5+5+5+5 (10 times), or 12*3 = 3+3+3+3+3+3+3+3+3+3+3+3 (12 times). Here is my code so far. In the code i put a comment where it should be written (example). Thanks.
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a, b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.println("The product of " + a + " and "
+ b + " is: " + multiRec(a, b));
System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
return x + (multiRec(x, y - 1));
}
}
}
}
A StringBuilder should be defiend as
StringBuilder buf = new StringBuilder (a);
Pass this StringBuilder paramater into multiRec
and then change multiRec to be
public static int multiRec(int x, int y, StringBuilder buf) {
if (x == 0 || y == 0) {
return 0;
} else {
if (x == 1) {
return y;
} else {
buf.append (" + ").append (x);
return x + (multiRec(x, y - 1, buf));
}
}
}
}
Then when completed simply printout its value
import java.util.Scanner;
public class RecursiveMultiplication {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
int a , b;
System.out.print("Enter first number: ");
a = key.nextInt();
System.out.print("Enter second number: ");
b = key.nextInt();
System.out.printf("%d %s %d %s",a , "*" , b ,"= ");
System.out.println("\nThe product of " + a + " and "
+ b + " is: " + multiRec(b, a));
// System.out.println("It could also be written as: "); //Here should product be broken into smaller numbers
}
public static int multiRec(int x, int y) {
if (x == 0 || y == 0) {
return 0;
} else {
System.out.print(x+" ");
if (y == 1) {
return x;
} else {
System.out.print(" + ");
return x + (multiRec(x, y - 1));
}
}
}
}

NumberFormatException: For input string: "[memorylocation" java

I'm doing an assignment where the goal is to, among other things, to add two large integers. Here is my code, spread out into four files.
Main that we cannot change:
import java.util.*;
import MyUtils.MyUtil;
public class CSCD210HW7
{
public static void main(String [] args)throws Exception
{
int choice;
String num;
LargeInt one, two, three = null;
Scanner kb = new Scanner(System.in);
num = HW7Methods.readNum(kb);
one = new LargeInt(num);
num = HW7Methods.readNum(kb);
two = new LargeInt(num);
do
{
choice = MyUtil.menu(kb);
switch(choice)
{
case 1: System.out.println(one + "\n");
break;
case 2: System.out.println("The value of the LargeInt is: " + two.getValue() + "\n");
break;
case 3: num = HW7Methods.readNum(kb);
one.setValue(num);
break;
case 4: if(one.equals(two))
System.out.println("The LargeInts are equal");
else
System.out.println("The LargeInts are NOT equal");
break;
case 5: three = two.add(one);
System.out.printf("The results of %s added to %s is %s\n", one.getValue(), two.getValue(), three.getValue());
break;
case 6: HW7Methods.displayAscendingOrder(one, two, three);
break;
default: if(two.compareTo(one) < 0)
System.out.printf("LargeInt %s is less than LargeInt %s\n", two.getValue(), one.getValue());
else if(two.compareTo(one) > 0)
System.out.printf("LargeInt %s is greater than LargeInt %s\n", two.getValue(), one.getValue());
else
System.out.printf("LargeInt %s is equal to LargeInt %s\n", two.getValue(), one.getValue());
break;
}// end switch
}while(choice != 8);
}// end main
}// end class
LargeInt Class(Custom Class We Created)
public class LargeInt implements Comparable<LargeInt>
{
private int[]myArray;
private LargeInt()
{
this("0");
}
public LargeInt(final String str)
{
this.myArray = new int[str.length()];
for(int x = 0; x < this.myArray.length; x++)
{
this.myArray[x] = Integer.parseInt(str.charAt(x)+ "");
}
}
public LargeInt add(final LargeInt passedIn)
{
String stringOne = myArray.toString();
String stringTwo = passedIn.myArray.toString();
int r = Integer.parseInt(stringOne);
int e = Integer.parseInt(stringTwo);
int s = r + e;
return new LargeInt(""+s);
}
public void setValue(final String arrayString)
{
this.myArray = new int[arrayString.length()];
for(int x = 0; x < myArray.length; x++)
{
this.myArray[x]=arrayString.charAt(x);
}
}
#Override
public int compareTo(LargeInt passedIn)
{
if(passedIn == null)
{
throw new RuntimeException("NullExceptionError");
}
int ewu = 0;
int avs = 0;
if(this.myArray.length != passedIn.myArray.length)
{
return this.myArray.length - passedIn.myArray.length;
}
for(int i = 0; i < this.myArray.length -1; i++)
{
if(this.myArray[i] != passedIn.myArray[i])
{
return this.myArray[i]-passedIn.myArray[i];
}
}
return ewu-avs;
}
public int hashCode()
{
String p = "";
for(int f = 0; f < this.myArray.length; f++)
{
p += myArray[f];
}
return p.hashCode();
}
public String getValue()
{
String h = "";
for(int t = 0; t < this.myArray.length; t++)
{
h += myArray[t];
}
return h;
}
#Override
public boolean equals(Object jbo)
{
if(jbo == null)
{
return false;
}
if(!(jbo instanceof LargeInt))
{
return false;
}
LargeInt k =(LargeInt)jbo;
if(k.myArray.length != this.myArray.length)
{
return false;
}
for(int d = 0; d < this.myArray.length; d++)
{
if(k.myArray[d] != myArray[d])
{
return false;
}
}
return true;
}
#Override
public String toString()
{
String c = "";
for(int q = 0; q < this.myArray.length; q++)
{
c += myArray[q];
}
return "The LargeInt is: " + c;
}
}
HW7Methods File
import java.util.*;
import java.io.*;
public class HW7Methods
{
public static String readNum(Scanner kb)
{
String num = "";
System.out.print("Enter Your Large Int: ");
num = kb.nextLine();
return num;
}
public static void displayAscendingOrder(final LargeInt first, final LargeInt second, final LargeInt third)
{
String highestInt;
if(first.compareTo(second) >= 0 && first.compareTo(third) >= 0)
{
highestInt = first.getValue();
}
else if(second.compareTo(first) >= 0 && second.compareTo(third) >= 0)
{
highestInt = second.getValue();
}
else
{
highestInt = third.getValue();
}
String middleInt;
if(first.compareTo(second) >= 0 && first.compareTo(third) <= 0)
{
middleInt = first.getValue();
}
else if(second.compareTo(first) >= 0 && second.compareTo(third) <= 0)
{
middleInt = second.getValue();
}
else
{
middleInt = third.getValue();
}
String lowestInt;
if(first.compareTo(second) <= 0 && first.compareTo(third) <= 0)
{
lowestInt = first.getValue();
}
else if(second.compareTo(first) <= 0 && second.compareTo(third) <= 0)
{
lowestInt = second.getValue();
}
else
{
lowestInt = third.getValue();
}
System.out.println("The LargeInts in order are: " + lowestInt + ", " + middleInt + ", " + highestInt);
}
}
MyUtil file
package MyUtils;
import java.io.*;
import java.util.Scanner;
public class MyUtil
{
public static int menu(Scanner kb)
{
int userChoice;
System.out.println("1) Print First Int");
System.out.println("2) Print Second Int");
System.out.println("3) Add Different Int");
System.out.println("4) Check If Equal");
System.out.println("5) Add Large Ints");
System.out.println("6) Display In Ascending Order");
System.out.println("7) Compare Ints");
System.out.println("8) Quit");
kb = new Scanner(System.in);
System.out.print("Please Select Your Choice: ");
userChoice = kb.nextInt();
while(userChoice < 1 || userChoice > 8)
{
System.out.print("Invalid Menu Choice. Please Re-Enter: ");
userChoice = kb.nextInt();
}
return userChoice;
}
}
When I go to run this code, it prompts me for two Large Integers like it's supposed to. However, when I choose option 5 to add them, this is what I get:
Exception in thread "main" java.lang.NumberFormatException: For input string: "[I#55f96302"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at LargeInt.add(LargeInt.java:24)
at CSCD210HW7.main(CSCD210HW7.java:41)
I've never seen that type of error before. Can someone tell me what is going on?
For input string: "[I#55f96302
That is not a "proper" String you are trying to parse here.
This is what an int[] looks like when you call toString() on it.
String stringOne = myArray.toString();
Why do you do that? What is that supposed to do?
int r = Integer.parseInt(stringOne);
int e = Integer.parseInt(stringTwo);
int s = r + e;
From the looks of it, you try to handle "large" ints with your LargeInt class by somehow storing them in an array of ints. That's okay, BigInteger also works like that (more or less), but you cannot just do calculations by trying to convert back to int (after all those numbers are too big for int arithmetic to handle, even if you do the string parsing properly).

Filling Array with user input and using if statements to do arithmetic depending on the value inside array

Here's the question:
Write a Java program that reads in a series of positive integer and writes out the product of all the integers less than 25 and the sum of all the integers greater than or equal to 25. Use 0 as a sentinel value.
I was able to understand how to let the user add the input to an array. But I could not find a way to integrate the code with if statements to make a full working program to do the task. Here's my findings as of now;
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
How is it possible to make the array read the input and find the product of all numbers under 25 and the sum of all the numbers above 25. Between, what is sentinel value and how useful is it to know?
Solution:
After hours of tweaking the answers posted by volunteers below, I was able to find a solution which worked for me. I hereby posted it in case anyone finds it useful;
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Scanner stdin = new Scanner(System.in);
do{
System.out.println("Current list is : " + list);
System.out.println("Enter number : ");
int entered = stdin.nextInt();
if(entered == 0){
int sum = 0,product = 1;
for(Integer number : list){
if(number<25){
sum += number;
}else if(number >= 25){
product *= number;
}
}
System.out.println("sum : " + sum);
System.out.println("product : " + product);
}else{
list.add(entered);
int sum = 0,product = 1;
for(Integer number : list){
if(number<25){
sum += number;
}else if(number >= 25){
product *= number;
}
}
System.out.println("sum : " + sum);
System.out.println("product : " + product);
}
System.out.println("Add more numbers to the list ? (Y/N) : ");
} while(stdin.next().equalsIgnoreCase("y"));
}
}
Thanks to everyone for your posts and comments! It was really helpful! :)
Class Main {
public static void main(String[] args) {
List<Integer> numsGe25 = new ArrayList<>(); // Store numbers greather than or equal to 25
List<Integer> numsLt25 = new ArrayList<>(); // Store numbers less than 25
Scanner in = new Scanner(System.in);
int num = -1;
// Reads a number from the standard input till the 0 value is inserted. 0 is the sentinel
while ((num = in.nextInt()) != 0) {
if (num >= 25) {
numsGe25.add(num)
} else {
numsLt25.add(num);
}
}
System.out.println("sum of numbers >= 25: " + sum(numsGe25));
System.out.println("product of numbers < 25: " + product(numsLt25));
}
private static int sum(List<Integer> numbers) {
int result = 0;
for (Integer num : numbers) {
result += num;
}
return result;
}
private static int product(List<Integer> numbers) {
int result = 1;
for (Integer num : numbers) {
result *= num;
}
return result;
}
}
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
Scanner stdin = new Scanner(System.in);
do{
System.out.println("Current list is : " + list);
System.out.println("Enter number : ");
int entered = stdin.nextInt();
if(entered != 0){
list.add(entered);
}else{
int sum = 0,product = 1;
for(Integer number : list){
if(number<25){
sum += number;
}else if(number >= 25){
product *= number;
}
}
System.out.println("sum : " + sum);
System.out.println("product : " + product);
break;
}
System.out.println("Add more numbers to the list ? (Y/N) : ");
}while(stdin.next().equalsIgnoreCase("y"));
}
}

Java skipping a number in the sequence

This is very interesting, i notice. Before i can explain further its best i show the code and you will understand what i mean.
This is the code:
public class Qn3 {
static BigDecimal[] accbal = new BigDecimal[19];
private static Integer[] accnums = new Integer[19];
public static void main(String[] args) {
addaccount();
}
public static void addAccount() {
int i = 0, accno, input, j, check;
BigDecimal accbala;
DecimalFormat df = new DecimalFormat("0.00");
Scanner sc = new Scanner(System.in);
Scanner in = new Scanner(System.in);
accnums[1] = new Integer(1);
while (accnums.length >= count(accnums)) {
System.out.print("Enter the account number: ");
while (sc.hasNext("[0-9]{7}")) {
accno = sc.nextInt();
System.out.print("Enter account balance: ");
accbala = in.nextBigDecimal();
for (j = 0; j < accnums.length; j++) {
if (accnums[j] == null)
break;
else if (accnums[j].equals(accno)) {
break;
}
}
if (j == accnums.length) {
System.out.print("No more than 20 accounts can be added.");
} else if (accnums[j] != null) {
if ((accnums[j].equals(accno)))
System.out.println("Account already exists");
break;
} else {
accnums[j] = accno;
accbala = accbala.setScale(2, RoundingMode.HALF_UP);
accbal[j] = accbala;
check = j;
System.out.println("Current number of accounts in the system: "
+ (check + 1)
+ "\nNumber of accounts still can be added: "
+ (20 - (check + 1)));
}
}
while (!sc.hasNext("[0-9]{7}")) {
System.out.println("Wrong NRIC");
break;
}
while (accnums.length <= count(accnums)) {
System.out.println("20 accounts have already been created");
break;
}
break;
}
}
private static int count(Integer[] array) {
int count = 0;
// accnums = new Integer[] {1,2};
for (int index = 0; index < array.length; index++) {
if (array[index] != null) {
count++;
}
}
// System.out.println("You have used " + count + " slots");
return count;
}
}
So now that you have seen the code the problem that is hard to notice is this, take note of the line in the addaccount() method where
System.out.println("Current number of accounts in the system: "+(check+1)+"\nNumber of accounts still can be added: "+(20 - (check+1)));
this line the first check+1 will give me 1 then the next one gives me 3! and then the next time i run the method it gives me 4 and then again 5 and so on so forth, what is happening to 2?
You have that println in an else block, and when j == 1 you're hitting the else if case. Try removing this line
accnums[1] = new Integer (1);

Categories