I ask the user to insert numbers in the console.
Then, I print those numbers but if any number contains "-", it will be converted in the same number inside parentheses..
For example: if user inserts 5 -17 35 -8 ,the output will be 5 (-17) 35 (-8)
The code I have tried:
public class Run {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter numbers");
String s = input.nextLine();
String[] split = s.split(" ");
for (int i = 0; i < split.length; i++) {
if (split[i].contains("-")) {
split[i].replace(split[i], "(" + split[i] + ")");
}
}
input.close();
System.out.println(Arrays.toString(split));
}
}
But it does not work as it prints numbers exactly as the user inputs them..
For instance, 5 -17 35 -8 and not 5 (-17) 35 (-8)..
I'm new in Java so that's why I can't understand what's wrong..
You are replacing the - with your desired format but then you are not storing it back in the split array.
You have to replace the following code snippet:
if (split[i].contains("-")) {
split[i].replace(split[i], "(" + split[i] + ")");
}
Here is the corrected code snippet:
if (split[i].contains("-")) {
/* Change Here */
split[i] = split[i].replace(split[i], "(" + split[i] + ")");
}
You don't do anything with the replaced string.
Simply calling this method won't replace the string directly, it returns a new string, which you simply ignore.
split[i].replace
So you have to do
spilt[i] = split[i].replace
The method replace(...) does not change the String you work on, but creates a new String with the replaced values.
You have to assign the result of split[i].replace(split[i], "(" + split[i] + ")"); back to split[i].
Related
I am taking a Java course and I am stumped on this question. I was to complete most of it up until the portion where I am required to convert a String to ASCII. I am able to get the first letter to output to Edit Unicode but it stops there. When I isolate the code on a scratch file and use a print statement it prints how it should:
class Scratch {
public static void main(String[] args) {
String str = "yams";
for (int i = 0; i < str.length(); i++) {
int numUni = (int)str.charAt(i);
int unicode = (int)numUni;
System.out.print(unicode + " ");
//return unicode; // this line will need to be changed
}
}
}
Output:
121 97 109 115
Process finished with exit code 0
Here is the code that I have completed so far and my issue is with Step 4:
public class Strings{
// STEP one - concatenateStrings()
public String concatenateStrings(String word1, String word2){
String concantWord = word1 + " " + word2;
return concantWord;
}
// STEP two - charToASCII()
public int charToASCII(char character){
int convertedChar = character;
return convertedChar;
}
// STEP three
public char getLastChar(String str){
//student code here\
int strLength = str.length();
char lastChar = str.charAt(str.length() - 1);
return lastChar; // this line will need to be changed
}
// step 4
public static String translateWord(String str){
//student code here
for (int i = 0; i < str.length(); i++) {
int numUni = (int)str.charAt(i);
String unicode = numUni + " ";
return unicode; // this line will need to be changed
}
return "";
}
// step 5
public String madLib(String noun1, double number, String pastTenseVerb, String adjective, String noun2) {
//student code here
return ""; // this line will need to be changed
}
/**
* A test block helps you test as you write. Eventually, you will learn
* test driven development, in which every method you write will have tests you write
* to make sure it works.
*
* Uncomment these lines out as you finish your various methods
*/
public void runTests() {
System.out.println();
//Concatenate Strings test
System.out.println("Testing concatenateStrings method: ");
System.out.println("Input: 'good','morning' \t Expecting: good morning\t Actual: " + concatenateStrings("good", "morning"));
System.out.println();
//Char to ASCII test
System.out.println("Testing charToASCII method: ");
System.out.println("Input: 'c' \t Expecting: 99\t Actual:" + charToASCII('c'));
System.out.println();
//Get Last Char test
System.out.println("Testing getLastChar method: ");
System.out.println("Input: 'Pterodactyl' \t Expecting: L\t Actual: " + getLastChar("Pterodactyl"));
System.out.println();
//Translate Word Test
System.out.println("Testing Translate word method: ");
System.out.println("Input: 'yams' \t Expecting: 121 97 109 115\t Actual: " + translateWord("yams"));
// System.out.println();
// Mad Libs Test
// System.out.println("Testing Mad Libs method: ");
// System.out.println("Input: 'pear, 202.356, swam, purple, bear'"
// + "\nExpecting: Today I went to the store and bought a pear for $202.36.\nThen I swam and saw a purple bear."
// + "\nActual: " + madLib("pear", 202.356, "swam", "purple", "bear"));
}
public static void main(String [] args) {
// running test method
Strings f = new Strings();
f.runTests(); // this is not a static method (should it have been?) so you have to run it with the object
}
}
I would appreciate any guidance.
Obviously, if you return inside a loop, the loop will only ever execute once.
You want to 'build up' your string, one ascii code at a time (well, unicode codepoint, really - as others have pointed out, I don't know what dank late 80s outdated cruft you're following, mate - the days of ASCII are loooong gone), so you need a StringBuilder, you want to append 'numUni + " "' to this in the loop, and then return the stringbuilder, built up to a string:
StringBuilder out = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
int uni = (int) str.charAt(i);
out.append(uni).append(" ");
}
return out.toString();
You're returning the ascii value immediately after the first iteration, edit your code to look something like below:
public static String translateWord(String str) {
//student code here
String ascii = "";
for (int i = 0; i < str.length(); i++) {
int numascii = str.charAt(i);
ascii += numascii + " ";
}
return ascii;
}
edit: As mentioned by commenter below, definitely read about String pool, StringBuilder and StringBuffer
When i run the following program I get an error at line 20, and this is my code:
package J1;
import java.util.Scanner;
public class SpeedLimit {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.next();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + "miles" + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
}
when i run the code, I enter the following input from the keyboard:
3
20 2
30 6
10 7
2
60 1
30 5
4
15 1
25 2
30 3
10 5
-1
to get this result as an output:
170 miles
180 miles
90 miles
but i get the following Error when i run the code
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at J1.SpeedLimit.main(SpeedLimit.java:20)
String pair = keyboard.next(); This reads only one token which are separated by " " so when you split pair by " ". It will only have one element, The String itself. So you need to read the whole line and then split it by delimited " ".
Another mistake is that when you change that line with String pair = keyboard.nextLine(); , You will still get error because System considers Enter key as input of .nextLine() method. So you need to discard that extra unnecessary input.
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
int ip1=keyboard.nextInt();
int ip2=keyboard.nextInt();
speed = speed + ip1*(ip2-last);
last = ip2;
}
output = output +speed + "miles" + "\n";
speed =0;
input = keyboard.nextInt();
}
You are reading the variable pair the wrong way and then you split it and assign it to tab which fails to automatically to fetch index cause pair variable got a problem.
*nextLine(): reads the remainder of the current line even if it is empty.
keyboard.nextLine(); //To avoid the exception you commented
String pair = keyboard.nextLine(); //here is solved
tab = pair.split(" ");
Keyboard.next() will only read the input till the space, so pair and the array will have only one number, so tab[1] results in arrayOutOfBound exception. Use the method nextLine() to read the inputs with space.
You Can try below changes in your code :
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = Integer.parseInt(keyboard.nextLine());
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.nextLine();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0].trim())*(Integer.parseInt(tab[1].trim())-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + " miles " + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
i did'n really understand how you are providing the inputs. but, if "3" happens to be your first line then split(" ") would return an array of length 1. thus, tab[0] would return 3 and tab[1] will give you a nullPointerException.
try adding an check for the length of tab before executing your line 20.
this should do the trick:
if(tab.length() > 1){
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
}
I have stored two text files into two separate arrays. Now, I am trying to compare both arrays to find duplicate values. I am having issues with my logic, and I am unable to print out the number of times a duplicate value appears.
file1 contains:
1913 2016 1 1913 186
2016 1711 32843 2016 518
3 1913 32843 32001 4
250 5 3500 6 7
8 27 73 9 10
1711 73 11 2 1.4
1.4 12 33.75278 84.38611 1913
19 1930 20 21 1947
22 1955 23 1961 23
1969 27 1995 26 27
1962 28 29 30 1970
31 31
file2 contains:
1913 2016 32843 31 27 1.4 4 7 2 23
I am trying to find values in file2 that are duplicated in file1, and how many times.
I have the following code:
public static void findDuplicates() {
// array for first file
for (int n = 0; n < nums.size(); n++) {
// matches are false by default
boolean match = false;
int count = 0;
String v = nums.get(n);
// array for second file
for (int k = 0; k < nums1.size(); k++) {
String p = nums1.get(k);
// second file contains values from first file
if (p.contains(v)) {
// there is a match
match = true;
// when there is a match print out matched values and the number of times they appear in second file
if (match) {
count++;
System.out.println( p + " " + "is duped" + " " + count + " " + "times");
}
}
}
}
}
When I compile and run this code, this is the output:
31 is duped 1 times
Could someone let me know what I am doing wrong here?
EDIT
Here is the rest of my code:
public static ArrayList<String> nums;
public static ArrayList<String> nums1;
//Create a main method to start the program.
//Add FileNot FoundException in case the file can't be found by computer.
public static void main(String[] args) throws FileNotFoundException{
//The while will help us read the content into our computer piece by piece. It will not stop until the end of assignment.csv.
while(FILE1.hasNext()){
//Create a String variable - TempString. We use TempString to store each piece temporarily.
String TempString = FILE1.next();
String temp1 = TempString.replaceAll("[\\,]", "");
String pattern1 = "[0-9]+\\.{1}[0-9]+";
//Compile the Regular Expression into Pattern and store it in r1 so that the computer can understand the Regular Expression.
Pattern r1 = Pattern.compile(pattern1);
Matcher m1 = r1.matcher(temp1);
String pattern2 = "[0-9]+";
//Compile the Regular Expression into Pattern and store it in r2 so that the computer can understand the Regular Expression.
Pattern r2 = Pattern.compile(pattern2);
Matcher m2 = r2.matcher(temp1);
nums = new ArrayList<String>();
//Recollect, m1 is used to match decimal numbers.
if(!(m1.find())){//if a decimal number CAN'T be found
//We use while statement instead of if statement here.
//If there is only one piece per line, we can use either while statement or if statement.
//However, we have to use while statement if there is more than one piece per line.
while(m2.find()) {//if an integer number CAN be found
//If an Integer is found, we add 1 to Variable count.
count++;
//Even though the number (i.e., m2.group(0)) is an Integer, its data type is String. So we store it to a String variable - number.
String number = m2.group(0);
nums.add(number);
//If the remainder of count by 5 is zero, we display the number and advance to a new line.
if (count % 5 == 0){
System.out.println(number);
}
//Otherwise, we just display the number on the same line and divide numbers by a space.
else
System.out.print(number + " ");
}
}
//If we find a decimal number
else{
//We add 1 to Variable count.
count++;
//Even though the number (i.e., m1.group(0)) is a decimal number, its data type is String. So we store it to a String variable - number.
String number = m1.group(0);
nums.add(number);
//If the remainder of count by 5 is zero, we display the number and advance to a new line.
if (count % 5 == 0) {
System.out.println(number);
}
//Otherwise, we just display the number on the same line and divide numbers by a space.
else
System.out.print(number + " ");
}
}
FILE1.close();//Once we finish the task, we close the file.
while(FILE2.hasNext()){
//Create a String variable - TempString. We use TempString to store each piece temporarily.
String TempString = FILE2.next();
//So I use replaceAll function to eliminate comma (,) and store the new string in temp1.
String temp1 = TempString.replaceAll("[\\,]", "");
String pattern1 = "[0-9]+\\.{1}[0-9]+";
//Compile the Regular Expression into Pattern and store it in r1 so that the computer can understand the Regular Expression.
Pattern r1 = Pattern.compile(pattern1);
//Match the Regular Expression with the piece (temp1) we read from assignment.csv.
Matcher m1 = r1.matcher(temp1);
String pattern2 = "[0-9]+";
//Compile the Regular Expression into Pattern and store it in r2 so that the computer can understand the Regular Expression.
Pattern r2 = Pattern.compile(pattern2);
//Match the Regular Expression with the piece (temp1) we read from assignment.csv.
Matcher m2 = r2.matcher(temp1);
nums1 = new ArrayList<String>();
//We have two types of numbers - Integer and Decimal
//Let's start us Integer.
//Recollect, m1 is used to match decimal numbers.
if(!(m1.find())){//if a decimal number CAN'T be found
//We use while statement instead of if statement here.
//If there is only one piece per line, we can use either while statement or if statement.
//However, we have to use while statement if there is more than one piece per line.
while(m2.find()) {//if an integer number CAN be found
//If an Integer is found, we add 1 to Variable count.
count++;
//Even though the number (i.e., m2.group(0)) is an Integer, its data type is String. So we store it to a String variable - number.
String number = m2.group(0);
nums1.add(number);
//If the remainder of count by 5 is zero, we display the number and advance to a new line.
if (count % 5 == 0){
//System.out.println(number);
}
//Otherwise, we just display the number on the same line and divide numbers by a space.
else
System.out.println(/*number + " "*/);
}
}
//If we find a decimal number
else{
//We add 1 to Variable count.
count++;
//Even though the number (i.e., m1.group(0)) is a decimal number, its data type is String. So we store it to a String variable - number.
String number = m1.group(0);
nums1.add(number);
//If the remainder of count by 5 is zero, we display the number and advance to a new line.
if (count % 5 == 0){
//System.out.println(number);
}
//Otherwise, we just display the number on the same line and divide numbers by a space.
else
System.out.println(/*number + " "*/);
}
findDuplicates();
}
FILE2.close();//Once we finish the task, we close the file.
}
I tried to delete as much unnecessary code as I could.
EDIT
Expected output should be:
1913 is duplicated 3 times.
2016 is duplicated 2 times.
32843 is duplicated 1 times.
31 is duplicated 2 times.....
EDIT
So I believe i've found the problem. For some reason,
String p = nums.get(k)
in my findDuplicates() method is only returning the value 31, and not the other values. I am working on solving the problem, and will post an answer when I do.
I think the biggest issue is that the printline is inside the second for loop.Furthermore I would remove the boolean and just compare the 2 Strings (p==v).
So the code would look more like this:
public static void main(String[] args) {
// array for second file
for (int n = 0; n < nums1.size(); n++) {
// matches are false by default
int count = 0;
String v = nums1.get(n);
// array for first file
for (int k = 0; k < nums.size(); k++) {
String p = nums.get(k);
// second file contains values from first file
if (p==v) {
count++;
}
}
System.out.println( v + " " + "is duped" + " " + count + " " + "times");
}
}
}
With the changes I made the code runs as intended.You can check out a live demo here.
Output:
1913 is duped 4 times
2016 is duped 3 times
32843 is duped 2 times
31 is duped 2 times
27 is duped 3 times
1.4 is duped 2 times
4 is duped 1 times
7 is duped 1 times
2 is duped 1 times
23 is duped 2 times
You should use the System.out.println statement outside inner loop so that first whole of second arraylist get iterated before number of times the number is duplicated is printled.
You also need to make a few other changes to run the program correctly
for (int n = 0; n < nums.size(); n++) {
// matches are false by default
boolean match = false;
int count = 0;
String v = nums.get(n);
// array for second file
for (int k = 0; k < nums1.size(); k++) {
String p = nums1.get(k);
// second file contains values from first file
if (p.contains(v)) {
// there is a match
match = true;
// when there is a match print out matched values and the number of times they appear in second file
if (match) {
count++;
match = false;
}
}
System.out.println( p + " " + "is duped" + " " + count + " " + "times");
count = 0;
}
}
But still then your logic will not work all case because you are not comparing how many times a number is repeated in first file. You are only comparing second file numbers with first file ones. For the case which you gave in question interchanging the two files after modifying the code as I have mentioned it will work.
please try it on.
package stackoverflow.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public List<Integer> list = new ArrayList<Integer>();
public List<Integer> dup = new ArrayList<Integer>();
public Map<Integer, Integer> hashDup = new HashMap<Integer, Integer>();
public void fileReader() {
File file = new File("/home/john/Documents/file1.txt");
List<Integer> list1 = this.output(file);
File file2 = new File("/home/john/Documents/file2.txt");
List<Integer> list2 = this.output(file2);
for (int i = 0; i < list1.size(); i++) {
int counter = 0;
for (int j = 0; j < list2.size(); j++) {
if (list1.get(i) == list2.get(j)) {
counter++;
}
}
if (!hashDup.containsKey(list1.get(i))) {
hashDup.put(list1.get(i), counter);
System.out.println(" dup " + list1.get(i) + " :" + counter);
}
}
}
public List<Integer> output(File file) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
// System.out.println( text);
String[] str = text.split(" ");
for (String string : str) {
list.add(Integer.parseInt(string));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
// print out the list
// System.out.println(list.toString());
return list;
}
public static void main(String args[]) {
Test t = new Test();
t.fileReader();
}
}
I have to write a program that takes a user's chemical equation as an input, like NaCl2, and separate it out into individual elements and the number associated with them. Is there a way to parse through a string and pair the individual elements, like in NaCl2 into Na and Cl2?
As you mentioned in a comment, checking whether letters are uppercase or lowercase is key to this problem. What you're looking for to solve this is the Character.isUppercase() method. Your code should iterate over the characters in the input String and pass each to this method. I wrote up this rough draft of a code to demonstrate it (and it also prints the output for you - how convenient!):
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> elements = new ArrayList<>();
System.out.print("Enter formula: ");
String formula = sc.next();
String s = "";
for (int i=0; i<formula.length(); i++) {
if (Character.isUpperCase(formula.charAt(i))) {
if (!s.isEmpty()) {
elements.add(s);
}
s = "" + formula.charAt(i);
} else {
s += formula.charAt(i);
}
}
elements.add(s);
for (int i=0; i<elements.size(); i++) {
System.out.print(elements.get(i) + " ");
}
System.out.println();
}
This can be done a number of ways. One of them is using regular expressions. In this case the expression looks for an uppercase character, followed optionally by a lower case character, followed optionally by a number.
Pattern elementPattern = Pattern.compile("(\\p{Upper}\\p{Lower}?)(\\p{Digit}*)");
This can be used to find all the elements in the input:
Matcher elementMatcher = elementPattern.match(input);
while (elementMatcher.find()) {
String element = elementMatcher.group(1);
String count = elementMatcher.group(2);
System.out.println("Element: " + element + " count: " + count);
}
I'm working on a recursive method that will return and print in my main method a String that will count down by 1 for N. Deleting one letter for each recursion for the string. Until N becomes 1 or until the string has 1 letter. (N being a int on the commandline)
For example if my command lines aruments are: 5 valentine
It should output too:
5 valentine, 4 alentine, 3 lentine, 2 entine, 1 ntine,
So far I managed to count down the number inputted on the commandline argument. I just don't know how to go about deleting one letter from the string? :o
My code so far:
public static void main(String[] args){
int number = Integer.parseInt(args[0]);
String word = new String("");
word = args[1];
String method = recursive.method1(number);
System.out.println(method);
}
public static String method1(int number){
if (number < 0){
return "";
}
else{
return number + ", " + method1(number - 1);
}
}
You can read through subString() documentation to understand how to go about taking the portions of a String.
Change your method definition to include the word
Add the word to your return statement: return number + " " + word +...
Call substring of the original word from the 1st index
Check for <=0 rather than <0
Code:
public static void main(String[] args){
int number = 5;
String word = new String("");
word = "Valentine";
String method = Recurcive.method1(number, word);
System.out.println(method);
}
public static String method1(int number, String word){
if (number <= 0){
return "";
}
else{
return number + " " + word + ", " + method1(number - 1, word.substring(1));
}
}
Gives,
5 Valentine, 4 alentine, 3 lentine, 2 entine, 1 ntine,