how to create array table that include number and character - java

actually i want the table have the header on the top like no.room, doctor name and the time
as for time i want it to show like 8-10 p.m
for no room like 01 and for doctor name like Dr.Ali. but i don't know how because as i know char can only has single digit.
char[][] doctor = new char[5][3];
doctor[0][0] = '1';
doctor[0][1] = 'A';
doctor[0][2] = '8';
doctor[1][0] = '2';
doctor[1][1] = 'S';
doctor[1][2] = '1';
doctor[2][0] = '3';
doctor[2][1] = 'N';
doctor[2][2] = '3';
doctor[3][0] = '4';
doctor[3][1] = 'R';
doctor[3][2] = '1';
doctor[4][0] = '4';
doctor[4][1] = 'M';
doctor[4][2] = '3';
for (int i=0; i < 5 ; i++) {
for (int j=0; j < 3 ; j++) {
System.out.print( doctor[ i ][ j ] + " " );
}
System.out.println( "" );
}
}

You can't store more that one char in char type. Instead of using char type, you can use String for storing multiple char. This is the documentation for further reading.
Here is the code for using string for you.
class HelloWorld {
public static void main(String[] args) {
String [][] doctor = new String[5][3];
doctor[0][0] = "Room 1:";
doctor[0][1] = "Dr. Alex";
doctor[0][2] = "8-10 AM";
doctor[1][0] = "Room 2:";
doctor[1][1] = "Dr. Mina";
doctor[1][2] = "10-12 AM";
doctor[2][0] = "Room 3:";
doctor[2][1] = "Dr. Nadir";
doctor[2][2] = "3-4 PM";
doctor[3][0] = "Room 4:";
doctor[3][1] = "Dr. Rahul";
doctor[3][2] = "1-4 PM";
doctor[4][0] = "Room 5:";
doctor[4][1] = "Dr. Mahir";
doctor[4][2] = "3-6 PM";
for (int i=0; i < 5 ; i++) {
for (int j=0; j < 3 ; j++) {
System.out.print( doctor[ i ][ j ] + " " );
}
System.out.println( "" );
}
}
}

Related

logic to reverse the even position words [duplicate]

This question already has answers here:
Reverse every 2nd word of a sentence
(6 answers)
Closed 2 years ago.
Input: "I am a software tester"
Output: "I ma a erawtfos tester"
What I tried so far :
import java.util.Arrays;
public class ReverseEvenWords {
public static void main (String[]args)
{
String val = "";
String val1="";
String value="";
String test="I am a software tester";
String[] t = test.split(" ");
System.out.println (Arrays.toString(t));
int arr= t.length;
System.out.println (arr);
for (int i=0; i<t.length;i += 2)
{
for (int j=1; j<t.length;j += 2)
{
val1=(t[j]);
value =new StringBuilder(val1).reverse().toString();
System.out.print ("*"+value);
}
val=t[i];
String Test =val;
System.out.print (","+Test);
}
}
}
I am successfully able to reverse the even position string but I am not able to concatenate the position and but I am not able to get desired output.
Not sure why you need inner loops
String test="I am a software tester";
String[] t = test.split(" ");
String val = "";
for (int i = 0; i < t.length; i++) {
if (i % 2 == 1)
val = val + new StringBuilder(t[i]).reverse().toString() + " ";
else
val = val + t[i] + " ";
}
val = val.trim();
System.out.println(val);
Of course using a StringBuilder than a String for val would be better
In Java 8, it can be simplified, using the String.join() method:
String test = "I am a software tester";
String[] t = test.split(" ");
for (int i = 1; i < t.length; i += 2)
t[i] = new StringBuilder(t[i]).reverse().toString();
System.out.println(String.join(" ", t));
I think your loop should be like this
StringBuilder result = new StringBuilder();
for( int i = 0; i < t.length; i += 1 )
{
if( i % 2 != 0 )
{
char[] word = t[i].toCharArray();
String reverseWord = "";
for( int k = word.length; k > 0; k-- )
{
reverseWord += String.valueOf( word[k-1] );
}
result.append( reverseWord ).append( " " );
}
else
{
result.append( t[i] ).append( " " );
}
}
System.out.println( result.toString() );

How do i Reverse Capitalize And Separate Words By Line Using String In Java?

The input is: i love cake
The output needs to be: Cake Love I
But the actual result is: I Love Cake
What I've got:
import java.util.regex.Pattern;
public class yellow {
static String reverseWords(String str){
Pattern pattern = Pattern.compile("\\s");
String[] temp = pattern.split(str);
String result = "";
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1)
result = temp[i] + result;
else
result = " " + temp[i] + result;
}
return result;
}
public static void main(String[] args){
String source = "i love cake";
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print(res.toString());
}
}
What am I doing wrong?
for (String str : strArr) {
}
This loops forward. What you want is to loop backwards, or to place elements into the string backwards. I recommend you loop backwards and print as you go:
for (int i = strArr.length - 1; i >= 0; i--) {
char[] stringArray = strArr[i].trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
System.out.println(new String(stringArray));
}
Or, you could use that convenient reverseWords method that you never use anywhere... though looping backwards is faster. Probably.
[EDITED]
Call this for each line with string s, then print a line break (If you have multiple sentences & expect them in their own lines).
void reverseCamel(String s){
String[] ar = s.split("\\s+");
for(int i = ar.length - 1;i>=0;i--){
ar[i][0] = Character.toUpperCase(ar[i][0]);
System.out.print(ar[i] + " ");
}
}
Here is what i did.
public class Main {
public static void main(String[] args) {
reverse("I Love Cake");
}
public static void reverse( String string){
String[] word =string.split(" "); // split by spaces
int i = word.length-1;
while (i>=0){
// System.out.print(word[i].toUpperCase()+" ");//if you want in upper case
System.out.print(word[i]+" ");
i--;
}
}
}
First of all you have to reverse the String.
String[] words = source.split("\\s");
String reversedString = "";
for(int i = words.length -1; i>=0; i--){
reversedString += words[i] + " ";
}
Then, you know that the ASCII code of 'a' character is 97, 'A' is 65. To convert from lower case to capital you substract 32. All capitals are between 65 and 92. All small letters are between 97 and 124.
You want to capitalize only letters at the beginning of a word (preceded by a space or first letter).
String capitalCase = "";
for (int i = 0; i < reversedString.length(); i++) {
char c = reversedString.charAt(i);
if (c >= 97 && c <= 124) {
if (i == 0) c -= 32;
else if ((reversedString.charAt(i - 1) + "").equals(" ")) c -= 32;
}
capitalCase += c;
}
And here you go now System.out.println(capitalCase);
Overall, you will have the following code:
import java.util.Scanner;
public class yellow {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a string:");
String source = s.nextLine();
String[] words = source.split("\\s");
String reversedString = "";
for (int i = words.length - 1; i >= 0; i--) {
reversedString += words[i] + " ";
}
String capitalCase = "";
for (int i = 0; i < reversedString.length(); i++) {
char c = reversedString.charAt(i);
if (c >= 97 && c <= 124) {
if (i == 0) c -= 32;
else if ((reversedString.charAt(i - 1) + "").equals(" ")) c -= 32;
}
capitalCase += c;
}
System.out.println(capitalCase);
}
}
Output:
Enter a string:
i love cake
Cake Love I
Java 8 * Apache Commons Lang
public static String reverseWordsInString(String str) {
List<String> words = Pattern.compile("\\s+").splitAsStream(str)
.map(StringUtils::capitalize)
.collect(LinkedList::new, LinkedList::addFirst, (a, b) -> a.addAll(0, b));
return words.stream().collect(Collectors.joining(StringUtils.SPACE));
}
Java 8
public static String reverseWordsInString(String str) {
List<String> words = Pattern.compile("\\s+").splitAsStream(str)
.map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase())
.collect(LinkedList::new, LinkedList::addFirst, (a, b) -> a.addAll(0, b));
return words.stream().collect(Collectors.joining(" "));
}

how to inverse a string

I have this homework from the school, however Im not sure Im doing wrong the second array does not takes the values of the first one, can you help me please?
public static void main(String[] rpp) {
String[] word = new String[7];
word[0] = "D";
word[1] = "E";
word[2] = "N";
word[3] = "T";
word[4] = "I";
word[5] = "S";
word[6] = "T";
String[] inverseWord = new String[7];
inverseWord[0] = "";
inverseWord[1] = "";
inverseWord[2] = "";
inverseWord[3] = "";
inverseWord[4] = "";
inverseWord[5] = "";
for(int x = word.length;x <= 0;x--){
for(int y = 0;y <= word.length;y++){
inverseWord[y] = word[x];
}
}
System.out.print(Arrays.toString(inverseWord) + "\n");
}
Array-indexes start at 0. Which means that if the length is L, the last index in the array will be (L-1).
This means that instead of int x = word.length you need to write int x = word.length - 1 and instead of y <= word.length you need to write y < word.length or y <= word.length - 1.
Also, the condition in your outer loop should be x >= 0, not x <= 0.
You don't need two for loops
x should be greater than equal to 0 not less than
public static void main(String[] rpp) {
String[] word = new String[7];
word[0] = "D";
word[1] = "E";
word[2] = "N";
word[3] = "T";
word[4] = "I";
word[5] = "S";
word[6] = "T";
String[] inverseWord = new String[7];
inverseWord[0] = "";
inverseWord[1] = "";
inverseWord[2] = "";
inverseWord[3] = "";
inverseWord[4] = "";
inverseWord[5] = "";
for (int x = word.length - 1; x >= 0; x--) {
inverseWord[(word.length-1) - x] = word[x];
}
System.out.print(Arrays.toString(inverseWord) + "\n");
}
The condition on your outer for loop should be
x >= 0
Rewrite the for loop used for reversing using 2 variables.This is the simplest and most basic method.
for(int i=word.length-1,int j=0;i>=0,j>=0;i--,j++) //loop for reversing
{
inverseWord[j] = word[i];
}
for(int i=0;i>=0;i++) // for displaying the inverseword array
{
System.out.print(inverseWord[j];
}
You can use StringBuilder to append individual characters into a String. The String "DENTIST" can be broken up into characters of reverse order with the use of the charAt method in the String class and a for loop.
public class MainClass {
public static void main(String[] args) {
String word = "DENTIST";
StringBuilder inverseWord = new StringBuilder();
for (int i = word.length()-1; i >= 0; i--) {
inverseWord.append(word.charAt(i));
}
System.out.println(inverseWord);
}
}

How to generate a char randomly between 'X' and 'O'?

public static String generate(){
StringBuffer stringBuffer = new StringBuffer();
for(int i = 0; i < TicTacToeUtil.NUM_OF_SPACES + 1; i++){
for(int j = 0; j < TicTacToeUtil.NUM_OF_SPACES + 1; j++) {
stringBuffer.append("1");
}
stringBuffer.append(" ");
}
String finalString = stringBuffer.toString();
return finalString;
}
the code above is basically a game, NUM_OF_SPACES = 2, so the print will be "111 111 111",but , I want to replace all the 1s by either 'X' or 'O', which is randomly chosen between these two char. For example,"XOX XOO OOO", this is generated randomly. Thanks in advance.
You can use the Random#nextBoolean() method to get either true or false randomly. If the value is true, append 'X. Otherwise append 'O':
public static String generate()
{
Random r = new Random(); // create a Random object
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 2 + 1; i++) {
for (int j = 0; j < 2 + 1; j++) {
if (r.nextBoolean()) { // r.nextBoolean() return 'true' or 'false'
stringBuilder.append("X");
} else {
stringBuilder.append("O");
}
}
stringBuilder.append(" ");
}
String finalString = stringBuilder.toString();
return finalString; // return stringBuilder.toString();
}
You can use Random class to generate random numbers. Here I used nextBoolean() method from Random class to generate boolean value randomly.
public static String generate() {
StringBuilder stringBuilder = new StringBuilder();
Random r = new Random(); // create a Random object
for (int i = 0; i <TicTacToeUtil.NUM_OF_SPACES+ 1; i++) {
for (int j = 0; j <TicTacToeUtil.NUM_OF_SPACES + 1; j++) {
if (r.nextBoolean()) { // r.nextBoolean() return 'true' or 'false'
stringBuilder.append("X");
} else {
stringBuilder.append("O");
}
}
stringBuilder.append(" ");
}
String finalString = stringBuilder.toString();
return finalString;
}
I selected a value for TicTacToeUtil.NUM_OF_SPACES as 2 and the output was like follows,
XXX XOO XXX
I replaced StringBuffer with StringBuilder as it's common practice. ( I think StringBuffer class is replicated. )

How can I count the frequency of words without using Collections?

Results
0: Bear
1: Car
2: Bear
3: Cat
4: Car
5: Dog
6: Bear
---Frequency---
Bear : 1
Car : 1
null : 1
Cat : 1
null : 1
Dog : 1
null : 1
Code
import java.util.Arrays;
import java.util.StringTokenizer;
public class WordCount {
public static void main(String[] args) {
String text = "Bear Car Bear Cat Car Dog Bear";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String w;
int count = -1;
while (str.hasMoreTokens()) {
count++;
w = str.nextToken();
word[count] = w;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int z = 0; z < 7; z++) {
if (Arrays.asList(unique).contains(word[z])) {
measure[z] += 1;
System.out.println(unique[z] + " : " + measure[z]);
}
}
}
}
There are several problems in your current code:
You're using Collection interface explicitly. This is done every time you call Arrays#asList(...). You're not fulfilling with your main requirement.
You should maintain a counter for the elements in all your arrays. In this case, you could use the same variable to hold the size of both unique and measure arrays.
Your algorithm to fill unique is wrong. You should only add the word once (since it must be unique).
You should add the counter for measure only once per every String in unique array.
This code takes into account all these recommendations.
import java.util.StringTokenizer;
public class ThirteenthMain {
public static void main(String[] args) {
String text = "Bear Car Bear Cat Car Dog Bear";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
// reading the words to analyze
int wordSize = 0;
while (str.hasMoreTokens()) {
String w = str.nextToken();
word[wordSize] = w;
System.out.println(wordSize + ": " + word[wordSize]);
wordSize++;
}
System.out.println("---Frequency---");
// create unique words
int uniqueWordSize = 0;
for (int i = 0; i < wordSize; i++) {
boolean found = false;
for (int j = 0; j < uniqueWordSize; j++) {
if (word[i].equals(unique[j])) {
found = true;
break;
}
}
if (!found) {
unique[uniqueWordSize++] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int i = 0; i < uniqueWordSize; i++) {
for (int j = 0; j < wordSize; j++) {
if (unique[i].equals(word[j])) {
measure[i]++;
}
}
}
//printing results
for (int i = 0; i < uniqueWordSize; i++) {
System.out.println(unique[i] + " : " + measure[i]);
}
}
}
It prints:
0: Bear
1: Car
2: Bear
3: Cat
4: Car
5: Dog
6: Bear
---Frequency---
Bear : 3
Car : 2
Cat : 1
Dog : 1
Thanks to Luiggi for the inspiration . Here is my solution, realizing I had missed something very important. The nested loops. It is just a few lines of editing to my existing code. I would love you all to look at Luiggi's code as it is more verbose (hehe).
Result
0: Bear
1: Car
2: Bear
3: Cat
4: Car
5: Dog
6: Bear
---Frequency---
Bear : 3
Car : 2
Cat : 1
Dog : 1
import java.util.Arrays;
import java.util.StringTokenizer;
public class WordCount {
public static void main(String[] args) {
String text = "Bear Car Bear Cat Car Dog Bear";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String w;
int count = -1;
while (str.hasMoreTokens()) {
count++;
w = str.nextToken();
word[count] = w;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int z = 0; z < 7; z++) {
if (unique[z] != null) {
for (int j = 0; j < 7; j++) {
if (unique[z].equals(word[j])) {
measure[z] += 1;
}
}
System.out.println(unique[z] + " : " + measure[z]);
}
}
}
}
Another solution:
String text = "Bear Car Bear Cat Car Dog Bear";
String[] allWords = text.split(" ");
String[] foundWords = new String[allWords.length];
int[] foundCount = new int[allWords.length];
int foundIndex= 0;
for (String aWord : allWords) {
int j = 0;
for (; j < foundIndex; j++) {
if (foundWords[j].equals(aWord)) { //found
foundCount[j]++;
break;
}
}
if (j == foundIndex) { //word bot found in foundWords
foundWords[foundIndex] = aWord;
foundCount[foundIndex] = 1;
foundIndex++;
}
}
// Print result
for (int i = 0; i <foundIndex ; i++) {
System.out.println(foundWords[i] + " : " + foundCount[i]);
}
The result is:
Bear : 3
Car : 2
Cat : 1
Dog : 1

Categories