I have an array alpha={"A","B","C”} and in console if I enter 0 it should display A(position of A = 0) in same way 1=B and 2=C. I have to achieve this in Java.
I have a similar code, but it returns different output. Can someone suggest me code to get output as in my question.
public class Position{
public static void main(String args[]){
String Alpha = ("abcd");
for (int i = 0 ; i<Alpha .length() ; i++)
if (Alpha .charAt(i) == 'd')
System.out.println(i);
}
}
I have an array alpha={"A","B","C”} and in console if i enter 0 it should display A(position of A = 0)
String[] alpha={"A","B","C"} ;
Then if you want to access element at 0 simply you could do
alpha[0] gives you "A"
String result = alpha[0];
public static void main(String args[]){
String[] alpha= {"A","B","C","D"};
for (int i = 0 ; i < alpha.length ; i++){
if(Integer.valueOf(args[0]) == i){
System.out.println(alpha[i] + " is at position " +i);
}
}
}
You can enter the position in the arguments when you run your java program.
public class Position{
public static void main(String args[]){
String[] alpha={"A","B","C”} ;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //read reading from console
String entered = br.readLine();
int index = Integer.parseInt(entered);
System.out.println(alpha[index]); // This will print out "A" if you enter 0
}
}
Related
I was assigned to do a program where the user will input two integers and the program will be able to display the same numbers in the two integers in descending form
for example
1st input: 1122334455
2nd input: 1234567
The output will be: 5 4 3 2 1
here is the code that I tried but didn't work since I can't seem to store values in the array or maybe my logic is wrong, any kind of help will be appreciated thanks!
import java.util.*;
public class Main {
public static void main (String[]args) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
String aa= a + "";
int b = input.nextInt();
String bb = b + "";
int[] cars = new int[aa.length()];
if ( aa.length() < bb.length() )
{
for ( int x = 0; x < aa.length(); x++ )
{
for (int y = 0 ; y < bb.length() ; y++ )
{
if ( aa.charAt(x) == bb.charAt(y) )
cars[x] = aa.charAt(x);
}
}
for ( int i = 0 ; i < cars.length; i++ )
{
if ( cars[i] != 0 )
System.out.println(cars[i]);
else {
}
}
}
}
}
Well you have too many for cicles and this is pretty simple, first convert any input to char array and then iterate over it checking if every value is contained in the other input, if it is then add it to a new list which will be your results and finally sort that list.
String aa="1122334455";
String bb="1234567";
List<Integer> result = new ArrayList();
char[] aa_arr = aa.toCharArray();
for(char aa_ : aa_arr){
if(bb.contains(aa_+"") && !result.contains(Integer.parseInt(aa_+""))){
result.add(Integer.parseInt(aa_+""));
}
}
Collections.sort(result, Collections.reverseOrder());
System.out.println(result);
Result:
[5, 4, 3, 2, 1]
I don't see anything obviously wrong. You have not included what error you are getting, or the unexpected output you are getting. Maybe if you optimize a little bit.
import java.util.*;
public class Main {
public static void main (String[]args){
Scanner input = new Scanner(System.in);
int a = input.nextInt();
String aa= a + "";
int b = input.nextInt();
String bb = b + "";
StringBuilder output = new StringBuilder("[");
String delimiter = "";
for (int x = 9 ; x >= 0 ; x++) {
String compare = Integer.toString(x);
if (aa.indexOf(compare) != -1 && bb.indexOf(compare) != -1) {
output .append(delimiter);
output .append(compare);
delimiter = ", ";
}
}
output.append("]");
System.out.println(output .toString());
}
}
I was solving a problem to reduce the form to it's non-reducible form. This was the question.
Shil has a string S , consisting of N lowercase English letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation.
Shil wants to reduce S as much as possible. To do this, he will repeat the above operation as many times as it can be performed. Help Shil out by finding and printing 's non-reducible form!
If the final string is empty, print Empty String; otherwise, print the final non-reducible string.
Sample Input 0
aaabccddd
Sample Output 0
abd
Sample Input 1
baab
Sample Output 1
Empty String
Sample Input 2
aa
Sample Output 2
Empty String
Explanation
Sample Case 0:
Shil can perform the following sequence of operations to get the final string:
Thus, we print .
Sample Case 1:
Shil can perform the following sequence of operations to get the final string:
aaabccddd -> abccddd
abccddd -> abddd
abddd -> abd
Thus we print abd
Sample case 1:
baab -> bb
bb -> Empty String.
And what I have done till now is try to solve it through StringBuilder in Java.But some of testcases pass while other's don't and I can't find out what's the error?
Here is the code that I have tried so far.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder(scan.nextLine());
for(int i = 0; i < sb.length()-1; i++)
{
if(sb.charAt(i) == sb.charAt(i+1))
sb.delete(i,i+2);
i = 0;
}
if(sb.length() == 0)
System.out.println("Empty String");
else
System.out.println(sb.toString());
}
}
Inputs like aaabccddd
and aa pass.But when the input is baab it fails.
You have to use a while loop. Problem with your code is that it just iterate through the code just one time. In first iteration though your input "baab" becomes "bb", then it checks 2nd b and try to find a "b" in i+1 (which does not exist). change your for loop to a while loop as below.
import java.util.Scanner;
public class Solution{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder(scan.nextLine());
int c=0;
while(c< sb.length()-1){
if(sb.charAt(c) == sb.charAt(c+1)){
sb.delete(c,c+2);
c=0;
}
else{
c+=1;
}
}
if(sb.length() == 0)
System.out.println("Empty String");
else
System.out.println(sb.toString());
}
}
The problem is you just run loop through the string for one time.
For example:
String "baab", you just delete "aa" and finish the loop.
Solution: use recursion with a flag isNonReducible, loop until it give empty string or flag isNonReducible = true;
public class Solution {
public static StringBuilder checkReducible(StringBuilder sb) {
boolean isNonReducible = true;
for (int i = 0; i < sb.length() - 1; i++) {
if (sb.charAt(i) == sb.charAt(i + 1)) {
isNonReducible = false;
sb.delete(i, i + 2);
}
}
if (sb.length() == 0) {
return new StringBuilder("Empty String");
}
else {
if(!isNonReducible) {
sb = checkReducible(sb);
}
return sb;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder(scan.nextLine());
System.out.println(checkReducible(sb));
scan.close();
}
}
you can do with the help of lable try this,
public static void main(String[] args) {
boolean canReduce = true;
Scanner scan = new Scanner(System.in);
StringBuilder sb = new StringBuilder(scan.nextLine());
startPoint: while (sb.length() > 0 && canReduce) {
for (int i = 0; i < sb.length() - 1; i++) {
if (sb.charAt(i) == sb.charAt(i + 1)) {
sb.delete(i, i + 2);
canReduce=true;
continue startPoint;
}else{
canReduce=false;
}
}
}
if (sb.length() == 0) {
System.out.println("Empty String");
} else {
System.out.println(sb.toString());
}
}
Try this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder sb =new StringBuilder(in.nextLine());
for (int i=0; i<sb.length()-1; i++){
if(sb.charAt(i)==sb.charAt(i+1)){
sb.delete(i, i+2);
i=-1;
}
}
if(sb.length()==0){
System.out.println("Empty String");
}else{
System.out.println(sb);
}
}
Why in my program am i getting the output on one single line ? like abc123... I want my output to be printed on multiple lines, same as my inputs..
import java.util.Scanner;
class Reverse
{
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
}
System.out.println(reverse);
}
}
It should be for example like this :
input: abc
123
...
output:cba
321
...
Here's one way of doing it:
import java.util.Scanner;
class Reverse {
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
StringBuilder output = new StringBuilder();
while (kbd.hasNextLine())
{
original = kbd.nextLine();
StringBuilder sb = new StringBuilder(original);
output.append(sb.reverse().toString()).append("\n");
}
System.out.println(output.toString());
}
}
EDIT I noticed that in your question it seems that you only want to print the output after all input has been provided. I've modified the code from my original answer to do this.
import java.io.*;
import java.util.*;
public class reverseString {
public static void main(String[] args) {
String input="";
System.out.println("Enter the input string");
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
input = br.readLine();
char[] try1= input.toCharArray();
for (int i=try1.length-1;i>=0;i--)
System.out.print(try1[i]);
}
catch (IOException e) {
e.printStackTrace();
}
}}
try this:
package stackoverflow;
import java.util.Scanner;
class Reverse
{
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
//befor you add the reversed string add a jump line firs
if(reverse.length()>0)reverse=reverse+"\n";
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
}
System.out.println(reverse);
}
}
You should change this part
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
in
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
reverse = reverse + '\n';
This will add new line character.
I have one advice for you - use StringBuilder for new reverse string
Like this:
public static void main(String args[]) {
String original;
StringBuilder sbReverse = new StringBuilder();
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--) {
sbReverse.append(original.charAt(i));
}
sbReverse.append('\n');
}
System.out.println(sbReverse.toString());
}
The reason - in Java, strings are immutable.
That mean every time it execute reverse = reverse + original.charAt(i); it will be created a new string in memory.
You're getting the output in a single line because you are using System.out.printf(). Use System.out.println() instead.
PS: an easier way to reverse a string would be to use reverse() from StringBuilder.
reverse = new StringBuilder(original).reverse().toString();
Currently I have a method that asks user for an input string but only outputs the first 16 characters! The method is supposed to take in any length of string then output the characters in 4x4 blocks after it does the following: first row remains the same. Shift the second row one position to the left, then shifts the third row two positions to the left. Finally, shift the fourth row three positions to the left. As of now it will only output the first 4x4 block
Also I am not sure how I can change the method so it doesnt ask for user input
I would like it to use a given string like:
String text = shiftRows("WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO");
"WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO" is the given encrypted string I would like to use. but without asking for user input..I keep getting errors and incorrect outputs..please show how I might fix this
code I am using:
public class shiftRows {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String[] input= new String[4];
String[] output= new String[4];
System.out.println("Enter a String");
String inputStr = sc.next();
for (int i = 0, n = 0; i < 4; i++, n+=4) {
input[i] = inputStr.substring(0+n, 4+n);
}
// -
output[0] = input[0];
for(int i=1; i<4; i++)
{
output[i] = Shift(input[i],i);
}
for(int i=0; i<4; i++)
{
System.out.println(output[i]);
}
}
public static String Shift(String str, int shiftNum)
{
char[] out = new char[4];
if(shiftNum==1)
{
out[0]=str.charAt(1);
out[1]=str.charAt(2);
out[2]=str.charAt(3);
out[3]=str.charAt(0);
}
if(shiftNum==2)
{
out[0]=str.charAt(2);
out[1]=str.charAt(3);
out[2]=str.charAt(0);
out[3]=str.charAt(1);
}
if(shiftNum==3)
{
out[0]=str.charAt(3);
out[1]=str.charAt(0);
out[2]=str.charAt(1);
out[3]=str.charAt(2);
}
return new String(out);
}
}
Here's a good way to do it :
import java.util.Scanner;
public class shiftRows {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String inputStr = "WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO";
for (int i = 0 ; i < inputStr.length() ; i++){
System.out.print(inputStr.charAt(i));
if ((i + 1)%4 == 0) System.out.println();
}
}
}
If you want to stock it into a String, just concatenate at each loop and add a "\n" each time the if test is valid.
The array stores all the information, I feel like this program is really close to working. I know its not tidy, I'll clean it right after! Problem is at the bottom.
public class FoodFacts
{
private static BufferedReader textIn;
private static BufferedReader foodFacts;
static int numberOfLines = 0;
static int NUM_COL = 7;
static int NUM_ROW = 961;
static String [][] foodArray = new String[NUM_ROW][NUM_COL];
public static String fact;
// Make a random number to pull a line
static Random r = new Random();
public static void main(String[] args)
{
try
{
textIn = new BufferedReader(new InputStreamReader(System.in));
foodFacts= new BufferedReader(new FileReader("foodfacts.csv"));
Scanner factFile = new Scanner(foodFacts);
List<String> facts = new ArrayList<String>();
// System.out.println("Printing out your array!");
while ( factFile.hasNextLine()){
fact = factFile.nextLine();
StringTokenizer st2 = new StringTokenizer(fact, ",") ;
while (st2.hasMoreElements()){
for ( int j = 0; j < NUM_COL ; j++) {
foodArray [numberOfLines][j]= st2.nextToken();
//System.out.println("Foodarray at " + " " + numberOfLines + " is " +foodArray[numberOfLines][j]);
}
}
numberOfLines++;
}
System.out.println("Please type in the food you wish to know about.");
String request; //user input
request = textIn.readLine();
System.out.println ("You requested" + request);
Problem starts here!
for ( int i = 0; i < NUM_ROW ; i++)
{
if ( foodArray[i][0] == request)
for ( int j = 0 ; j < NUM_COL ; j++ )
System.out.println ( foodArray[i][j] ); //never prints anything
}
}
catch (IOException e)
{
System.out.println ("Error, problem reading text file!");
e.printStackTrace();
}
}
}
I'm trying to test it in the terminal where the foodArray[6][0] should match input All-Bran Cereal
In your last for loop, you are comparing your string using == operator in your if construct, which would give you incorrect result, because == compares the string reference, which would be different, as both the references point to different string objects.
Use equals method to compare string contents: -
if (foodArray[i][0].equals(request))
You should always use equals method with any object if you want to compare their content.
Check out this post: - How do I Compare strings in Java for more details.