Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
As per my code, I ask user to enter a string. I want to convert it in 2 dimensional array of NXN size. Although N can be variable but for now considering it to be 3. I want to format the string inputted by the user as below.
For input string :
⌐Φ┼╨¡¬╨┴╨
I want to arrange like this way.
[⌐ Φ ┼
╨ ¡ ¬
╨ ┴ ╨]
Below is the code.
public static void main(String[] args) {
Map<Character,Character> inputMap = new HashMap<Character,Character>();
inputMap.put('a', '|');
inputMap.put('b', 'β');
inputMap.put('c', '⌐');
inputMap.put('d', '≡');
inputMap.put('e', '╨');
inputMap.put('f', 'Ω');
inputMap.put('g', '╟');
inputMap.put('h', '¬');
inputMap.put('i', '↔');
inputMap.put('j', 'Σ');
inputMap.put('k', '¥');
inputMap.put('l', '╒');
inputMap.put('m', '┼');
inputMap.put('n', '«');
inputMap.put('o', 'Φ');
inputMap.put('p', '╔');
inputMap.put('q', 'Є');
inputMap.put('r', '┴');
inputMap.put('s', 'δ');
inputMap.put('t', '╬');
inputMap.put('u', '┤');
inputMap.put('v', 'θ');
inputMap.put('w', '●');
inputMap.put('x', '◙');
inputMap.put('y', 'σ');
inputMap.put('z', '∞');
inputMap.put(' ', '¡');
Scanner ins = new Scanner(System.in);
System.out.println("Enter a String");
String myData = ins.nextLine();
char arr[]=new char[myData.length()];
arr=myData.toCharArray();
for(int i = 0; i < arr.length; i++) {
arr[i]=inputMap.get(arr[i]);
System.out.println( arr[i]);
}
}
how can I do this?
There is a method in String.java toCharArray(). This will give you single dimensional array. Now iterate it using simple for loop. In each iteration you can print the character and at each Nth iteration print a new line.
public static void main(String[] args) {
Scanner ins = new Scanner(System.in);
System.out.println("Enter a String");
String myData = ins.nextLine();
ins.close();
char [] oneDArray = myData.toCharArray();
int N = 3; // or you can set it by asking the user
char[][] twoDArray = new char[N][N];
int size = oneDArray.length;
boolean isEndReached = false;
for(int row = 0; row < N ; row++ ){
for(int col = 0; col < N; col++){
int index = row*N + col;
if(index >= size){
isEndReached = true;
break;
}
twoDArray[row][col] = oneDArray[index];
}
if(isEndReached){
break;
}
}
//printing...
System.out.print("[");
for(int row = 0; row < N ; row++ ){
for(int col = 0; col < N; col++){
System.out.print(twoDArray[row][col]+" ");
}
System.out.println();
}
System.out.print("]");
}
Hope this helps...
You can print blank line at certain interval, e.g.:
String[] array = new String[10];//your map
int n = 5;
int count = 0;
for(String element : array){
count++;
System.out.print(element + " ");
if(count%n == 0){
System.out.println();
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
If a have for example:
nem
ava
ma
Output would be:
nam eva ma
This is My code:
class Message {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("String without white spaces:");
String str = s.next();
str.replaceAll("\\s+", "");
if (str.length() <= 81) {
System.out.println("in range");
} else {
System.out.println("out of range");
}
gridStr(str);
}
static void gridStr(String str) {
int l = str.length();
int k = 0, row, column;
row = (int) Math.floor(Math.sqrt(l));
column = (int) Math.ceil(Math.sqrt(l));
if (row * column < l) {
row = column;
}
char s[][] = new char[row][column];
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (k < str.length())
s[i][j] = str.charAt(k);
k++;
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (s[i][j] == 0) {
break;
}
System.out.print(s[i][j]);
}
System.out.println("");
}
}
}
This shows only answers for first element of string but not all code for matrix.
You could do it like this using streams.
split the string on spaces to create an array.
stream a large number of ints for string indices
for each of those, stream the array
if the index is less than the length of the streamed string, get the character at that index. Otherwise, return an empty string.
join into a string.
and continue doing so until the returned string is empty.
String str = "nem ava ma";
String[] strs = str.split("\\s+");
String[] result = Stream.iterate(0, i->++i)
.map(i -> Arrays.stream(strs)
.map(s -> i < s.length() ?
s.substring(i, i + 1) : "")
.collect(Collectors.joining()))
.takeWhile(s -> !s.isEmpty()).toArray(String[]::new);
for (String r : result) {
System.out.println(r);
}
prints
nam
eva
ma
And here is one way of doing it using for loops
// create an array of the words as before.
String str = "nem ava ma";
String[] strs = str.split("\\s+");
// generate an unlimited number of potential columns
for (int col = 0;; col++) {
// allocate a StringBuilder in which to build the string
StringBuilder sb = new StringBuilder();
// iterate thru the array of strings and append the
// character at the current column. If the col is equal to the string
// length, don't append anything.
for (String s :strs) {
if (col < s.length()) {
sb.append(s.charAt(col));
}
}
// if the stringBuilder is empty, then no more strings
// can be built so break out of the loop
if (sb.isEmpty()) {
break;
}
// otherwise, print the string.
System.out.println(sb.toString());
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How could an user input their numbers, for example : "122113333443" and I needed to output "3333".
If they again input something like "1224" I then needed to output "22".
How would this be possible if I don't know which numbers they are going to input and how the code would look like?
So far I only have the beginning, which shows input output error if the input aren't numbers.
int k;
Scanner sc = new Scanner(System.in);
System.out.println("input string:");
if (sc.hasNextInt())
k = sc.nextInt();
else {
System.out.println("input-output error");
sc.close();
return;
}
You can use a variable (StringBuilder longest in the code given below) to keep track of the longest sequence of characters having the same characters.
Iterate all characters of the string and keep appending the characters to a StringBuilder (StringBuilder sb in the code given below) until a different character is found. When this happens, reset the sb.
After each append to the sb, check if its length has become bigger than that of longest. If yes, transfer the content of the StringBuilder to longest.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input string: ");
String input = sc.nextLine();
System.out.println(getLongest(input));
}
static String getLongest(String str) {
StringBuilder sb = new StringBuilder();
StringBuilder longest = new StringBuilder();
char current = 0;
// Process all but the last character of str
for (int i = 0; i < str.length() - 1; i++) {
current = str.charAt(i);
sb.append(current);
if (sb.length() > longest.length()) {
longest = new StringBuilder(sb);
}
if (current != str.charAt(i + 1)) {
sb = new StringBuilder();
}
}
// Process the last character of str
sb.append(str.charAt(str.length() - 1));
if (sb.length() > longest.length()) {
longest = new StringBuilder(sb);
}
return longest.toString();
}
}
A sample run:
Input string: 122113333443
3333
Another sample run:
Input string: 1224
22
This is Java not JavaScript, wrong tag. However, heres my shot. I am not that good with java but anyway:
public String findMostCommon(int inp) {
int[] occuranceTable = new int[9];
for (int i = 0; i < occuranceTable.length; i++) {
occuranceTable[i] = 0;
}
// Convert input int to Array of digits
String temp = Integer.toString(inp);
int[] digits = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
digits[i] = temp.charAt(i) - '0';
}
// Get Occurances of each digit
for(int digit : digits) {
occuranceTable[digit]++;
}
// Find most frequent digit
int max = -1;
for (int i = 0; i < occuranceTable.length; i++) {
max = occuranceTable[i] > max ? i : max;
}
// Make result string
String result = "";
for (int i = 0; i < occuranceTable[max]; i++)
result += String.valueOf(max);
return result;
}
I am trying to use user inputted N lines of N characters to do some operations with. But first I need to know N and another int being inputted. When I define N and the other integer K and then write 5 lines (in this case) of 5 characters each the program runs well. But when I use the represented String a (which I then would split into 2 ints, N and K, not shown here to not complicate things), an error occurs. Even if I now input 6 lines, being the 5 last of 5 characters each, the program gives an error of no line found for the multi function. I don't understand what's the problem, and if I remove the string a and just define N and K the program runs well. What's more surprising, the program runs if I use an interactive console instead of text input and write the terms one by one.
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
int N = 5;
int K = 5;
String [][] multi = vetor(N);
I've tried many things, but I can't make sense of this. I didn't find any similar questions, but feel free to redirect me to an explanation.
Edit: This is a similar program one can run (with a possible input down (K<= N)) :
import java.util.Scanner;
import java.util.Arrays;
public class Main {
static int[] numerificar() {
Scanner myObj = new Scanner(System.in);
String Input = myObj.nextLine();
String[] Inputs = Input.split(" ", 0);
int size = Inputs.length;
int [] a = new int [size];
for(int i=0; i<size; i++) {
a[i] = Integer.parseInt(Inputs[i]);}
return a;
}
static String [][] vetor (int N) {
Scanner scan = new Scanner(System.in);
String[][] multi = new String [N][N];
for (int i = 0 ; i<N ; i++){
String forest = scan.nextLine();
String[] chars = forest.split("");
for (int k=0; k<N; k++){
multi[i][k]= chars [k];
}
}
return multi;
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int[] a = numerificar();
int N = a[0];
int K = a[1];
int cadeira = 0;
String [][] multi = vetor(N);
for (int i = 0 ; i<N ; i++){
if (cadeira == 1) {
break;
}
for (int k=0; k<N-K+1; k++){
if (cadeira == 1) {
break;
}else if( multi[i][k].equals(".")){
for (int j=0; j<K; j++){
if(multi[i][k+j].equals( "#")){
k+=j;
break;
} else if (j == K-1) {
cadeira = 1;
}
}
}
}
}
System.out.println(cadeira);
}
}
5 3
.#.##
#####
##...
###..
#####
The output should be 1 in this case.
The problem is you are creating more than one Scanner that reads from System.in. When data is readily available, a Scanner object can read more data than you ask from it. The first Scanner, in the numerificar() method, reads more than the first line, and those lines are not available to the second Scanner, in the vetor() method.
Solution: use just one Scanner object in the whole program.
public class Main {
static Scanner globalScanner = new Scanner(System.in);
static int[] numerificar() {
String Input = globalScanner.nextLine();
String[] Inputs = Input.split(" ", 0);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My target is to reverse the string without changing the postion of the words, I want to print "tesT eht tcudorp"
public class roughWork {
public static void main(String[] args) {
String str = "Test the product";
String arr[] = str.split(" ");
for (int i = 0; i < arr.length; i++) {
for (int j = arr[i].length() - 1; j >= 0; j--) {
System.out.print(arr[j] + " ");
}
}
}
}
Your problem is that you're asking it to print the whole string repeatedly in this line: System.out.print(arr[j]+" ");. Changing that to print only an individual character will fix it:
public class roughWork {
public static void main(String[] args) {
String str= "Test the product";
String arr[]=str.split(" ");
for(int i=0;i<arr.length;i++)
{
for(int j=arr[i].length()-1;j>=0;j--)
{
System.out.print(arr[i].charAt(j));
}
System.out.print(" ");
}
}
}
The second print adds the space between each words after it has output all that words characters.
You are almost there just use charAt and print arr[i].charAt(j)
String str = "Test the product";
String arr[] = str.split(" ");
for (int i = 0; i < arr.length; i++) {
for (int j = arr[i].length() - 1; j >= 0; j--) {
System.out.print(arr[i].charAt(j));
}
System.out.print(" ");
}
Demo
class reverse {
public static void main(String[] args) {
String s = "Hello India";
String[] ch = s.split(" ");
for (String chr : ch) {
String rev = "";
for (int i = chr.length() - 1; i >= 0; i--) {
rev = rev + chr.charAt(i);
}
System.out.print(rev + " ");
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am having trouble with "//Clinton's delegates in order from highest to lowest". I realize that it's currently in ascending order (I was more familiar with this), but it still isn't looping enough times to even do the ascending order properly. I would like for the third column to be in descending order --> Integer.parseInt(primary[row][2]).
import java.io.*;
public static void main(String[] args) throws IOException
{
//Read text file
FileReader fr = new FileReader("primary1.txt");
BufferedReader br = new BufferedReader(fr);
//2D array
String[][] primary = new String[44][5];
//Section break
System.out.println("1. The file contents are:\n");
//Add column titles
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");
//Set delimiter as "/"
String line;
int i=0;
while((line=br.readLine())!=null){
primary[i]=line.split("/");
i++;
}
//Print text file
for(int row=0; row<primary.length; row++){
for(int col=0; col<primary[row].length; col++){
//Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
//Newline
System.out.println("");
}
//Clinton's delegates in order from highest to lowest
int temp=0;
for(int row=0; row<primary.length-1; row++){
//Parse Integer
int delC = Integer.parseInt(primary[row][2]);
int delC1 = Integer.parseInt(primary[row+1][2]);
if(delC > delC1){
temp=delC1;
delC1=delC;
delC=temp;
}
System.out.println(temp);
}
}
Try this:
public static void main(String[] args) throws IOException {
//Read text file
FileReader fr = new FileReader("primary1.txt");
BufferedReader br = new BufferedReader(fr);
//2D array
String[][] primary = new String[44][5];
//Section break
System.out.println("1. The file contents are:\n");
//Add column titles
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");
//Set delimiter as "/"
String line;
int i=0;
while((line=br.readLine())!=null){
primary[i]=line.split("/");
i++;
}
//Print text file
for(int row=0; row<primary.length; row++){
for(int col=0; col<primary[row].length; col++){
//Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
//Newline
System.out.println();
}
//Clinton's delegates in order from highest to lowest
for(int row=0; row<primary.length-1; row++){
for(int row1=row+1; row1<primary.length; row1++) {
//Parse Integer
int delC = Integer.parseInt(primary[row][2]);
int delC1 = Integer.parseInt(primary[row1][2]);
if(delC < delC1){
String[]tmpprimary = primary[row];
primary[row] = primary[row1];
primary[row1] = tmpprimary;
}
}
}
System.out.println("\n**************************** Order Descending *******************************");
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");
for(int row=0; row<primary.length; row++){
for(int col=0; col<primary[row].length; col++){
//Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
//Newline
System.out.println();
}
}
I think your code looks like trying to do bubble sort. If that is what you are trying to do then you need to have 2 for loops to iterate the contents and swap them. Since you are using String array hence the array elements needs to be swapped. not just numbers in the array for display. See the following modified code.
I see you have tagged with selection sort. Let me know if you need that. Bubble sort below because your looked like doing that.
public static void main(String[] args) throws IOException {
// Read text file
FileReader fr = new FileReader("primary1.txt");
BufferedReader br = new BufferedReader(fr);
// 2D array
String[][] primary = new String[44][5];
// Section break
System.out.println("1. The file contents are:\n");
// Add column titles
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");
// Set delimiter as "/"
String line;
int i = 0;
while ((line = br.readLine()) != null) {
primary[i] = line.split("/");
i++;
}
// Print text file
for (int row = 0; row < primary.length; row++) {
for (int col = 0; col < primary[row].length; col++) {
// Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
// Newline
System.out.println("");
}
// Clinton's delegates in order from highest to lowest
int temp = 0;
// bubble sort
for (int row = 0; row < primary.length - 1; row++) {
for (int k = row + 1; k < primary.length; k++) {
// Parse Integer
int delC = Integer.parseInt(primary[row][2]);
int delC1 = Integer.parseInt(primary[k][2]);
int delO = Integer.parseInt(primary[row][4]);
if (delC >= delC1) {
// swap contents
swap(primary, row, k);
temp = delC1;
delC1 = delC;
delC = temp;
}
}
// System.out.println(temp);
}
// Print output
for (int row = 0; row < primary.length; row++) {
System.out.println(primary[row][2]);
}
}
private static void swap(String[][] primary, int row, int k) {
String[] temp = primary[k];
primary[k] = primary[row];
primary[row] = temp;
}