import javax.swing.JOptionPane;
public class Result
{
public static void main (String[] args)
{
int numa;
int numb;
int sum;
String num1 = JOptionPane.showInputDialog(null,"Enter 1st Number: ");
numa=Integer.parseInt(num1);
String num2 = JOptionPane.showInputDialog(null,"Enter 2nd Number: ");
numb=Integer.parseInt(num2);
{
sum=num1+num2;
}
if (sum>=10)
JOptionPane.showMessageDialog(null,"Congratulations"+sum);
else if(sum<10)
JOptionPane.showMessageDialog(null,"the sum of the number less than 10");
else if(sum>100)
System.exit(7);
}
}
This line:
sum=num1+num2;
is trying to add two strings together and make an int.
Instead, you want:
sum = numa + numb;
In other words, take the values you've just parsed from the strings, and add those together.
Additionally, I'd suggest:
Where possible, declare variables at the point where you first use them (typically assignment)
Don't add braces just for the sake of it (e.g. for this sum line) but...
... do add braces to all if blocks for clarity
Indent all code appropriately (there should never be two braces lining up as per the end of your method)
Unless you really need to use Swing, don't bother - this app would be simpler if it took input from the console and just wrote the answer to the console, instead of showing a message box.
sum = numa + numb
You were trying to add the two strings.
Edit: skeeted again!
Related
I'm struggling with an assignment. I need help figuring out how to call the right methods within each other and eventually in main. My whole code might need work at this point, what am I doing wrong? I've been stuck on this for a week.. (Guidelines at the bottom) Thanks!
import java.util.Scanner;
public class AverageWithMethods {
static Scanner in = new Scanner(System.in);
public static void main(String[]args)
{
userPrompt(); //Can't figure out how I'm supposed to set this up.
}
public static String userPrompt()
{
System.out.println("Enter 5 to 10 numbers separated by spaces, then press enter: ");
String num = in.nextLine();
return num; //I think I'm supposed to call the averager method here somehow?
}
public static double averager(String userPrompt)
{
double nums = Double.parseDouble(userPrompt);
double average = 0;
int counter = 0;
char c = ' ';
for (int i = 0; i < userPrompt.length(); i++)
{
if(userPrompt.charAt(i) == c)
{
counter++;
}
average = nums / counter;
}
return average;
}
public static void result(double average, String userPrompt)
{
System.out.println("The average of the numbers" + userPrompt + "is" + average);
}
}
GUIDELINES:
The program prompts the user for five to ten numbers, all on one line, and separated by spaces. Then the user calculates the average of those numbers, and displays the numbers and their average to the user.
The program uses methods to:
Get the numbers entered by the user Calculate the average of the numbers entered by the user Print the results with the whole number, a decimal, and two decimal positions The first method should take no arguments and return a String of numbers separated by spaces.
The second method should take a String as its only argument and return a double (the average).
The third method should take a String and a double as arguments but have no return value.
For example, if the user input is... 20 40 60 80 100
...the program should give as output... The average of the numbers 20 40 60 80 100 is 60.00.
I will not exactly provide complete solution to your questions but guide you in solving the problem:
User input : 1 2 3 4 5
Thus, now you need to read it in a String which you are already doing in your userPrompt() method.
Post that you need to call your averager() method to get the average
of the numbers. In that averager method you can need to split the
String to get the numbers. Check : String.split() method
documentation on how to achieve that. Then, you need to call
Double.parseDouble() for your String array of numbers.
Finally , you need to make a call to result method in you main()
method.
I hope it helps you on how to approach the problems and has sufficient hints to get the correct solution
Create a java program to find and print all palindrome numbers within b and a
such that a<3000, b<3000and b<a.
My approach:-
import java.util.*;
class PalinDrome_Within_A_Range_Of_Two_Numbers{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter an upper limit<3000");
int a=sc.nextInt();
System.out.println("Enter a lower limit <3000,upper limit");
int b=sc.nextInt();
int c=0;
int d,e,f,j;
for(int i=b;i<=a;i++){
j=(int)(Math.log10(i) + 1);
e=0;
f=0;
d=i;
for(int k=1;k<=j;k++){
f=i%10;
f=(int)(f*(Math.pow(10,(j-k))));
i=(i-(i%10))/10;
e=e+f;
}
if(e==d){
c=c+1;
System.out.println("The "+c+"th Palindrome number between "+b+" and "+a+" is "+d);
}
else{
break;
}
}
}
}
In this program, nothing appears in the output after giving the two integers.
The reason is that the first number, if it is not a palindrome, will end the loop at the else break; statement. To fix the problem, you should also not manipulate i within its loop, but rather a copy of it.
You may think about debugging. Shows you the point of failure faster than Stackoverflow.
Are you absolutely sour you enter uper limit before entering the lower limit because I by intuition added lower limit first and it did not work any way here is a simpler soultion if you want
public class PalinDrome_Within_A_Range_Of_Two_Numbers {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
System.out.println("Enter an upper limit<3000");
int a=sc.nextInt();
System.out.println("Enter a lower limit <3000,upper limit");
int b=sc.nextInt();
int c=0;
int d,e,f,j;
for(int i=b;i<=a;i++){
String num = String.valueOf(i);
String reversNum = getReversStr(num);
if(num.equals(reversNum)){
System.out.println(num);
}
}
}
private static String getReversStr(String num) {
char[] chars = num.toCharArray();
char[] revers = new char[chars.length];
for(int i = chars.length;i>0;i--)
revers[chars.length-i]=chars[i-1];
return new String(revers);
}
}
Others already suggested to use a debugger. That makes sense because your code is quite complicated. (By the way, you should keep the scope of your variables as small as possible to make your code more readable. It makes no sense to declare and initialize a variable outside a loop when it is used only inside the loop body.)
A better approach would be to simplify your code. You could split it into multiple functions and give each of these a meaningful name.
Or you could use a completely different approach. Being a palindrome is not so much a property of the number itself but of its string representation. So why not base the whole algorithm on strings:
for (int i = b; i <= a; i++) {
String num = String.valueOf(i);
String reverse = new StringBuilder(num).reverse().toString();
if (num.equals(reverse)) {
System.out.println(i);
}
}
I see two issues with your code (no guarantee that they are the only two, but solving them should get you a step further at the least).
You are using i as control variable in your outer loop, and then you are modifying i inside your inner loop (i=(i-(i%10))/10;). Since you are taking a copy of i into d anyway, there is a simple fix: do the modification on d instead of on i.
The break; statement in you else part will break out of the outer loop if the first number tried (b) is not a palindrome. I think you can just delete the else part.
I tried entering 102 as upper limit and 99 as lower. Your program correctly prints The 1th Palindrome number between 99 and 102 is 99, but then because i has been modified goes into an infinite loop. So you are on the way.
I agree with what others have said about breaking your code up in less comlex methods. This will also allow unit testing each method, which will help to locate bugs. Better variable names will help understanding the code, not least when you ask others to take a look. Finally, don’t declare a variable until you need it, this will also help readability.
I'm not sure if this is possible in Java. I just finished Python and I've taken a webdesign course, so my brain isn't synced with Java yet.
I want it to be something like this
double yourInput = input.nextDouble();
double numCount = (numCount + yourInput);
For example, if I entered 2, 7, and 9 (it would loop) I would want it to do something like this: numCount = 0; then numCount = 0 + 2; then numCount = 2 + 7; then numCount = 9 + 9.
Is this possible in Java? If so, how?
Just loop using input.hasNextDouble():
//give default value
double numCount = 0;
//while user is still giving input
while(input.hasNextDouble()) {
//get input
double yourInput = input.nextDouble();
//add input
numCount += yourInput;
}
//output
System.out.println("total = " + numCount);
Algorithm CONTINOUS_COUNTER()
BEGIN
DECLARE inputReader : java.util.Scanner(System.in);
DECLARE numCount : Double;
SET numCount := 0.0; //Setting the default value to the counter;
LOOP until inputReader.hasNextDouble() returns TRUE
numCount := numCount + inputReader.nextDouble();
END LOOP;
print "Num count = " + numCount;
END;
Dear Katy, this is the logic you should use to develop this program. This is just an algorithm. I don't think it's good to post the real program here, since you are learning Java. Try to convert this algorithm to the Java code. Learn it. :)
Here a working example:
import javax.swing.JOptionPane;
public class DoubleCounter {
private static double total = 0.0;
public static void run(){
while(true){
String input = JOptionPane.showInputDialog("Total Count: "+ total+" add next double: ");
try{
double next = Double.parseDouble(input);
total+=next;
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null, "Wrong input! You must get a valid number!");
continue;
}
}
}
public static void main(String[] args) {
DoubleCounter.run();
}
}
You define a class DoubleCounter with a static member total count.
This class has a run() method that infinitly loop and show ad InputDialog.
The input dialog alway return a string that we 'try' to parsed in a double.
If parsed without problem, we add the result to the total count.
The class has a main method that is the application entry point that 'statically' call run() method of DoubleCounter.
I suggest you to see how 'static' modifier work on class member (total) and on methods (run()).
Hope helped you!
Katy, this is the real program.
import java.util.Scanner;
public class ContinousCounter{
public static void main(final String [] args){
double numCount = 0.0;
Scanner inputReader = new Scanner(System.in);
System.out.println("Enter the values : ");
while(inputReader.hasNextDouble()){ numCount += inputReader.nextDouble();}
System.out.printf("The value for numCount = %f",numCount);
}
}
In order to do what I think you're saying here, you should be using a while loop. It is fairly simple, just think about how you want it to work. It will loop a block of code that adds the scanner's next line to a sum
double mySum = 0;
while(input.nextDouble() != 0){
double myInput = input.nextDouble();
mySum += myInput;
}
In the above loop, we are assuming that when the scanner's next line is 0 there are no more numbers to add, but that can be adjusted so that it stops at other times.
I can see that since you have completed a course in Python programming that you are able to come up with the logic for this and are only looking for convention or proper syntax, so let's explain how the above works:
A while loop will run as long as the statement you let it handle evaluates to true, if you want it to do something while false you can put use an exclamation point before your statement and encase your parameters in parentheses such as the following : while (!(x<=2))
A while loop has the following syntax (in logical form):
while (boolean) {run this code}
You can use the shorthand for adding myInput to your mySum:
+= will add the righthand side to the lefthand side and save that value
If you want to run the code at least once despite the value, you can use a do while loop. The logic behind it is: do {this} while (boolean);
So I am doing a project for a class of mine and it involves the use of delimiters and other scanner methods. However I've been doing a lot of research and the book we have does not clearly explain as to how it works. So after several headaches and trying to understand I figured I'd ask here (EDIT: This is something somewhat similar I found [relating to delimiters and splitting number sequences] to what my teacher was asking me and thought it would be adequate to ask it here. So before I get accused of doing my homework on here I wanted to clarify)
Here's what I have typed so far:
import java.io.*;
import java.util.*;
public class addUp
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1345 - 137 : ");
String s = kb.nextLine( );
Scanner sc = new Scanner(s);
/* sc.useDelimiter("\\s*"); With some help and research I found
out that the \\s* actually causes every character to be split
apart. so 33 is 3 3 */
int sum = sc.nextInt();
while(sc.hasNextInt( ))
{
String operator = sc.next();
int value = sc.nextInt();
if(operator.equals("-"))
{
sum = sum - value;
}
else if(operator.equals("+"))
{
sum = sum + value;
}
}
System.out.println("Sum is: " + sum);
}
}
And my last attempt got me a weird output:
----jGRASP exec: java addUp
Enter something like 8 + 33 + 1345 - 137 : 8 + 33 + 1345 - 137
Sum is: 8
----jGRASP: operation complete.
Now I don't know a ton and I'm sure if I came in with something more complicated than the progress of what we've been through would not be appreciated (since I know I've seen some people answer other questions that is way over my understanding). So keep it dumbed down for me if you can XD. Thanks.
The problem with your code at the moment is that your while loop is checking for while(sc.hasNextInt( )), but it's expecting an operator. Change that to while(sc.hasNext() and you should be ok.
Additionally, when facing problems like this, try running your code in a debugger and stepping through it. You'd see pretty quickly that it didn't enter into the while loop and that would help you diagnose the problem. If you don't have access to a debugger, just put in some System.out.println() statements.
UPDATE
So, I ran your code in a debugger (after changing the while loop as I described), and the first thing I noticed was that the first call to sc.nextInt() returns 3, not 33, because of the reason H L explained. Having removed the call to setDelimeter, the code runs fine. It should now look like:
import java.io.*;
import java.util.*;
public class addUp
{
public static void main(String args[])
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter something like 8 + 33 + 1345 - 137 : ");
String s = kb.nextLine( );
Scanner sc = new Scanner(s);
//sc.useDelimiter("\\s*"); <-- don't do this
int sum = sc.nextInt();
while(sc.hasNext( )) // <-- not hasNextInt
{
String operator = sc.next();
int value = sc.nextInt();
if(operator.equals("-"))
{
sum = sum - value;
}
else if(operator.equals("+"))
{
sum = sum + value;
}
}
System.out.println("Sum is: " + sum);
}
}
And outputs:
Enter something like 8 + 33 + 1345 - 137 : 8 + 33 + 1345 - 137
Sum is: 1249
Again, you should have spotted this if you stepped through your code in a debugger (Eclipse, IntelliJ, NetBeans, jdb, etc).
There are multiple issues with your code:
You call the next() and nextInt() methods multiple times within the while loop which consumes too much of our input.
The sum is initialized to 0 and the very first operand is omitted.
Only the last else block is executed because you compare strings with characters (single quotes instead of double quotes) which always evaluates to false.
Code:
// WRONG: sc.useDelimiter("\\s*");
int sum = sc.nextInt(); // consume the first token, must be an integer
while (sc.hasNext()) { // as long as there are more tokes, do the following
String operator = sc.next(); // read next token, must be a + or - sign
int operand = sc.nextInt(); // read next token, must be an integer again
// depending on the arithmetic operator we update the sum variable
if (operator.equals("-")) {
sum = sum - operand;
} else if (operator.equals("+")) {
sum = sum + operand;
} else {
// if the operator variable contains something else than a + or - sign
// we throw an exception. In general this is the preferred way to avoid
// that the software changes into an undefined state.
throw new RuntimeException("Unknown operator: " + operator);
}
}
System.out.println("Sum is: " + sum);
First Problem (Apparently corrected in an edit to the quesiton)
You call sc.next() in every if statement. Call it once, and then use the value when you need it. If you keep calling it, you'll keep eating your input!
String op = sc.next();
if (op.equals('-') {}
else if (op.equals('+') {}
else {}
Second Problem
You never initialize sum to the first number. You skip the first number completely! Start off like this to make sure you consume the first int before you consume the first operator.
int sum = sc.nextInt();
Third Problem
hasNextInt() only returns true if the next token is an int. It returns false if the next token is an operator like "+" or "-". Change your while to loop on hasNext().
The last fix may cause you to consume a "/n" or some other line seperator nonsense on your last iteration of the loop. as it stands, it looks like this will only cause you to print the sum twice. That seems like something you should be able to solve on your own.
Rather than making me edit my answer four MORE times, try to do this on paper, going in circles for the while loop. Consume an int. Consume an operator. Consume an int. Consume an operator. Consume an int. If you break that order, your logic isn't in the right order. Know the logic before you even try to write code.
Go read the Javadoc for Scanner to see what each method you are calling actually does. Learn about Streams in Java so you understand how they work.
I'm teaching myself how to code with java and I use exercises I find in the Internet to practice what I learn.
Anyway, I'm in a middle of an exercise that asks me to build a method that get two strings containing only the characters "0" and "1" from the user and returns one string of them both (binary)combined
example:
BinaryAdder("0","0") - > "0"
BinaryAdder("1","1") - > "10"
BinaryAdder("10100","111") - > "11011"
what I did is:
import java.util.Scanner;
public class assigment03
{
private static String whichIsBigger(String a, String b)
{
if(a.length()>b.length())
return a;
if(a.length()<b.length())
return b;
if(a.length()==b.length())
return a;
else return null;
}
private static String binaryAdder(String a,String b)
{
int[] binaryResult= new int[maxlength(a,b)+1];
String result="";
if(whichIsBigger(a,b)==a)
{
for(int i=0;i<b.length();i++)
{
binaryResult[i]=a.charAt(i)+b.charAt(i);
}
for(int i=b.length();i<a.length();i++)
{
binaryResult[i]+=a.charAt(i);
}
}
else
{
for(int i=0;i<a.length();i++)
{
binaryResult[i]=b.charAt(i)+a.charAt(i);
}
for(int i=a.length();i<b.length();i++)
{
binaryResult[i]+=b.charAt(i);
}
}
for(int i=0;i<binaryResult.length-1;i++)
{
if(binaryResult[i]>=2)
{
binaryResult[i]=binaryResult[i]%2;
binaryResult[i+1]++;
}
}
for(int i=binaryResult.length-1;i>=0;i--)
{
result+=Integer.toString(binaryResult[i]);
}
return result;
}
private static int maxlength(String a, String b)
{
if(a.length()>b.length())
return a.length();
else
return b.length();
}
public static void main(String[] args)
{
Scanner temp= new Scanner(System.in);
System.out.print(binaryAdder(temp.next(),temp.next()));
}
}
But it doesn't return the right result.
Do you mind help me out here?
thanks a lot!
Reading your question, I understood that you might be looking for some help implementing the methods to actually add two binary numbers, and then giving back the result in base two (which btw might be complicated in Java). However, I believe that this exercise lacks of a very important restriction like the what is max length allowed for the binary numbers to be read (overflows can arise while processing the values with primitive data types like int or String). Also this exercise needs some planning when dealing with none significant zeroes like in these cases because "00110b" = "0110b" = "0110b" and when dealing with rolling over the carry of any addition that yields 2 ("10b") or 3 ("11b"). More information on those topics can be found here, in chapter 2.
At least in Java, when tackling these type of exercises, an option is to avoid dealing with such restrictions and conditions. Java provides a class called BigInteger that takes care of huge values, none significant zeroes, and the carries taking away the burden of dealing with those things from the programmers. Java BigInteger also offers a constructor that can initialize their objects in any base. (Well not any, there are some restrictions to this too, please see this link for more information).
With that said, here is my solution to this exercise:
import java.util.Scanner;
import java.util.ArrayList;
import java.math.BigInteger;
public class BinaryAdder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> numbers = new ArrayList<String>();
String number = "";
int count = 1;
System.out.print("Instructions:\nPlease enter a set of binary numbers. When you are ready to calculate their addition, enter \"done\",\n\n");
System.out.print("Number " + count + ": ");
while(!(number = scanner.next()).equals("done")){
numbers.add(number);
count++;
System.out.print("Number " + count + ": ");
}
System.out.print("Result = " + binaryAdder(numbers) + "b");
scanner.close();
}
public static String binaryAdder(ArrayList<String> numbers){
BigInteger accumulator = new BigInteger("0");
for(String number: numbers){
accumulator = accumulator.add(new BigInteger(number, 2));
}
return accumulator.toString(2);
}
}
Example:
Instructions: Please enter a set of binary numbers. When you are ready
to calculate their addition, enter "done",
Number 1: 00001
Number 2: 011
Number 3: done
Result = 100b
Between lines 8-11 some variables are declared: a scanner to read the binary numbers entered, an array list to store the binary numbers entered, a string to hold a number once is entered, and a int to keep track of how many numbers have been entered, since I extended this solution to add 0,1,2,3,...,n numbers).
Line 13 prints the instructions of this solution. Line 14 only prints "Number 1: ".
The while loop between lines 16-20 sets the value entered to the variable number and checks if it is equal to "done". Given the case it steps out of the loop, otherwise, it adds the number to the array list.
Line 22 prints the result of the addition of all the binary numbers entered.
But the "magic" really happens between lines 27-35 in the method "binaryAdder" (Note that "binaryAdder" receives that ArrayList holding all the numbers entered as a parameter). At line 28 an accumulator of type BigInteger is initialized to zero to hold the addition of all the numbers in the ArrayList. Then, a for loop travels through all the numbers in the array list to add them to the accumulator. Finally, the accumulated value is returned in base two.