2 or more digit numbers with delimiters in java - java
I have this basic program that works pretty well when entering single digit numbers. But when calculating an expression with multiple digits, like 1337 - 456 + 32, the program doesn't move on...it acts likes I did nothing.
It doesn't freeze or output an error message, it just stops.
here's the code:
import java.io.*;
import java.util.*;
public class Tester {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter number: ");
String s = kb.nextLine();
Scanner sc = new Scanner(s);
//Set delimiters to a plus sign surrounded by any amount of white space...or...
// a minus sign surrounded by any amount of white space.
sc.useDelimiter("\\s*");
int sum = 0;
int temp = 0;
int intbefore = 0;
if (sc.hasNext("\\-")) {
sc.next();
if (sc.hasNextInt()) {
intbefore = sc.nextInt();
int temper = intbefore * 2;
intbefore = intbefore - temper;
}
}
if (sc.hasNextInt()) {
intbefore = sc.nextInt(); //now its at the sign (intbefore = 5)
}
sum = intbefore;
while (sc.hasNext()) {
if(sc.hasNext("\\+")) { //does it have a plus sign?
sc.next(); //if yes, move on (now at the number)
System.out.println("got to the next();");
if(sc.hasNextInt()) { //if there's a number
temp = sc.nextInt();
sum = sum + temp; //add it by the sum (0) and the sum of (5) and (4)
System.out.println("added " + sum);
}
}
if(sc.hasNext("\\-")) {
sc.next();
System.out.println("got to the next();");
if (sc.hasNextInt()) {
temp = sc.nextInt();
sum = sum - temp; //intbefore - temp == 11
System.out.println("intbefore: " + intbefore + " temp: " + temp);
System.out.println("subtracted " + sum); // subtracted by 11
}
}
}
System.out.println("Sum is: " + sum);
}
}
Help with why this happens and what to do to fix it?
(I'm using netbeans if that helps)
Also, I'm assuming that the input has a space between each number Ex: 123 + -23 - 5
I tried to execute your code and this is what i found.
Suppose your input was 12+1.
Not sc.hasNextInt() will give you 1 which you are assigning to intbefore.
Next the while loop in your code is going to infinite loop cos sc.hasNext() will always be true (and returning 2 in this case ) and it doesn't match the two if conditions inside the while loop thus making your code run in infinite loop. Now go ahead and work on that. All the best.
Try to change the dilimeter as "\\s+" in the first place or just use the default one
Related
How do you make it so that when you enter a number it puts a space between each integer
import java.util.Scanner; public class Digits { public static void main(String[] args) { /* * count = 1 temp = n while (temp > 10) Increment count. Divide temp by 10.0. */ //Assignment: fix this code to print: 1 2 3 (for 123) //temp = 3426 -> 3 4 2 6 Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); int count = 1; int temp = input.nextInt(); while(temp >= 10){ count++; temp = temp / 10; System.out.print(temp + " "); } } } Need help fixing code. Example: when you type 123 it becomes 1 2 3.
Your code is dividing by ten each time, that could be used to print the value in reverse. To print it forward you need a bit more math involving logarithms. Sometime like, Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); int temp = input.nextInt(); while (temp > 0) { int p = (int) (Math.log(temp) / Math.log(10)); int v = (int) (temp / Math.pow(10, p)); System.out.print(v + " "); temp -= v * Math.pow(10, p); } Alternatively, read a line of input. Strip out all non digits and then print every character separated by a space. Like, String temp = input.nextLine().replaceAll("\\D", ""); System.out.println(temp.replaceAll("(.)", "$1 "));
Most of your code is correct, and what you are trying to do is divide by 10 and then print out the value - this probably should have been a modulus operation % to get the remainder of the operation and print that out - but a nice way of thinking about it. Nevertheless. You can just use a string and then split the string on each character public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer: "); // we know that we are going to get some input - so we will just grab it as a String // whilst we are expecting an int - we will test this later. // we are doing this as it makes it easier to split the contents of a string String temp = input.next(); // is this an int? - we will test this first try { // if this parsing fails - then it will throw a java.lang.NumberFormat exception // see the catch block below int test = Integer.parseInt(temp); // at this point it is an int no exception was thrown- so let's go // through and start printing out each character with a space after it // the temp(which is a string).toCharArray returns a char[] which we // can just iterate through and set the variable of each iteration to 'c' for (char c : temp.toCharArray()) { // now we are going to print out the character with a space after it System.out.print(c + " "); } } catch (NumberFormatException ex){ // this is not an int as we got a number format exception... System.out.println("You did not enter an integer. :("); } // be nice and close the resource input.close(); }
Answering solely your question, you can use this one-line code. int test = 123; System.out.println(String.join(" ", Integer.toString(test).split(""))); Output is: 1 2 3
Making a calculator that does operation of x number of numbers
package com.company; import java.util.*; import java.lang.*; public class ENCRYPTED { public static void main (String args[]) { //Declaring scanner Scanner sc = new Scanner(System.in); //Declaring Arrays double[] numbers = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}; String[] op = {"+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+",}; double[] ans = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}; //Getting Number of Numbers System.out.println(" How many numbers to add/subtract ? : "); int nofns = sc.nextInt(); // for loop that executes to get the numbers for (int i = 0; i < nofns; i++) { System.out.println("Enter Number " + i + " : "); numbers[i] = sc.nextDouble(); System.out.println("Enter Operator for number " + i + " : "); op[i] = sc.next(); ans[i] = numbers[i] + numbers[i+1]; System.out.println(ans[i]); System.out.println(numbers[i]); System.out.println(op[i]); } } } this is a program I made that takes in x numbers of numbers and stores them in the array (numbers) and operators (op). I want to store the operations done (-,+,*,/) on the ans array. I want to get a logic for this program that does the operations and stores them in the array. so these are my question. How do I write this Write this : (This taken from numbers array:5) ((This taken from op array)-) (This taken from numbers array:4) = (Stored and printed in ans aray)1 thanks for all for reading this EDIT: "I just discovered the method for adding and substracting but I still want to find the multiplication and division, Sorry for not commenting the code" THIS IS THE IMPROVED CODE package com.company; import java.util.*; import java.lang.*; public class ENCRYPTED { public static void main (String args[]) { //Declaring scanner Scanner sc = new Scanner(System.in); //Declaring Arrays double[] numbers = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}; String[] op = {"+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+","+",}; double[] ans = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,}; double sum=0; //Getting Number of Numbers System.out.println(" How many numbers to add/subtract ? : "); int nofns = sc.nextInt(); // for loop that executes to get the numbers for (int i = 0; i < nofns; i++) { System.out.println("Enter Number " + i + " : "); numbers[i] = sc.nextDouble(); //Ex : 5 // System.out.println("Enter Operator for number " + i + " : "); // op[i] = sc.next(); //Ex: + System.out.println("Enter Number " + i + " : "); numbers[i+1] = sc.nextDouble(); //Ex : 6 ans[i] = numbers[i] + numbers[i+1]; System.out.println("Answer is " + ans[i]); if (i == nofns) { break; } } for(int i=0; i<nofns; i++){ sum = sum + ans[i]; } System.out.println("Elements of the sums are: "+Arrays.toString(ans)); System.out.println("Sum of the numbers :: "+sum); } } IF anyone can suggest the method for multiplication and division, thanks for the help "OUTPUT: Number one : 4 Number Two : -2 and : 2" NOTE: YOU NEED TO SUFFIX "-" SIGN BEFORE THE NUMBER TO SUBSTRACT IT
This looks like homework so I'll go at a high level. In general, you want to handle each of the 4 cases you have. Those cases are (+-*/) and maybe teh default case where you have invalid input. Then, based on what the value of op[i] you will perform the corresponding item instead of unconditionally adding like this: ans[i] = numbers[i] + numbers[i+1];
How to make for loop stop when scanner is at the very end of the input
I'm currently trying to make a program that will allow the user to enter any amount of integers (I'm only asking them to enter 9 for now as a test) and have the rotateArray function rotate the array of integers. For example: input: 1 2 3 4 5 output: 5 4 3 2 1 The reason as to why I included the arraylist is because I want to make the program dynamically allocate memory so that the user can enter as many single digit inputs as well. My problem is with a for loop I'm currently using. I"m looking for a way to properly make it so that the for loop stops when it hits the very end of the user's input. I tried using scan.nextInt().isEmpty() but that did not work as intended. public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("This program takes two arrays, compares them, and " + "determines whether the original array has been rotated and put " + "into another array. \nWatch what happens when the original " + "array = [0,1,2,3,4,5,6,7,8,9] is compared to an array with contents: \n" + "[9,7,5,3,1,8,6,4,2,0]"); int[] original = {0,1,2,3,4,5,6,7,8,9}; int[] notRotated = {9,7,5,3,1,8,6,4,2,0}; int[] rotatedArray = {9,8,7,6,5,4,3,2,1,0}; boolean rotation; rotation = isRotated(original, rotatedArray); if(rotation == true) { System.out.println("The original array has been rotated!"); }else{ System.out.println("The original array has not been rotated"); } System.out.println("\n Watch what happens when the original array is compared to an array" + " with contents \n [9,8,7,6,5,4,3,2,1,0]"); rotation = isRotated(original, rotatedArray); if(rotation == true) { System.out.println("The original array has been rotated!"); }else{ System.out.println("The original array has not been rotated"); } ArrayList<Integer> userArray = new ArrayList<Integer>(9); System.out.println("This program can also rotate arrays that contain " + "single digit integers.\n Enter 9 single digit " + "integers separated by spaces"); //***************************************************** userArray.add(scan.nextInt()); for(int i = 0; i<userArray.size(); i++) { //*****problem if(???????? ) break; else userArray.add(scan.nextInt()); } System.out.println("The array you entered is: " + userArray.toString() +"\n"); rotateArray(userArray); System.out.println("When your array is rotated, it looks like this: \n" + userArray.toString()); } public static ArrayList<Integer> rotateArray(ArrayList<Integer> userArray) { int replace = 0; int inc = 1; int indexVariable = 0; //if number of elements equals an even number if(userArray.size() % 2 == 0) { for(int i = 0; i < (userArray.size()/2);i++) { replace = userArray.get(i); userArray.set(userArray.get(i),userArray.size() - inc ); userArray.set(userArray.size() - inc, replace); inc++; } } //if number of elements equals an odd number else { for (int i = 0; i <(userArray.size()/2) ; i++) { replace = userArray.get(i); userArray.set(userArray.get(i),userArray.size() - inc ); userArray.set(userArray.size() - inc, replace); inc++; } } return userArray; }
The thing about the scanner is that when its reading from the console, #hasNext will only ever return false if the scanner is closed, such as when you close it or the console is no longer usable for input. Otherwise, calling it will tell the scanner to wait for input and will let you know if it is valid input (e.g if you call #hasNextInt). So the best way IMO to solve your issue is to read the scanner as a string, then split it and process it yourself as follows. String input=scan.nextLine(); String[] numbers=input.split(" "); for(String number:numbers) { if(number.isEmpty()) continue;//check for trailing so input like 3 4 5 is read userArray.add(Integer.parseInt(number));//You would want to add a catch here for invalid input. }
If input: 1 2 3 4 5 and userArray.size should match original.length then you can do like this: int size = original.length; for (int i = 0; i < size; i++) { int num = scan.nextInt(); userArray.add(num); Or you can hardcode variable size: int size = 9; or input it from console: int size = scan.nextInt();
Getting a sum from a while loop
I am trying to get the sum of even numbers between 2 and a value entered by the user. I managed to get as far as printing out the even numbers but how would I get it to print just a sum of the even numbers? Rather than listing out all of the even numbers? At the end it should look like this: Entered value: 20 Sum of even numbers between 2 and 20: 110 import java.util.Scanner; public class Practice_7_1 { public static void main (String[] args) { Scanner input = new Scanner(System.in); while (true) { //Gather data value System.out.println("Please enter a number: "); int value = input.nextInt(); String text = "Sum of even numbers between 2 and " + value + " is: "; //Loop int i = 2; while (i <= value) { if (i%2 == 0){ text = (text + i); if (i< value) text = (text + ", "); else text = (text + ". "); } i++; } //Output System.out.println(text); } } } Edit: Final answer: import java.util.Scanner; public class Practice_7_1 { public static void main (String[] args) { Scanner input = new Scanner(System.in); while (true) { //Gather data value System.out.println("Please enter a number: "); int value = input.nextInt(); String text = "Sum of even numbers between 2 and " + value + " is: "; //Loop int sum = 0; for (int i = 2; i <= value; i +=2){ sum += i; } //Output System.out.print(text); System.out.println(sum); } } }
Use a for loop. With a for loop, you can customize the "step" of your internal loop variable (i). This also removes the need to check for even-ness. int sum = 0; for (int i = 2; i < value; i+=2) { sum += i; } System.out.println(sum); On a side note, you should probably avoid the use of while(true) because it's going to require the use of an explicit break to exit the program. You should instead use some sort of boolean control variable.
A Quiz In Java (Average Guesses Made)
I am coding a quiz game in Java and I can't figure out how to find the average number of guesses a user makes. Here is the game in simple code: import java.util.Scanner; import java.io.File; public class JavaQuiz { public static void main(String[] args) throws Exception { Scanner input = new Scanner(System.in); File file = new File("questions.txt"); Scanner scan = new Scanner(file); String line; double lineNum = 0; int skip = 0; int correct = 0; double guesses = 0; while(scan.hasNextLine()){ // Counting of the line number lineNum = lineNum + 1; // Scanning the next line line = scan.nextLine(); // Declaring the delimeter. String delimiter = "\\|"; // Splitting the line String[] temp = line.split(delimiter); // Print out the questions System.out.println(temp[0]); // Wait for the user to input String keyboard = input.next(); // Take the space off the answer String two = temp[1].replaceAll("\\s",""); if(keyboard.equals("q")){ skip = skip + 1; } else{ while(!(keyboard.equals(two)) && !(keyboard.equals("q"))){ keyboard = input.nextLine(); if(keyboard.equals("q")){ skip = skip + 1; } else { System.out.println("Incorrect. Please Try Again"); } } if(keyboard.equals(two)){ correct = correct + 1; } } } System.out.println("You got " + correct + " Questions Correct."); System.out.println("You skipped " + skip + " questions."); System.out.println("And for the questions you completed, you averaged " + avg + " guesses."); } } Should I do something like this? double avg = guesses / lineNum; I am getting an answer of 0 no matter what though.
After this Line :String keyboard = input.next(); You should do something like this: if(!(keyboard==null)) guesses++; then you are right when: avg=guesses/lineNum; *Tip guesses & lineNum should be int where guesses represents the number of times he answered and lineNum represents the number of lines.There is no need to double here int takes less space than double on Ram