i have generated a pace of code that gets 4 inputs and calculates the square roots of all of them.
int i;
System.out.print("print numbers here:");
int[] arr = new int[4];
Scanner in = new Scanner(System.in);
for (i = 0; i < arr.length; i++ ){
arr[i] = in.nextInt();
}
for (i = arr.length; i > 0; --i){
double s =Math.sqrt(arr[i-1]);
System.out.println(s);
}
here is the code from main method but one important part that i still need to add is to get user inputs with spaces and line breaks. So, for instance
1427 0
876652098643267843
5276538
1427 is first num, 0 the second and etc.. i am new to java and programming and i don't have any idea please help if you can.
thanks in advance!!
Replace your nextInt() call with next(). This will retrieve the next word, with whitespace characters as seperators (newlines and spaces). This will allow for any number of spaces, empty lines etc.
Example:
System.out.print("print numbers here:");
int[] arr = new int[4];
Scanner in = new Scanner(System.in);
for (int i = 0; i < arr.length; i++){
int num;
try {
num = Integer.parseInt(in.next()); // get input
} catch (NumberFormatException e) {
// invalid number
}
arr[i] = num;
}
for (int i = arr.length; i > 0; i--) {
double s = Math.sqrt(arr[i-1]);
System.out.println(s);
} // this is printing the square roots in reverse order, you may want to change
// that to avoid confusion
If you want to split the answer by white space characters (spaces and line breaks), try using the .split function present in Java. In your case, you would take the input received from the user as a String, then do this:
String[] inputVariables = string.split("\\s");
(note that \s represents all white space characters and "string" is your input received)
Now you have a String array of the input received from the user. Then you can use Integer.parseInt on each String to convert them from Strings to ints, and you now have your four integers ready to square-rootify.
you can try something like this
for (i = 0; i < arr.length; i++ ){
try{
String []nos = in.nextLine().split("\\s+");
if(nos.length > 0)
{
for(String no:nos)
arr[i] = Integer.parseInt(no);
}else{
arr[i] = Integer.parseInt(in.nextLine());
}
}catch(Exception e){
i--;
}
}
Related
I'm almost done with this activity, I just need to arrange them in columns and rows given the user's split size and I'm stuck with an output that prints only strings itself. This is my code so far.
Scanner lagoScan = new Scanner(System.in);
System.out.println("Enter String:");
String letters = lagoScan.next();
final int numInLetters = letters.length(); // converted string to number length
System.out.println("Enter Split Size:");
int splitSize = lagoScan.nextInt();
if (numInLetters % splitSize == 0) {
System.out.println("The Given String is: "+letters);
System.out.println("The Split String are:");
//My Split here
String []in_array;
in_array = letters.split(""); //Note this there is no delimiter
for(int k=0; k < in_array.length; k++){
System.out.print(" "+in_array[k]);
}
// Split ENdss
}
else {
System.out.println("Given input is not divisible by input size.");
}
}
This is the output that I'm trying to follow
Here's a possible solution:
for (int i = 1; i <= inArray.length; i++) {
// print the current char.
System.out.print(inArray[i - 1]);
// if it's over the split size then print a line break
// for split size = 3
// i = 1 - print the char, i = 2, print the char, i = 3, print the char + line break
if (i % splitSize == 0) {
System.out.println();
}
}
When I run the method below keep in mind ADFGVX will be printed to the left and over the top of the array when its displayed, just like a classic ADFGVX cypher.
static char [][] poly = new char[][]{
{'p','h','0','q','g','6'},
{'4','m','e','a','1','y'},
{'l','2','n','o','f','d'},
{'x','k','r','3','c','v'},
{'s','5','z','w','7','b'},
{'j','9','u','t','i','8'}};
I have written a method that displays a polybius square using a 2d array(array can be seen above) and what I want to do is pair what ever the user enters with the square, so if the user types OBJECT I want it to return FG VX XA DF GV XG.
Scanner console = new Scanner (System.in);
String phrase;
displayGrid();
System.out.println("");
System.out.print("Please enter a phrase you want to use\n");
phrase = console.nextLine();
console.close();
Does anyone here know how I would go about this? I was going to make a switch statement or something but I don't think that would work and even if it did it would be very long and inefficient.
You could just iterate over your array to get the position of the character you are looking for and than decode this position to the letter.
public static String[] cypherADFGVX(String phrase){
String[] output=new String[phrase.length()];
for (int i = 0; i < phrase.length(); i++) {
//optional for breaking
//squareIteration:
for (int j = 0; j < 6; j++) {
for (int k = 0; k < 6; k++) {
if(poly[j][k]==phrase.charAt(i)){
output[i]=new String(new char[]{switchChar(j),switchChar(k)});
//To stop the iteration over poly and take care of the next char
//break squareIteration;
}
}
}
}
return output;
}
public static char switchChar(int integer){
switch (integer) {
case 0:
return 'A';
case 1:
return 'D';
//and so on
}
}
If I left any questions just ask.
To answer your questions
Oh. I see. I made it a bit too complicated for java beginners.
An easier solution with just one String would be:
public static String cypherADFGVX(String phrase){
String output=new String[phrase.length()];
for (int i = 0; i < phrase.length(); i++) {
//optional for breaking
//squareIteration:
for (int j = 0; j < 6; j++) {
for (int k = 0; k < 6; k++) {
if(poly[j][k]==phrase.charAt(i)){
output=output+switchChar(j)+switchChar(k)+" ";
//To stop the iteration over poly and take care of the next char
//break squareIteration;
}
}
}
}
return output;
}
Now let me explain what my lines do.
String[] output=new String[phrase.length()];
creates a new array of string where each string are the two capital letters.
It would look like ["FG","VX",...]. It is easier for futher processing in my opinion.
if(poly[j][k]==phrase.charAt(i))
Compares the character at position jk in your square with the i-th character of the input String.
output[i]=new String(new char[]{switchChar(j),switchChar(k)});
I use the String constructor that takes a char-array as argument.
new char[]{'a','b'}
creates the array and fills it with the elements listed in the brackets.
Sure you can use the switch to set the value of a variable and than return that variable.
https://drive.google.com/a/navasotaisd.org/file/d/0B3eMFMufj6uVaVNpR0JYNnV4OTQ/view
Okay, so the problem above asks that you read in a file with a message and, using and x, y coordinate system, find the characters being read in and print out the character of that index value. I honestly have tried multiple solutions with making and array of arraylists, a arraylist of arraylists and many other failed data structures. All I need to know, is how would go about reading in the message so that I can search for it?
File f = new File("cipher.in");
f.createNewFile();
Scanner scan = new Scanner(f);
int numOfLines = scan.nextInt();
scan.nextLine();
ArrayList<Character> list = new ArrayList();
String code = "";
for (int i = 0; i < numOfLines; i++) {
code = scan.nextLine();
for (int j = 0; j < code.length(); j++) {
list.add(code.charAt(j));
}
}
int index = 0;
char[][] matrix = new char[(int)(list.size())][(int)(list.size())];
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
matrix[r][c] = list.get(index);
index++;
if(index>=list.size())
index--;
}
}
Sorry if this problem is a bit long. It's for my class I need to turn this problem in to be able to make a 100 in the gradebook. I'm just utterly stuck and frustrated.
Try to use a hash table to store the data. You will be able to search for it later on.
The key fits quite nicely into a two-dimensional charcter array (char[][]). I would consider reading the first line (which specifies the number of lines on the key (rows of the array), and then construct the array. You have a constraint defined that a row can be no longer than 100 characters long so you can now define the complete "map".
After that i would read each line of the key, use an operator as charAt(index) and fill the map.
From there you have a very convenient structure to lookup the messages in the next part of the assignment.
Try this out , this is you code with changes and comments so that you can understand the changes and the way this code works based on the instruction in your link, I did not try to compile it, so if it has any compilation errors try to fix them. I kept your code and commented out the items that are not needed so that you can look at the differences,
File f = new File("cipher.in");
//f.createNewFile(); //* you are overwriting the file here
Scanner scan = new Scanner(f);
int numOfLines = scan.nextInt();
//str = scan.nextLine(); //* you just skipped one line from the numOfLInes
//ArrayList<Character> list = new ArrayList(); //* this does not help, you need to index into the line number, char index
TreeMap charMap = new TreeMap(); //* use this to map the line number to a char array
String code = "";
for (int i = 0; i < numOfLines; i++) {
strubg code = scan.nextLine();
charMap.put(i, code.toCharArray()); //* map the line number with the char array of each line
//for (int j = 0; j < code.length(); j++) {
// list.add(code.charAt(j));
//}
}
int numOfMessageLines = scan.nextInt(); //* get the number of message lines next
for (int i = 0; i < numOfMessageLines; i++) {
string str = scan.nextLine();
string[] pairs = str.split(" "); //* each line has several key pairs for line number char number seprated by spaces
ArrayList<char> list = new ArrayList(); //* this does not help, you need to index into the line number, char index
for(int j=0; j<pairs.length; j++)
{
string[] st = pairs[j].trim().split(","); //* example 2,13 indicate line 2 character 13 non zero indexed
int lineNum = Integer.parse(st[0]) - 1; //* zero indexed line number since we stored the lines in zero index map
int charNum = Integer.parse(st[1]) - 1; //* zero indexed char number since we stored the char array in zero indexed array
char[] chars = charMap.get(lineNum); //* get the char array for this line number
char c = chars[charNum]; //* get the character for the first message
list.add(c);
}
String message = new String(list.toArray()); //* construct the message from the char array
System.out.println(message);
}
//int index = 0;
//char[][] matrix = new char[(int)(list.size())][(int)(list.size())];
//for (int r = 0; r < matrix.length; r++) {
// for (int c = 0; c < matrix[r].length; c++) {
// matrix[r][c] = list.get(index);
// index++;
// if(index>=list.size())
// index--;
// }
//}
Hello I am having trouble implementing this function
Function:
Decompress the String s. Character in the string is preceded by a number. The number tells you how many times to repeat the letter. return a new string.
"3d1v0m" becomes "dddv"
I realize my code is incorrect thus far. I am unsure on how to fix it.
My code thus far is :
int start = 0;
for(int j = 0; j < s.length(); j++){
if (s.isDigit(charAt(s.indexOf(j)) == true){
Integer.parseInt(s.substring(0, s.index(j))
Assuming the input is in correct format, the following can be a simple code using for loop. Of course this is not a stylish code and you may write more concise and functional style code using Commons Lang or Guava.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < s.length(); i += 2) {
final int n = Character.getNumericValue(s.charAt(i));
for (int j = 0; j < n; j++) {
builder.append(s.charAt(i + 1));
}
}
System.out.println(builder.toString());
Here is a solution you may like to use that uses Regex:
String query = "3d1v0m";
StringBuilder result = new StringBuilder();
String[] digitsA = query.split("\\D+");
String[] letterA = query.split("[0-9]+");
for (int arrIndex = 0; arrIndex < digitsA.length; arrIndex++)
{
for (int count = 0; count < Integer.parseInt(digitsA[arrIndex]); count++)
{
result.append(letterA[arrIndex + 1]);
}
}
System.out.println(result);
Output
dddv
This solution is scalable to support more than 1 digit numbers and more than 1 letter patterns.
i.e.
Input
3vs1a10m
Output
vsvsvsammmmmmmmmm
Though Nami's answer is terse and good. I'm still adding my solution for variety, built as a static method, which does not use a nested For loop, instead, it uses a While loop. And, it requires that the input string has even number of characters and every odd positioned character in the compressed string is a number.
public static String decompress_string(String compressed_string)
{
String decompressed_string = "";
for(int i=0; i<compressed_string.length(); i = i+2) //Skip by 2 characters in the compressed string
{
if(compressed_string.substring(i, i+1).matches("\\d")) //Check for a number at odd positions
{
int reps = Integer.parseInt(compressed_string.substring(i, i+1)); //Take the first number
String character = compressed_string.substring(i+1, i+2); //Take the next character in sequence
int count = 1;
while(count<=reps)//check if at least one repetition is required
{
decompressed_string = decompressed_string + character; //append the character to end of string
count++;
};
}
else
{
//In case the first character of the code pair is not a number
//Or when the string has uneven number of characters
return("Incorrect compressed string!!");
}
}
return decompressed_string;
}
I've been working on a Java lab that wants us to have the user enter two digits up to 50 digits long and add them together. I've successfully been able to complete everything except for when the two arrays have a different length. I've been toying around with the code for a while, but I keep coming up short. Can anyone look at the code for this and have any suggestions? Thanks!
int[] number1 = new int[input1.length()];
int[] number2 = new int[input2.length()];
int[] answer = new int[input1.length()];
if(number1.length > number2.length){
number2 = new int[number1.length];
for(int i = 0; i < number2.length - number1.length; i++){
number2[i] = 0;
}
}
if(number2.length > number1.length){
number1 = new int[number2.length];
for(int i = 0; i < number1.length - number2.length; i++){
number1[i] = 0;
}
}
Whenever I add, say 120 and 12, it says there's an Array out of bounds error.
First thing you need to do is get the numbers into an int array. Do that by Splitting string to char array. Then convert to int array. Then add.
String input1 = scanner.nextLine().trim(); <-- get input as String
String input2 = scanner.nextLine().trim();
char[] array1 = input1.toCharArray(); <-- split to char array
char[] array2 = input2.toCharArray();
// convert to int array
int[] intArray1 = new int[array1.length]; <-- declare int array
int[] intArray2 = new int[array2.length];
for (int i = 0; i < array1.length; i++){
intArray1[i] = Integer.parseInt(String.valueOf(array1[i])); <-- convert to int
}
for (int i = 0; i < array2.legnth; i++){
intArray2[i] = Integer.parseInt(String.valueOf(array2[i]));
}
// check which one is larger and add to that one
if (intArray1.length > intArray2.length){
for (int i = 0; i < intArray2.length; i++){
intArray1[i] += intArray2[i]; <-- add values
}
System.out.println(Arrays.toString(intArray1); <-- print largest
} else {
for (int i = 0; i < intArray1.length; i++){
intArray2[i] += intArray1[i];
}
System.out.println(Arrays.toString(intArray2);
}
If you want to get the number representation printed instead of an array, instead of the System.out.println(), use this
StringBuilder sb = new StringBuilder();
for (int i : intArray1){
sb.append(String.valueOf(i));
}
System.out.println(sb.toString());
So 123 and 12 will print out 233
My understanding of your code is, you try to pre-append (push from head) 0s to the shorter array. Look at the first if-block. The length of number1 is larger than what of number2. Thus, number2.length - number1.length is negtive. Then, in the for loop, i < number2.length - number1.length is always ture. (I am not familiar with java. I guess array's length is an integer.) And you still have to copy the rest of array.
The correct code should be,
if(number1.length > number2.length) {
int[] number3 = new int[number1.length];
for(int i = 0; i < number1.length - number2.length; ++i) {
number3[i] = 0;
}
for(int i = 0; i < number2.length; ++i) {
number3[i + number1.length - number2.length] = number2[i];
}
number2 = number3;
}
BTW, the second if-block should be changed in a similar way. Perhaps, java provides an API link insert(0, 0) for array object. It will be easier to implement.