I'm relatively new to Java and I'm trying to write a program for my computer programming class that will accept a string from the user (the string must be something like 1 + 2 - 1) and then take the string, use a delimiter to get rid of the +/- signs, and then perform the addition and subtraction and return the sum of the string input. To do this, my program has to run through a while loop and each time an integer is found it must perform the appropriate function based on whether a + or - sign preceded the number. I'm trying to use .findInLine to have the program determine whether the character is a + or - and then based on this add or subtract the number that follows, but it doesn't seem to work while also using a delimiter and I'm stuck as to what to do. Here's my code:
import java.util.*;
import java.io.*;
public class Lesson17p1_ThuotteEmily
{
public static void main(String args[])
{
Scanner kb=new Scanner(System.in);
System.out.println("Enter something like 8 + 33 + 1,257 + 137");
String s=kb.nextLine();
Scanner sc=new Scanner(s);
char c=sc.findInLine("\\+").charAt(0);
sc.useDelimiter("\\s*\\+\\s*");
double sum=0;
while(sc.hasNextInt());
{
if(c=='+')
{
sum=sum+sc.nextInt();
System.out.println(sum);
}
}
System.out.println("Sum is: "+sum);
}
}
I had code for - signs in the program previously but deleted them temporarily because I want to figure out how to make the program run for addition problems and then I'm going to add in the subtraction programming later, using the same thing that worked for addition.
My code compiles and runs fine, but when it gets to the part where it should be adding and then returning the sum of the problem, it stops. It doesn't return an error or anything, it just freezes. I'm not really sure why this is happening. I need the delimiter for the loop and addition to work, and when I tried taking that out it returned an error. I could remove the find in line but then I'll need a different way for the program to determine whether to add or subtract and I'm struggling to think of anything. I've also tried rearranging my code so it will find the + or - sign first, then use a delimiter to get rid of the symbol and proceed with the addition or subtraction, but again the program froze.
Any help you can give is much appreciated!
Remade the code with comments:
import java.util.Scanner;
import java.util.LinkedList;
public class AddSubstract {
public static void main(String[] args) {
Scanner userInputScanner = new Scanner(System.in);
System.out.print("Type in an expression using + and - operators.\n>> ");
String userInput = userInputScanner.nextLine();
// our example input: " 35 - 245 + 34982 "
userInput = userInput.trim();
// input is now "35 - 245 + 34982"
if(userInput.charAt(0) != '-') userInput = "+" + userInput;
// we need to change the input to a set of operator-number pairs
// input is now "+35 - 245 + 34982"
int result = 0;
// result
byte sign = 0;
// sign; 1 -> positive number, -1 -> negative number, 0 -> not yet checked
int numberToPush = 0;
for(char c : userInput.toCharArray()) {
if(c == '+' || c == '-') {
if(sign == 0) sign = (c == '+')?1:-1;
else {
result += sign*numberToPush;
sign = (c == '+')?1:-1;
numberToPush = 0;
}
} else if(c >= '0' && c <= '9') {
numberToPush = ((int) c-'0') + 10*numberToPush;
}
}
result += sign*numberToPush;
System.out.println("The result is: "+result);
}
Related
This question already has answers here:
Java: parse int value from a char
(9 answers)
Closed 2 months ago.
I'm trying to write a small program that will accept an integer input and count the number of even, odd, and zero digits. I can get everything to work except counting how many times 0 occurs in the integer. If I write my conditional statement like:
if(inputString.charAt(index) == '0')
it works. But if I write:
if(test == 0)
It does not work. For some reason I can't query the existence of 0 directly as a number. I have to change it to a string and find it that way. Why can't I just query it directly like in my second example? Seems like it should be pretty straightforward.
import java.util.Scanner;
public class ParseInt {
public static void main(String[] args) {
//Declarations
int index = 0, test, odd = 0, even = 0, zero = 0;
String inputString;
Scanner scan = new Scanner(System.in);
//Inputs
System.out.println("Input an integer");
inputString = scan.nextLine();
//Process
while(index<= inputString.length()-1)
{
test = inputString.charAt(index);
if(inputString.charAt(index) == '0') //this line here
zero++;
if(test%2 == 0)
even++;
if(test%2 != 0)
odd++;
index++;
}
System.out.println("The number of zero digits is " + zero + ".");
System.out.println("The number of even digits is " + even + ".");
System.out.println("The number of odd digits is " + odd + ".");
scan.close();
}
}
I tried changing the line in question to a string and querying that way. It works, but I want to try and query 0 as a number.
The reason why your second attempt is not working is that a char holds a ASCII reference with has it own integer number. If you want to compare a int to char, you have to convert it and then compare, that's why your first attempt work as both is chars.
When you use inputString.charAt(index) java get the ascii code of number 0 (that is 48).
When you compare it with char '0' Java compare ascii code 48 with 48 and it returns true, if you compare it with a integer Java try to do 0==48 and return false
You can examine this site to see every ascii code https://www.ascii-code.com/
Anyone please help me with the break of the while loop, I just want to end the program when user types nothing in, but why cannot it work? Please do help, thanks a lot.
import java.util.Random;
import java.util.Scanner;
import java.lang.Math;
public class Determining_Pi_Experiment {
public static void main(String[] args) {
while (true) {
System.out.println("Press 'enter' to exit, or type an integer number indicating for how many times you " +
"want the experiment run: ");
Scanner input = new Scanner(System.in);
if(!input.equals(null)) {
if(input.hasNextInt()) {
System.out.println("Processing...");
Random rand = new Random();
int ExperimentTimes = input.nextInt();
double count_success = 0;
double Pi = 0;
for (int i = 0; i < ExperimentTimes; ++i) {
double x = rand.nextDouble();
double y = rand.nextDouble();
double distance = Math.pow(Math.pow((x - 0.5), 2) + Math.pow((y - 0.5), 2), 0.5);
if (distance <= 0.5) {
++count_success;
}
}
Pi = (count_success / ExperimentTimes) * 4;
System.out.println("Pi is approximately equal to: " + Pi);
}
else {
System.out.println("Invalid input.");
}
}
else if(input.equals(null)) {
System.exit(0);
}
}
}
}
I can see many mistakes in your code, I'll walk you through them.
1) Overly complex, overly verbose, checks that aren't needed
2) Missuse of the #equals method
3) Not following standard naming conventions
4) General misunderstanding of how to structure an input-reading loop
To expand on them:
1) Try to simplify your code, remove the while true loop and the else clause (see point 4), declare variables only once, outside, remove reduntant parentheses.
Also, the distance can be computed as Math.hypot(x1-x2, y1-y2) (See here)
2) Notice that the equals method should be used to check if an object is equal to another object. If it were to return true in your example, that would mean that the scanner itself is null (not what it's reading), so the check couldn't work because a NullPointerException would be thrown (calling a method on the null scanner). To check if a Scanner (or any object) is null, you instead want to do anyObject == null. Notice that this has nothing to do with the Scanner input (see point 4).
3) Please correctly name the variables (see here).
4) If you want to keep reading the user input up to the point where no more input is available, you should use Scanner#hasNext . If you instead want to end when an empty string is entered, you should indeed check that the string is empty. This has nothing to do with the scanner being null. someString.isEmpty() will do the job for you.
Pseudo loop:
while(scanner.hasNextLine() && !((line = scanner.nextLine()).isEmpty()))
//do something with the input, stored in the line String
//Exits when enter is pressed (or EOF)
I am trying to only accept integers between the values of 1 and 3 using a while loop and nested if statement in Java.
Anything outside of this range, produces an error message
The program should only accept integers between 1 and 3, any strings of text or decimal values should also produce the same error message and loop back to the original print statement (enter a number: )
The code below runs without any compiler errors although the statement || (a < 1 || a > 3)) will always produce the error message, regardless of the value.
If I was to delete this statement, the program will run and only accept integers of any value, (error message appearing when a string or decimal value is entered)
Could anyone help range this program, only accepting values of between 1 and 3, thanks.
import java.util.Scanner;
public class Validate {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = 0;
while (true) {
System.out.print("enter a number: ");
if (!input.hasNextInt() || !input.hasNext() || (a < 1 || a > 3)) {
System.out.println("Oops! ");
input.nextLine();
}
else {
a = input.nextInt();
break;
}
}
input.close();
System.out.println("a = " + a);
}
}
Make sure to be careful of the order of expressions. If one of the 3 statements you wrote happens to be true then the code in the if curly braces will execute. You likely want something like this
if (!input.hasNextInt() || !input.hasNext()){
if ((a > 1 || a < 3)){
YourCode
}
}
The biggest issue is that you need to remember that initially your integer "a" is set to "0". This always catches your first if condition meaning that a is never set!
You are not updating the value of a, so it's 0 all the time.
import java.util.Scanner;
public class Validate {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = 0;
boolean loop = true;
while (loop) {
System.out.print("enter a number: ");
if (!input.hasNextInt() || !input.hasNext()) {
System.out.println("Oops! ");
input.nextLine();
} else {
a = input.nextInt();
if (a <= 3 && a >= 1)
loop = false;
else {
System.out.println("Oops! ");
input.nextLine();
}
}
}
input.close();
System.out.println("a = " + a);
}
}
EDIT:
I was having problem with the output: it always puts an extra star at the end when there isn't suppose to be. Sample:
m*i*c*h*a*e*l*
When it is suppose to not have an asterisk after l or the last character. Can anyone help me figure this out? Here is my code so far:
import java.util.Scanner;
public class CoolSet2Problem3
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your first name in all lowercase: ");
String name = keyboard.next();
int n = 0;
String star = "*";
while (n < name.length())
{
System.out.print(name.charAt(n) + star);
n++;
}
}
}
My teacher told me that we might have to do something with ASCII character sets, which I have no idea about.
Well when you print the last character you are adding a star at the end of it... Thats why there is one being added at the end.
Try this:
while (n < name.length() - 1)
{
System.out.print(name.charAt(n) + star);
n++;
}
System.out.print(name.charAt(n));
There are a number of approaches. One simple one is to check a boundary condition to see if the star should be printed, e.g.
while (n < name.length())
{
if (n != 0) System.out.print(star);
System.out.print(name.charAt(n));
n++;
}
I'm writing a java program that will count up to a number that the user inputs. The user is only allowed to input a number that is between 1-10.
For instance:
if the user entered 6 the output will be:
1 2 3 4 5 6
How do I do this with only using operators and while and if statements?
Here's my code. I've been painfully trying to figure out why my code won't work. Thanks in advance!
import java.util.Scanner;
public class loop_lab {
public static void main(String[] args) {
System.out.println("Hi user, input any number that is between 1-10");{
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = 0;
if (1<=num1 && num1>=10);
num2=0;
while (num2 < num1)
System.out.println(""+(num2 + 1));
num2++;
}
}
}
I think the problems lies with the code-blocks (the stuff between {}). Especially look at how the while-loop behaves. What is supposed to be in the loop and what not? Also, your if-statement is empty. The ; closes the code-block that is handled by the if.
An IDE can help you detect these errors by applying syntax-formatting. The comments in your code looked like they were coming from Eclipse. Try ctrl-shift-f (or look it up in the menu). This automatically formats and indents your code, this makes it easier to detect errors in the structure.
The if has a stray trailing ; As a result, the next line is always run.
I make it a point to include even single line statements involved with conditional statements and loops inside {/}. That helps make the start & end of the code block clear. My earlier comment about the code indentation is also a factor in identifying where code block begin & end.
First, your conditional check should use an or and braces; and assign 0 to num1, as to prevent the loop from running if the user inputs anything outside the 1-10 range:
if (num1 < 1 || num1 > 10){
num1=0;
}
And you can also improve your loop:
while (num2 < num1) {
System.out.println( ""+ num2++ );
}
Also, as said by user689893, check your {} blocks.
in while loop just change
while (num2 < num1){
if(num2==0)
System.out.println((num2 + 1));
else{
num2++;
System.out.println(num2);
}
}
Try this one
import java.util.Scanner;
public class loop_lab {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hi user, input any number that is between 1-10");
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = 1;
if (1<=num1 && num1>=10){
num2=1;
while (num2 <= num1)
{
System.out.println("" + num2);
num2++;
}
}
}
}