12.9 ; I # 13 jav
3.8 ; can # 6 aru
4.0 ; read # 109 les
The program is supposed to read this in as a string and then add all the doubles, integers, and then to add the first string together and the last string together. So the program should provide
Double total : 20.7
Integer total : 128
Line : I can read
Word: javarules
This is what I have so far , I know that I have to use scanner to skip over the tokens .
public class Test {
public static void main (String args[]) throws FileNotFoundException {
Scanner sc = new Scanner(Test4.class.getResourceAsStream("week2inputdata.txt"));
double doubletotal = 0;
int inttotal = 0;
String line = " ";
String word;
Scanner scanLine;
while (sc.hasNextLine()){
scanLine = new Scanner (sc.nextLine());
scanLine.next();
line += sc.hasNextLine();
inttotal += sc.nextInt();
// scanLine = new Scanner (sc.nextLine());
// scanLine.next();
// line += sc.next() + " ";
// inttotal += sc.nextInt();
doubletotal += sc.nextDouble();
}
System.out.println(inttotal);
System.out.println(doubletotal);
System.out.println(line);
}
}
This is rather ugly but it will work,
String[] weirdLookingString = new String[] { "12.9 ; I # 11 jav", "3.8 ; can # 11 aru"
,"4.0 ; read # 109 les" };
double doubleValue = 0.0;
String strValue1 = "";
String strValue2 = "";
int integerValue = 0;
for (int i = 0; i < weirdLookingString.length; i++) {
String array[] = weirdLookingString[i].split("[;\\#]\\s+");
String lastString[] = array[2].split("\\s");
integerValue += Integer.parseInt(lastString[0]);
doubleValue += Double.parseDouble(array[0]);
strValue2 += lastString[1];
strValue1 += array[1];
}
System.out.println("Integer value: " + integerValue);
System.out.println("Double value: " + doubleValue);
System.out.println("Words: " + strValue2);
System.out.println("Line: " + strValue1);
output,
Integer value: 131
Double value: 20.7
Words: javarules
Line: I can read
You can create an arraylist of double, Integers and then create a sb builder for the first set of string and a stringBuilder for the second set of strings.
String line = "12.9 ; I # 13 jav";
String str[] = line.split("[;\\#\\s+]");
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
ArrayList<Double> doubleArray = new ArrayList();
ArrayList<Integer> intArray = new ArrayList();
for(int i =0; i < str.length; i++){
if(i == 0){
doubleArray.add(Double.parseDouble(str[i]));//convert to double and add it to the list
}else if(i == 1){
sb.append(str[i]);
}else if(i == 2){
doubleInt.add(Integer.parseInt(str[i]));//convert it to integer and add to the list
}else if(i == 3){
sb2.append(str[i]);
}
}
you can put everything in a loop so you won't have to rewrite everything. after everything has been added you can build a string using the stringBuilder and add everything using the array from arrayList
Related
Input:
2,3,1
5,2,3
Expected Output:
2,5,3,2,1,3
All digits should be separated with a comma.
My code:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input1 = scanner.nextLine();
char[] elms1 = input1.toCharArray();
String input2 = scanner.nextLine();
char[] elms2 = input2.toCharArray();
for (int i = 0; i < elms1.length; i++)
System.out.print(elms1[i] + "," + elms2[i]);
}
Alas, it outputs an unexpected result with extra commas and it looks like:
Input:
2,3,1
5,2,3
My Output is:
2,5,,,3,2,,,1,3
How can I eliminate extra commas to get the right output?
What you have to do is to just make a little change in your print statement as:
for (int i = 0; i < elms1.length; i++) {
if (i == elms1.length - 1) {
System.out.print(elms1[i] + "," + elms2[i]);
} else {
System.out.print(elms1[i] + "," + elms2[i] + ",");
}
}
You can do:
Scanner scanner = new Scanner(System.in);
String input1 = scanner.nextLine();
List<Integer> elms1 = Arrays.stream(input1.split(",")).map(Integer::parseInt).collect(Collectors.toList());
String input2 = scanner.nextLine();
List<Integer> elms2 = Arrays.stream(input2.split(",")).map(Integer::parseInt).collect(Collectors.toList());
for (int i = 0; i < elms1.size()-1; i++) {
System.out.print(elms1.get(i) + "," + elms2.get(i) + ",");
}
System.out.print(elms1.get(elms1.size()-1) + "," + elms2.get(elms1.size()-1));
Output (based on your input):
2,5,3,2,1,3
You can change your print statement for your current code which would take 2 characters from each array at a time considering commas to be a valid character input. Here's your code fix:
for (int i = 0; i < elms1.length; i += 2) {
if (i == elms1.length - 1)
System.out.print(elms1[i]+","+elms2[i]);
else
System.out.print(elms1[i]+""+elms1[i+1]+""+elms2[i]+""+elms2[i+1]);
}
I'm trying to get the 2D array from the text file. So far I accessed the file and got all the numbers in the file, but all these numbers are string so I used split() and then convert it to double. How can convert this to double 2D array?
1.65 4.50 2.36 7.45 3.44 6.23
2.22 -3.24 -1.66 -5.48 3.46
4.23 2.29 5.29
2.76 3.76 4.29 5.48 3.43
3.38 3.65 3.76
2.46 3.34 2.38 8.26 5.34
This is what I have so far:
public static void main(String[] a) throws FileNotFoundException {
File file = new File("district3.txt");
Scanner scan = new Scanner(file);
String b;
String[] c;
int r = 6;
double[][]arr = new double[r][];
while(scan.hasNextLine()) {
//get number as String
b = scan.nextLine();
//split them
c = b.split(" ");
for(String i:c)
System.out.println(Double.parseDouble(i) );
}
}
Change your for to print inline and then add a println after you've printed all the numbers:
for(String i:c)
System.out.print(i + " ");
System.out.println()
To store the numbers you can do the following:
double[][]arr = new double[r][];
int i = 0;
while(scan.hasNextLine()) {
//get number as String
b = scan.nextLine();
//split them
c = b.split(" ");
arr[i] = new double[c.length];
for(int j = 0; j < c.length; ++j) {
arr[i][j] = Double.parseDouble(c[j]);
// Display them if needed
System.out.print(c[j] + " ");
}
System.out.println();
++i;
}
This question already has answers here:
How to read integer value from the standard input in Java
(7 answers)
Closed 3 years ago.
I'm trying to have the user input 2 strings into this function so that they can be compared.
I am not too familiar with java more familiar with c++ and I'm not a dev.
public class Levenshtein {
public static int distance(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
// i == 0
int [] costs = new int [b.length() + 1];
for (int j = 0; j < costs.length; j++)
costs[j] = j;
for (int i = 1; i <= a.length(); i++) {
// j == 0; nw = lev(i -1, j)
costs[0] = i;
int nw = i - 1;
for (int j = 1; j <= b.length(); j++) {
int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1);
nw = costs[j];
costs[j] = cj;
}
}
return costs[b.length()];
}
public static void main(String [] args) {
String [] data = { "kitten", "Mitten" };
for (int i = 0; i < data.length; i += 2)
System.out.println("distance(" + data[i] + ", " + data[i+1] + ") = " + distance(data[i], data[i+1]));
}
}
just use the args in main
public static void main(String [] args) {
for (int i = 0; i < args.length; i += 2)
System.out.println("distance(" + args[i] + ", " + args[i+1] + ") = " + distance(args[i], args[i+1]));
}
and run it with java -jar app.jar kitten mitten
Here's an example of how to use Scanner to read inputs in Java.
Scanner s = new Scanner(System.in);
String first = s.nextLine();
String second = s.nextLine();
String[] nextTwo = s.nextLine().split(" ");
System.out.println(first);
System.out.println(second);
System.out.println(nextTwo[0]);
System.out.println(nextTwo[1]);
s.close();
Sample input
I am a teapot
Short and stout
Here is my handle
Sample output
I am a teapot
Short and stout
Here
is
As for how to apply this in your program, simply do the following:
public static void main(String [] args) {
// Using this construct, the "try-with-resources" block, will automatically
// close the Scanner resource for you
try(Scanner s = new Scanner(System.in) {
System.out.println("Enter first word:");
String first = s.nextLine();
System.out.println("Enter second word:");
String second = s.nextLine();
System.out.println(String.format("The distance is: %d",distance(first, second)));
}//Scanner s is automatically closed here
}
Note that you should generally NOT close the System.in stream, as it will disallow you from reading input in the rest of the program. However, as your program terminates in the scope of the try-with-resources block, it is acceptable to do so in this scenario.
One approach you can take to close Scanners linked to your System.in stream is to wrap System.in in a CloseShieldInputStream, as seen here.
You can use the scanner object:
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
I use Scanner for inputs from the Console.
U can do:
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = sx.nextLine();
System.out.println("distance(" + s1 + ", " + s2 + ") = " + distance(s1, s2));
sc.close();
Im trying to collect some data from a user and display it with the user input. the example i was giving is:
Filename: output.txt
number of lines: 4
Line Length: 8
Character Set: ABC123
2CB3A32C
BB13CAA3
C3A21CB2
CC2B13A3
i currently have gotten the user input but i dont know how to display the random letters and numbers based on the input. Here is my code. Any help would be big.
the data has to be displayed using Loop.
public static void main(String[] args) throws IOException
{
int lineNum = 0;
int numChars = 0;
String charSet = "";
String userInput = "";
String filename;
//Creates a Scanner Object for keyboard input.
Scanner keyboard = new Scanner(System.in);
//Get the filename.
System.out.print("Enter a filename: ");
filename = keyboard.nextLine();
System.out.print("Enter number of lines: ");
lineNum = keyboard.nextInt();
if( lineNum < 1 || lineNum > 20){
lineNum = 20;
System.out.println("Defaulting to 20 lines");
}
System.out.print("Enter number of characters in each line: ");
numChars = keyboard.nextInt();
keyboard.nextLine();
if( numChars < 1 || numChars > 20){
numChars = 20;
System.out.println("Defaulting to 20 characters");
}
System.out.print("Enter character set: ");
charSet = keyboard.nextLine();
//Put all the input together to display the results
PrintWriter pw = new PrintWriter(filename);
pw.println("\nFilename: " + filename);
pw.println("Number of lines: " + lineNum );
pw.println("Line Length: " + numChars );
pw.println("Character set: " + charSet );
pw.println("\n" + userInput );
pw.close();
// Read the file
BufferedReader br = new BufferedReader(new FileReader(filename));
for (String line; (line = br.readLine()) != null;) {
System.out.println(line);
}
}
Try this.
Random random = new Random();
for (int i = 0; i < lineNum; ++i) {
for (int j = 0; j < numChars; ++j)
pw.print(charSet.charAt(random.nextInt(charSet.length())));
pw.println();
}
Take a look at: RandomStringUtils
This might help get you on the right track:
import org.apache.commons.lang.RandomStringUtils;
System.out.println(RandomStringUtils.random(8,new char[]{'a','b','c','1', '2', '3'}));
Try:
str.charAt(ThreadLocalRandom.current().nextInt(0, str.length()));
In Java8
final int length = 8;
final Random rand = new Random();
String random = IntStream.range(0, length).mapToObj(i -> str.charAt(rand.nextInt(100) % str.length()) + "").collect(Collectors.joining());
System.out.println(random);
random string generated for 10 runs
A31CCCB3
1AC3A2CA
BAB11B2A
A33A1ACA
BCCCB2AC
331C12CA
3CC1AAB3
113BAABB
1BC22B1A
31BBCAC1
You can use the below Utilty class
import java.util.Random;
public class RandomString {
private char[] symbols;
private final Random random = new Random();
private final char[] buf;
public RandomString(int length ,char[] symbols) {
if (length < 1)
throw new IllegalArgumentException("length < 1: " + length);
buf = new char[length];
this.symbols = symbols;
}
public String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return new String(buf);
}
}
To Use it from your main,
RandomString randString = new RandomString(numChars ,charSet.toCharArray());
for (int i = 0; i < lineNum; i++) {
System.out.println("" +randString.nextString());
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I have to get a string input and an integer input, but there order of input should be that integer comes first then user should be asked for string input
Scanner in = new Scanner(System.in);
input = in.nextLine();
k = in.nextInt();
in.close();
The above code works fine but if I take an integer input first like in the following code
Scanner in = new Scanner(System.in);
k = in.nextInt();
input = in.nextLine();
in.close();
then it throws the java.lang.ArrayIndexOutOfBoundsException.
Here's the complete code of my source file:
import java.util.Scanner;
public class StringSwap {
public static void main(String args[]) {
String input;
int k;
Scanner in = new Scanner(System.in);
k = in.nextInt();
input = in.nextLine();
in.close();
int noOfCh = noOfSwapCharacters(input);
originalString(input, noOfCh, k);
}
public static int noOfSwapCharacters(String s) {
char cS[] = s.toCharArray();
int i = 0, postCounter = 0;
while (cS[i] != '\0') {
if (cS[i] != '\0' && cS[i + 1] != '\0') {
cS[cS.length - 1 - postCounter] = '\0';
postCounter++;
}
i++;
}
return postCounter;
}
public static void originalString(String s, int noOfCh, int k) {
int counter = 1, chCounter = 0;
char cArray[] = s.toCharArray();
String post = "";
String pre = "";
String finalString = "";
char temp;
for (int i = 1; i <= k; i++) {
chCounter = 0;
counter = 1;
post = "";
pre = "";
for (int j = 0; j < cArray.length; j++) {
if (counter % 2 == 0 && chCounter <= noOfCh) {
temp = cArray[j];
post = temp + post;
cArray[j] = '\0';
chCounter++;
}
counter++;
}
for (int h = 0; h < cArray.length; h++) {
if (cArray[h] != '\0')
pre = pre + cArray[h];
}
finalString = pre + post;
for (int l = 0; l < finalString.length(); l++) {
cArray[l] = finalString.charAt(l);
}
}
System.out.println(finalString);
}
}
Kindly point out what I am doing wrong here.
The problem is the '\n' character that follows your integer. When you call nextInt, the scanner reads the int, but it does not consume the '\n' character after it; nextLine does that. That is why you get an empty line instead of the string that you were expecting to get.
Let's say your input has the following data:
12345
hello
Here is how the input buffer looks initially (^ represents the position at which the Scanner reads the next piece of data):
1 2 3 4 5 \n h e l l o \n
^
After nextInt, the buffer looks like this:
1 2 3 4 5 \n h e l l o \n
^
The first nextLine consumes the \n, leaving your buffer like this:
1 2 3 4 5 \n h e l l o \n
^
Now the nextLine call will produce the expected result. Therefore, to fix your program, all you need is to add another call to nextLine after nextInt, and discard its result:
k = in.nextInt();
in.nextLine(); // Discard '\n'
input = in.nextLine();