How to take a string and read it for an array - java

Im having trouble finding out how to read letters and turn them into numbers like -1 and 1.
Here's the context:
I'm working on a word problem for my Java programming class. I'm asked to create a program in Java that receives input of a number of "L"s or "R"s, short for left or right. For each L the program should go one spot back in an array, and for each R it should go one spot forward. Like if you start at 0, and get an input of RR, it should move to be at 2. Hopefully that makes sense, here's a diagram to hopefully clarify.
Now, what I don't understand is how to take the input from using Scanner(System.in) that gives me the L/R combination (eg. LLR) and turn that into the series of directions for the program (eg. -1,-1,+1). How do i specify that the input of an L is equal to going one space back? And vice versa for any R's input into the program?
Any tips would be greatly appreciated, thanks a ton
Edit: Heres the current code I have:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String args[] ) throws Exception {
int max = 100;
int min = 1;
int posMax = 10000;
int posMin = -10000;
boolean dataExists = false;
String inputData;
int initialPosition;
System.out.println("Insert sequence of commands (L and R)");
Scanner input = new Scanner(System.in);
inputData = input.nextLine();
System.out.println("Input starting position");
initialPosition = input.nextInt();
}
}
What it does it it defines the minimum and maximum commands (left and rights, which is 1-100) and the min and max positions which are -10000 and 10000. The next part would have been recieving the string of L's and R's and reading them to change the array but thats where im stuck.

The return value of Scanner.nextLine() is a String Object.
You can split up this String Object to a char array and check if the char is a 'L', 'R', or something else.
String cmds = "RRRRRLLLRLRLLRLRLLRLLRLRL";
char[] cCmds = cmds.toCharArray();
int pos = 39;
for (char c : cCmds) {
switch (c) {
case 'L' -> pos--;
case 'R' -> pos++;
default -> System.out.println("That was not an L or R...");
}
}
System.out.println("Position: " + pos);
Next step would now to add some conditions to check if the user input was too long or too short.
if (cmds.length() > MAX_INPUT || cmds.length() < MIN_INPUT) {
System.out.println("User input was too long or too short");
return;
}
The last step now is to check if you can move to another position each time if you want to move.
case 'L' -> { if (pos > POS_MIN) pos--; }
case 'R' -> { if (pos < POS_MAX) pos++; }
All in one, it would look like this (with Scanner):
import java.util.Scanner;
public class Solution {
static final int MIN_INPUT = 1;
static final int MAX_INPUT = 100;
static final int POS_MIN = -10000;
static final int POS_MAX = 10000;
public static void main(String[] args) {
System.out.println("Insert sequence of commands (L and R)");
Scanner input = new Scanner(System.in);
String cmds = input.nextLine();
if (cmds.length() > MAX_INPUT || cmds.length() < MIN_INPUT) {
System.out.println("User input was too long or short");
return;
}
System.out.println("Input starting position");
int pos = input.nextInt();
char[] cCmds = cmds.toCharArray();
for (char c : cCmds) {
switch (c) {
case 'L' -> { if (pos > POS_MIN) pos--; }
case 'R' -> { if (pos < POS_MAX) pos++; }
default -> System.out.println("That was not an L or R...");
}
}
System.out.println("Position: " + pos);
}
}
Keep in mind to catch the exception which the Scanner Object can cause.
(e.g. when scanner.nextInt() gets non Integer user input)
And also add a check if the user input for the initial position is in the given range.

Related

How to create an addition loop of random numbers?

After writing 1 on scanner I want a random dice number generated and after pressing 1 again I want another random number generated but now I want it added with previous number. I want to make a loop, I want to keep pressing 1 and keep adding random numbers till I reach a certain number.
Thank you.
import java.util.Random;
import java.util.Scanner;
public class dice {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int k = 0; k < 100; k++) {
Scanner scan = new Scanner(System.in);
int s = scan.nextInt();
System.out.println(s);
int previous = s;
if (s == 1) {
Random ran = new Random();
int n = ran.nextInt(6) + 1;
System.out.print(n);
int next;
while (true) {
next = scan.nextInt();
if (next == 1) {
System.out.println(previous);
}
previous = n + 10;
}
}
}
}
}
Define previous outside the for loop, and replace
int previous = s;
previous = n + 10;
with
previous += s;
previous += n + 10;
Scanner sc=new Scanner(System.in);
int sum=0;
for(;;)
{
if(sc.nextInt()==1)
{
int num = (int)(Math.random()*6); // using the pre-defined random function in java.lang.Math class
System.out.println("Dice Value: "+num);
sum+=num; // shorthand adding the number for each iteration
}
//if(sum>100)
// break;
//if statement to check if value of sum is greater/lesser than a specific number
}
System.out.println("Final Answer: "+sum)
Something like this might work (not yet tested): an infinite loop that can be terminated as per choice.
If you are looking for a way that the program works as soon as you physically press the '1' key on your keyboard, without having to press the enter key, something like a keyevent might work:
https://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html
Please do let me know if there are any errors or doubts :)

String having r & g separated by 5 characters! (Error:String index out of range error)

Given an input string,check whether the string has char 'r' & 'g' separated be exactly 5 characters.
For the following code, the error is String index out of range error.
Can't figure out whats wrong
My code for class having function that checks for pattern:
public class classb {
String s = new String();
public int match(String str){
int counter = 0;
int j;
s=str;
for(j=0;j<(s.length()-6);j++){
if(s.charAt(j)=='r' && s.charAt(j+6)=='g') {
counter=1;
break;
}
if(s.charAt(j)=='g' && s.charAt(j+6)=='r'){
counter=1;
break;
}
while(s.charAt(j)!='r' || s.charAt(j)!='g'){
if(j<(s.length()-6))
j++;
else
break;
}
}
return counter;
}
}
Main class:
import java.util.*;
public class classa
{
public static void main(String[] args)
{
String a = new String();
int count;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
a= sc.nextLine();
classb x = new classb();
count=x.match(a);
if(count==1)
System.out.println("Pattern found ");
else if(count==0)
System.out.println("Pattern not found ");
}
}
You can use a regex for this problem, r.{5}g.
The r says that the pattern starts with r, and the g says that it ends with g. The . means any character, and the {5} means that there are exactly 5 (in this case of any character).
And to implement this, you would just use the method String#matches("r.{5}g").
The root problem in your code is this:
for(j=0;j<s.length();j++){
while(s.charAt(j)!='r' || s.charAt(j)!='g')
j++;
You have a loop for j where you increase J - but inside that loop you increase j again. Below that, you use j+6 in an index and you haven't checked to see if j+6 is too long. So you're repeatedly modifying j and checking 6 characters out without ever checking to see if those are in bounds.
I'd start by stopping your for loop at s.length()-6. If an r or g sequence starts in those last spots it can't complete, so no need to check them - and then your j+6 logic will work and not blow up.

Trying to write a simple compiler in java (I am using notepad++)

My question is how would I write a simple compiler ,that is like the compilers used in fax machines, that would convert something like aaaavvvvvddddddddddd to 4a5vBd.
Also, I get to "Assume" that any string entered will not contain uppercase letters and no numbers, and that any string will contain less than 61 of any type of character so, I get to assume no one will put in 64 continues a's in my program.
This is as far as I gotten
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n;
char cn;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Hello, please enter a string");
word = scan.nextln();
if(n <= 61)
{
int n = ?;
cn = numChars.charAt(n);
}
}
}
I assume I need to use a loop, but I don't know what I should use to count the repeating letters and then tell how many letters of that type are in a row. Now I am only asking for advice and not so much for code, because I want to do it but, as a beginner my Java "Vocabulary" isn't very big right now.
Any advice/ tips would be greatly appreciated.
Sincerely,
Mr.Trips
Well I am back and it appears my code here likes to only print out 147. No matter what I type in I will always get 147. I have tried to hand trace all my variables, but when I do it I get exactly what I want, and I must have some error in my logic. Any thoughts?
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = 0;
int s = 0;
char a;
char b;
char c;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Please enter a string");
word = scan.nextLine();
while (n < word.length())
{
a = word.charAt(n);
b = a;
n = n ++;
a = word.charAt(n);
if (a == b)
{
s = (s + 1) ;
}
else if (a != b);
{
c = numChars.charAt(s);
System.out.print(b + c);
s = 0;
c = 0;
break;
}
}
}
}
Thank you again!
Since you don't want code this is logically how to do it. You are right you should loop through the string for each char. Store the last char in a variable and keep a counter variable. Compare current char to last char if it is equal then increment the counter. As soon as it is not equal to the last char then add counter + last char to result string and reset counter variable. Each iteration update last char variable.

Let user input integers until "X" is pressed Java

Basically what I have to do is read user input in (CUI) until the user presses x. Then display the min,max and average of the numbers the user has entered. I keep getting a InputMismatchException when I press x. I have tried a lot of different ways and that is why I may have some unnecessary code in there.
import java.io.*;
import java.util.Scanner;
import java.lang.Number;
public class taskTwo{
public static void main(String [] args) throws IOException {
int min = 0;
int max = 0;
boolean isX =false;
Scanner input = new Scanner (System.in);
BufferedReader input2 = new BufferedReader (new InputStreamReader (System.in));
String s = "x";
s = input2.readLine();
while(isX == false){
if(s.equals ("x") || s.equals ("X")){
isX = true;
}
int val = input.nextInt();
if (val == 0) {
break;
}
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
}
if(isX == true){
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
}
}
in the while loop you are using nextInt(), obviously it will expect an integer as input. So when you are giving input x which is an string then it will fail.
So in the loop take string as input and if it is not X and is a number then convert it to int values and calculate
s = input2.readLine(); is called outside while loop means only for first line it will check for X and loop can never be ended if fist line is not X or you entered 0.
1.) You don't need two objects reading input. Just input is sufficient.
2.) You can use
input.hasNextInt();
and
input.hasNext();
to check if the input is an int or a string. Something like:
while(true){
if(input.hasNextInt()){
//do something with the integer
}else if(input.hasNext()){
if(input.next().toLowerCase() == "x"){
break;
}
}
}

How to implement Java "Scanner" in C++?

Please have a look at the following java code
import java.util.Scanner;
public class Main
{
static int mul=1;
static String convert;
static char[] convertChar ;
static StringBuffer buffer = new StringBuffer("");
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
int number=0;
int loopValue = scan.nextInt();
//System.out.println("print: "+loopValue);
for(int i=0;i<loopValue;i++)
{
number = scan.nextInt();
// System.out.println("print: "+number);
for(int a=1;a<=number/2;a++)
{
if(number%a==0)
{
//System.out.println(a);
mul = mul*a;
//System.out.println(mul);
}
}
convert = String.valueOf(mul);
convertChar = convert.toCharArray();
if(convertChar.length>4)
{
/*System.out.print(convertChar[convertChar.length-4]);
System.out.print(convertChar[convertChar.length-3]);
System.out.print(convertChar[convertChar.length-2]);
System.out.print(convertChar[convertChar.length-1]);
System.out.println();*/
buffer.append(convertChar[convertChar.length-4]);
buffer.append(convertChar[convertChar.length-3]);
buffer.append(convertChar[convertChar.length-2]);
buffer.append(convertChar[convertChar.length-1]);
System.out.println(buffer);
}
else
{
System.out.println(mul);
}
//System.out.println(mul);
mul = 1;
}
}
}
This code is built to compute the product of positive divisors of a given number. I have used scanner here because I don't know how many inputs will be entered. That is why I can't go something like
int a, b;
cin >> a >> b
in C++. All the inputs will be inserted by a test engine, into one single like like following
6 2 4 7 8 90 3456
How can I implement the Java "Scanner" using C++ ? Is there a header file for that? Please help!
You seem to be using Scanner to read one integer at a time from the standard input stream. This is easily accomplished with the extraction operator, operator>>.
Replace this code:
Scanner scan = new Scanner(System.in);
int number=0;
int loopValue = scan.nextInt();
//System.out.println("print: "+loopValue);
for(int i=0;i<loopValue;i++)
{
number = scan.nextInt();
// System.out.println("print: "+number);
With this:
int number=0;
int loopvalue=0;
std::cin >> loopvalue;
for(int i = 0; i < loopValue; i++)
{
std::cin >> number;
You should check the value of std::cin after the >> operations to ensure that they succeeded.
Refs:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt
If you use std::cin >> value; to read the value then you can only process the entire line once a new-line has been detected.
If you want to process each number as it is typed then you could use a function like:
int nextInt()
{
std::stringstream s;
while (true)
{
int c = getch();
if (c == EOF) break;
putch(c); // remove if you don't want echo
if ((c >= '0' && c <= '9') || (c == '-' && s.str().length() == 0))
s << (char)c;
else if (s.str().length() > 0)
break;
}
int value;
s >> value;
return value;
}
OK, there are probably more efficient ways to write that but it will read the input character by character until a number is encountered and will return whatever number is read when anything other than a number is encountered.
E.g. 1 2 3 4 would return 1 on the first call, 2 on the second etc.

Categories