I've tried searching a number of threads in terms of multiplying 2 strings. However, it seems that most of the links I found weren't applicable or I couldn't interpret them well enough.
Would it be possible if could tell me what is wrong with my current code?
public static void main(String[] args) {
String sample = value1();
String sample2 = value2();
//========== Test if users placed any characters within the boxes =========\\
try {
Integer.parseInt(sample);
} catch (NumberFormatException e) {
System.out.println("System detects that you are using characters");
return;
}
try {
Integer.parseInt(sample2);
} catch (NumberFormatException e) {
System.out.println("System detects that you are using characters");
return;
}
Integer.parseInt(sample);
Integer.parseInt(sample2);
System.out.println("The total multiplication that you have inserted is "+sample * sample2+ ".");
}
public static String value1() { //obtain first user input.
String sample = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
if (sample.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
sample = value1();
}
return sample;
}
public static String value2() { //obtain second user input.
String sample2 = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
if (sample2.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
sample2 = value2();
}
return sample2;
}
}
My final output should multiply the following numbers
System.out.println("The total multiplication that you have inserted is "+sample * sample2+ ".");
You can't multiply strings together. You can multiply numbers, and it sounds like that's what you want to do. Indeed, you're already parsing the strings as integers - and then ignoring the result. You just need to change this:
Integer.parseInt(sample);
Integer.parseInt(sample2);
System.out.println("The total multiplication that you have inserted is "+sample * sample2+ ".");
to:
int value1 = Integer.parseInt(sample);
int value2 = Integer.parseInt(sample2);
System.out.println("The total multiplication that you have inserted is "
+ (value1 * value2) + ".");
you are trying to multiply two string not two number
you should use like this :
System.out.println("The total multiplication that you have inserted is "+ Integer.parseInt(sample) * Integer.parseInt(sample2)+ ".");
You have to assign the return value of Integer.parseInt() to variables. The variables passed as param stay unchanged.
int a = Integer.parseInt(sample);
int b = Integer.parseInt(sample2);
System.out.println("The total multiplication that you have inserted is " + a * b + ".");
1st suggestion: Don't (ever!) declare 2 methods that do exactly the same thing!!
public static String value() { //obtain *first and second* user input.
String sample = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
if (sample.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
sample = value();
}
return sample;
}
2nd suggestion: Don't check the validity of your input in both value() method and main():
public static int value() { //obtain second user input.
String sample = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
if (sample.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
return value();
}
try {
int v = Integer.parseInt(sample);
return v;
} catch (NumberFormatException e) {
System.out.println("System detects that you are using characters");
return value();
}
}
for this 2nd case, main becomes:
public static void main(String[] args) {
int x1 = value();
int x2 = value(); // call again the *same* method
System.out.println("The total multiplication that you have inserted is "+x1 * x2+ ".");
}
Related
I'm trying to initialize an array of objects in a for loop, each object with a different value that comes from the console, I have a for loop to do this and everything is ok until I see the objects, all the objects have the values of the second input, I have tried a lot of different things but I can't see what's wrong, I'm 17 years old and a total beginner, I'm not a native English speaker so sorry if is hard to understand, sorry if the solution is obvious.
Please help me, Thank you.
This is my main class code.
import java.util.Scanner;
public class StockDriver {
static Stocks stockObj[];
static int NumStocks;
static String Symbol;
static String ComName;
static int Shares;
public static void main(String[] args) throws Exception {
Scanner cin = new Scanner(System.in);
System.out.println("How many stocks do you want to create?");
//Stocks input
try { //Try-Catch to handle Imput Mismatch Exeption
NumStocks = cin.nextInt();
cin.nextLine();
System.out.println("You entered: " + NumStocks);
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Stock");
}
System.out.println("You will now enter in the company symbol, name and their share quantity. The price will be randomly generated.");
//Initialitation of stock objects
stockObj = new Stocks[NumStocks];
//For loop to ask for the imput of all stock, forced to a maximum of 10 stocks
for(int i = 0; i < NumStocks && i < 10; i++){
stockObj[i] = new Stocks(Symbol,ComName,Shares);
//Symbol input
System.out.println("Please enter the three character symbol: ");
try { //Try-Catch to handle Imput Mismatch Exeption
Symbol = cin.nextLine();
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Symbol");
}
//Company Name input
System.out.println("Please enter the conpany name:");
try { //Try-Catch to handle Imput Mismatch Exeption
ComName = cin.nextLine();
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Name");
}
//Number of Shares input
System.out.println("Please enter the total shares:");
try { //Try-Catch to handle Input Mismatch Exeption
Shares = cin.nextInt();
cin.nextLine();
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Shares");
}
// stockObj[i] = new Stocks(Symbol,ComName,Shares);
}
for( int i = 0; i < NumStocks;i++){
System.out.println("this is "+i);
System.out.println(stockObj[i].getSymbol());
}
}
}
This a class for my program.
public class Stocks {
private static String Symbol;
private static String ComName;
private static int Shares;
private static double price;
Stocks(String symbol, String comName, int shares) {
Symbol = symbol;
ComName = comName;
Shares = shares;
}
//Method to get symbol
public String getSymbol(){
return Symbol;
}
//Method to get Company Name
public String getComName(){
return ComName;
}
//Method to get the random price between $1.00 and $200.99
public double randomPrice(){
double price = (Math.random() * (200.99 - 1.00)) + 1.00;
Stocks.price = price;
return price;
}
//Method to get Shares
public int getShares(){
return Shares;
}
//Method to get the total value of the stock
public double totalValue(){
return price * Shares;
}
}
In the next for loop I ask for three inputs the number of times that was entered before, what I tried to do is to store the inputs the first time of the loop and create a object with this inputs before the loop ask for the inputs again and the inputs change. I have verified and the program does store different inputs so this is no the problem. The problem is that when a take a look at each object have the same values although there were different inputs, the input that is stored in all objects is one before the last one or the last one. I would like understand what's going on and know a way to store the different inputs in the objects, thank you very much and sorry for the long reading.
for(int i = 0; i < NumStocks && i < 10; i++){
//stockObj[i] = new Stocks(Symbol,ComName,Shares);
//Symbol input
System.out.println("Please enter the three character symbol: ");
try { //Try-Catch to handle Imput Mismatch Exeption
Symbol = cin.nextLine();
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Symbol");
}
//Company Name input
System.out.println("Please enter the conpany name:");
try { //Try-Catch to handle Imput Mismatch Exeption
ComName = cin.nextLine();
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Name");
}
//Number of Shares input
System.out.println("Please enter the total shares:");
try { //Try-Catch to handle Input Mismatch Exeption
Shares = cin.nextInt();
cin.nextLine();
} catch (Exception e) {
System.out.println("That is an improper value. The program has been stoped.");
cin.close();
System.err.println(e + "in Shares");
}
stockObj[i] = new Stocks(Symbol,ComName,Shares);
}
All the fields in Stocks class are static, that is, they exist per class -- not per instance, and therefore the same values are shared across all instances when they are created.
To fix the issue, just remove static modifier, and change the field names to be camelCase to comply with Java naming conventions:
public class Stocks {
private String symbol;
private String comName;
private int shares;
private double price;
// ...
// update getters/setters/constructor according to the updated field names
}
Good morning.
I suppose it's a very simple question for you guys...
In below code, exception NumberFormatException, can be thrown in to places, when we provide value for "a" and "b" variables. Catch block handles exceptions by starting the method again, no matter if the exception was trigged by wrong value of "a" or "b".
I would like to change the code in a way that if the exception occurs while providing value for varaible "b", the method start not from the very beginning, but from the place where I'm suppose to provide value for "b" (in other words I don't want the user to go again from the start and provide value for "a" variable
Suppose I could insert two more methods handling the code where I provide the values for "a" and "b" ... but is there any other way to get the same functionality without implementing new methods ?
import java.io.*;
public class Rozdzial1{
public static void Zadanie11()
throws IOException
{
try {
Double a, b, area;
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader read = new BufferedReader(input);
System.out.println("The program calcultes area of rectangle");
System.out.println("Provide length of first edge: ");
a = Double.parseDouble(read.readLine());
System.out.println("Length of the first edge is: " + a);
System.out.println("Provide length of second edge: ");
b = Double.parseDouble(read.readLine());
System.out.println("Length of the second edge is: " + b);
area = a*b;
System.out.println("Area of provided rectangle is: " + area);
}
catch (NumberFormatException exception) {
System.out.println("Provided vale should be a number, please try again\n");
Rozdzial1.Zadanie11();
}
}
public static void main(String[] args)
throws IOException
{
Rozdzial1.Zadanie11();
}
}
Reading values until valid value is entered should be extracted into a separate method, which should be called for a and b variables separately.
public static void main(String[] args) {
Task1();
}
public static void Task1() {
Scanner scan = new Scanner(System.in);
System.out.println("The program calculates area of rectangle");
double a = readValue(scan, "first edge");
double b = readValue(scan, "second edge");
System.out.println("Area of provided rectangle is: " + (a * b));
}
private static double readValue(Scanner scan, String name) {
try {
System.out.println("Provide length of " + name + ": ");
return Double.parseDouble(scan.nextLine()); // exit from recursion with valid value
} catch (NumberFormatException numex) {
System.out.println("Provided value should be a number, please try again");
return readValue(scan, name); // recursive call for invalid value
}
}
Another option (without creating a separate method) could be to use nested loops to read inputs until valid value is provided:
public static void Task2() {
Scanner scan = new Scanner(System.in);
System.out.println("The program calculates area of rectangle");
String[] names = {"first edge", "second edge"};
double[] arr = new double[2];
for (int i = 0; i < arr.length; i++) {
try {
System.out.println("Provide length of " + names[i] + ": ");
arr[i] = Double.parseDouble(scan.nextLine());
} catch (NumberFormatException numex) {
System.out.println("Provided value should be a number, please try again");
i--; // repeat the input
}
}
System.out.println("Area of provided rectangle is: " + (arr[0] * arr[1]));
}
I've built a little random number generator using JOptionPane. The exceptions that I've written prevent the user from quitting the program when clicking the X button. I've done lots of research and tried several things but nothing seems to work.
Here's my code:
import javax.swing.JOptionPane;
import java.util.Random;
public class Generate {
private int number;
private int min;
private int max;
private int repeat;
Random no = new Random();
int x = 1;
void generateNumber() {
do {
try {
String from = (String) JOptionPane.showInputDialog(null, "Welcome to Random Number Generator!\n\nPlease insert your number range.\n\nFrom:", "Random Number Generator", JOptionPane.QUESTION_MESSAGE, null, null, "Enter Number");
min = Integer.parseInt(from);
String to = (String) JOptionPane.showInputDialog(null, "To:", "Random Number Generator", JOptionPane.QUESTION_MESSAGE, null, null, "Enter Number");
max = Integer.parseInt(to);
System.out.println();
String count = (String) JOptionPane.showInputDialog(null, "How many numbers would you like?", "Random Number Generator", JOptionPane.QUESTION_MESSAGE, null, null, "Enter Number");
repeat = Integer.parseInt(count);
System.out.println();
for (int counter = 1; counter <= repeat; counter++) {
number = no.nextInt(max - min + 1) + min;
JOptionPane.showMessageDialog(null, "Random number #" + counter + ": " + number, "Random Number Generator", JOptionPane.PLAIN_MESSAGE);
}
x = 2;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "INPUT ERROR: please insert a number", "Random Number Generator", JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "INPUT ERROR: the second number needs to be higher than the first", "Random Number Generator", JOptionPane.ERROR_MESSAGE);
}
} while(x == 1);
}
}
Main:
class RandomNumber {
public static void main(String[] args) {
Generate obj = new Generate();
obj.generateNumber();
}
}
This is what happens when I try to close the program
You don't test the from value after showInputDialog() invocations.
For example here :
String from = (String) JOptionPane.showInputDialog(null,...
After this call, You chain directly with
min = Integer.parseInt(from);
whatever the value of from.
If from is null you finish in this catch as null is not a number :
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "INPUT ERROR: please insert a number", "Random Number Generator",
JOptionPane.ERROR_MESSAGE);
}
And x has still 1 as value. So the loop condition is still true.
To solve your problem, you just to test the value returned by showMessageDialog() and if the value is null, let the user exits from the method.
Add this code at each time you retrieve a user input and that you want to enable the user to exit :
if (from == null) {
return;
}
I have an assignment where two users are to enter their names, then get the number of games they played, then get the scores for each game that they played, put the scores in an array (or two arrays???), then compare the two arrays and scores to see who won each game or if they're tied, then display results. I don't have to sort it or search through it I don't believe.
Ss my teacher says getting the scores has to be a void method, but I'm not sure how I get the values from this void method into arrays for each player so I can compare the score values.
public class Lab9 {
public static void inputScores(int[] array, String name) {
String inputScores = "";
for (int i = 1; i < array.length; i++) {
inputScores = JOptionPane.showInputDialog(name + " enter your score for game " + i);
array[i] = Integer.parseInt(inputScores);
}
}
public static void main(String[] args) {
int numberOfGames = getPositiveIntOrQuit("How many games were played?", "Lab 9 (by Jarvis),");
String name = getStringOrQuit("Player 1-What is your name?", "Lab 9 (by Jarvis");
String name1 = getStringOrQuit(" Player 2 - What is your name?","Lab 9(by Jarvis");
int score = getNonNegativeIntOrQuit(name + " enter your score for game" , "Lab 9 (by Jarvis)");
}
public static String getStringOrQuit(String prompt, String title) {
String userInputString;
userInputString = JOptionPane.showInputDialog(null, prompt, title, JOptionPane.QUESTION_MESSAGE);
// Did user hit Cancel or OK with nothing typed?
if (userInputString == null || userInputString.trim().equals("")) {
JOptionPane.showMessageDialog(null,"No input, so program will terminate now.");
System.exit(0);
}
return userInputString;
} // getStringOrQuit
public static int getPositiveIntOrQuit(String prompt, String title) {
String userInputString;
int userInputInt = 0;
do {
userInputString = JOptionPane.showInputDialog(null, prompt, title, JOptionPane.QUESTION_MESSAGE);
// Did user hit Cancel or OK with nothing typed?
if (userInputString == null || userInputString.trim().equals("")) {
JOptionPane.showMessageDialog(null,"No input, so program will terminate now.");
System.exit(0);
}
else
try {
userInputInt = Integer.parseInt(userInputString); // This line might throw an exception.
// Ok, if conversion in above line worked, check if input is a positive integer.
if (userInputInt < 1)
JOptionPane.showMessageDialog(null,"Bad input value. It must be a positive integer.",
"Input error", JOptionPane.ERROR_MESSAGE);
}
catch (NumberFormatException exc) {
JOptionPane.showMessageDialog(null,"Bad input value. It must be a positive integer.",
"Input error", JOptionPane.ERROR_MESSAGE);
}
} while (userInputInt < 1);
return userInputInt;
} // getPositiveIntOrQuit
public static int getNonNegativeIntOrQuit(String prompt, String title) {
String userInputString;
int userInputInt = -1;
do {
userInputString = JOptionPane.showInputDialog(null, prompt, title, JOptionPane.QUESTION_MESSAGE);
// Did user hit Cancel or OK with nothing typed?
if (userInputString == null || userInputString.trim().equals("")) {
JOptionPane.showMessageDialog(null,"No input, so program will terminate now.");
System.exit(0);
}
try {
userInputInt = Integer.parseInt(userInputString); // This line might throw an exception.
// Ok, if conversion in above line worked, check if input is a positive integer.
if (userInputInt < 0)
JOptionPane.showMessageDialog(null,"Bad input value. It must be a non-negative integer.",
"Input error", JOptionPane.ERROR_MESSAGE);
}
catch (NumberFormatException exc) {
JOptionPane.showMessageDialog(null,"Bad input value. It must be a non-negative integer.",
"Input error", JOptionPane.ERROR_MESSAGE);
}
} while (userInputInt < 0);
return userInputInt;
}
}
Ive written up some code, take it as my solution to your problem.
I would create a hashmap ( or two, one for each player ) and map the game number to the score. You can then use this hashmap to compare scores quite easily
Example ( This is rough code i did it quickly ):
public class random {
private static Scanner keyboard = new Scanner(System.in);
private static HashMap<Integer, String> gameMap = new HashMap<Integer, String>();
public static void mapScores(){
System.out.println("How many games have been played?");
int numOfGames = keyboard.nextInt();
String score = "";
for(int i = 0; i < numOfGames; i++){
System.out.println("Please enter the score for game: " + i);
score = keyboard.nextLine();
gameMap.put(i, score);
}
}
}
EDIT:
Okay, then i would suggest declaring your integer arrays statically. Makes for easy access. You're saying an array that holds the players scores and the players name, which is why id suggest a hashmap because and array cannot store the name. I'll demonstrate,:
public class random {
private static Scanner keyboard = new Scanner(System.in);
private static HashMap<String, int[]> gameMap = new HashMap<String, int[]>();
private static int[] hello = new int[10];
public static void mapScores(int[] array, String name){
String inputScores = "";
for (int i = 1; i < array.length; i++) {
inputScores = JOptionPane.showInputDialog(name + " enter your score for game " + i);
array[i] = Integer.parseInt(inputScores);
}
}
public static void main(String[] args) {
random.gameMap.put("name", new int[10]);
random.mapScores(gameMap.get("name"), "name");
for(int i = 0; i < gameMap.get("name").length; i++){
System.out.println(gameMap.get("name")[i]);
}
}
}
Obviously i haven't taken the time to correctly create the objects but hopefully you can see the idea despite the bad code. Hope this helps!
I'm trying to write a simple program that will ask for the user to enter a number in-between 1 and 10, then display the number. Now I have gotten part to work where if the number is outside of the range it asks again, but I can't seem to get it to ask again if anything aside from a number is inputted, such as % or hello.
The source code: (Cut out the top)
public static void main(String[] args){
int number; //For holding the number
String stringInput; //For holding the string values until converted
//------------------//
//Introducing the user
JOptionPane.showMessageDialog(null, "This is a program that will ask \n"
+ "you to enter a number in-between \n"
+ "1-10, if the number is not within \n"
+ "the parameters, the program will repeat.");
//---------------------//
//Get input from the user
stringInput = JOptionPane.showInputDialog("Enter number.");
number = Integer.parseInt(stringInput);
//-----------------//
//Checking the number
while (number > 10 || number < 0){
stringInput = JOptionPane.showInputDialog("That number is not within the \n"
+ "allowed range! Enter another number.");
number = Integer.parseInt(stringInput);
}
//-------------------//
//Displaying the number
JOptionPane.showMessageDialog(null, "The number you chose is "
+ number
+ ".");
//-------------//
//Closing it down
System.exit(0);
}
The main problem is the:
number = Integer.parseInt(stringInput);
I can't seem to convert the data values properly. I already thought of something like using an if statement to determine if the number is an integer, but I couldn't figure out how to check. I wish I could do:
if (number == Integer)
As you can see I am still extremely new to Java, any help is appreciated, thanks for taking the time to read.
You need to surround the call to Integer.parseInt() with a try/catch block to detect invalid input, like:
try {
number = Integer.parseInt(stringInput);
} catch (NumberFormatException e) {
// Not a number, display error message...
}
Here is a solution:
String errorMessage = "";
do {
// Show input dialog with current error message, if any
String stringInput = JOptionPane.showInputDialog(errorMessage + "Enter number.");
try {
int number = Integer.parseInt(stringInput);
if (number > 10 || number < 0) {
errorMessage = "That number is not within the \n" + "allowed range!\n";
} else {
JOptionPane
.showMessageDialog(null, "The number you chose is " + number + ".");
errorMessage = ""; // no more error
}
} catch (NumberFormatException e) {
// The typed text was not an integer
errorMessage = "The text you typed is not a number.\n";
}
} while (!errorMessage.isEmpty());
I'm trying to write a simple program that will ask for the user to
enter a number in-between 1 and 10
please to read Oracle tutorial How to use Dialogs - JOptionPane Features, then code should be very short and simple, without parsing an Integer from String
.
import java.awt.EventQueue;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
public class MyOptionPane {
public MyOptionPane() {
Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
Object[] possibilities = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer i = (Integer) JOptionPane.showOptionDialog(null,
null, "ShowInputDialog",
JOptionPane.PLAIN_MESSAGE, 1, errorIcon, possibilities, 0);
// or
Integer ii = (Integer) JOptionPane.showInputDialog(null,
"Select number:\n\from JComboBox", "ShowInputDialog",
JOptionPane.PLAIN_MESSAGE, errorIcon, possibilities, "Numbers");
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyOptionPane mOP = new MyOptionPane();
}
});
}
}