alright so im wondering how can I read an integer and string from the same line? Ill give an example:
if I have input=3K how can I make my output look like this: 3K=3000?
Start by breaking down you requirements.
You have an input value of [number][modifier]
You need to extract the number from the modifier
You need to apply the modifier to the number
If you want a variable/flexible solution, where you can supply any type of modifier, you will need to determine the number of digits the user has entered and then the modifier.
Once you have that, you can split the String, convert the digits to an int and apply the appropriate calculations based on the modifier...
Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
int index = 0;
while (index < input.length() && Character.isDigit(input.charAt(index))) {
index++;
}
if (index >= input.length()) {
System.out.println("Input is invaid");
} else {
String digits = input.substring(0, index);
String modifier = input.substring(index);
int value = Integer.parseInt(digits);
switch (modifier.toLowerCase()) {
case "k":
value *= 1000;
break;
//...
}
System.out.println("Expanded value = " + value);
}
String input = "3k";
String output = input.replaceAll("[Kk]", "000");
int outputAsInt = Integer.parseInt(output);
Related
I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```
This is my second question here and still a beginner so please bear with me.
I have this code of a very basic hangman type game.I have changed the characters to "-",I am able to get the indices of the input but I am not able to convert back the "-" to the characters entered.
Its an incomplete code.
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
for (int j=0;j<10;j++){ //Asks 10 times for user input
input = inpscanner.nextLine();
int check = line.indexOf(input);
while (check>=0){
//System.out.println(check);
System.out.println(encrypt.replaceAll("-",input).charAt(check));
check = line.indexOf(input,check+1);
}
Here is how it looks like:
You have 10 chances to guess the movie
------
o
o
o
L
L
u //no repeat because u isn't in the movie.While 'o' is 2 times.
I would like to have it like loo---(looper).
How can I do like this "[^ ]","-" in case of a variable?
This might help.
public static void main(String[] args) {
String line = "xyzwrdxyrs";
String input;
String encrypt = line.replaceAll("[^ ]","-");
System.out.println(encrypt);
System.out.println(line);
Scanner scanner = new Scanner(System.in);
for (int j=0;j<10;j++) { //Asks 10 times for user input
input = scanner.nextLine();
//int check = line.indexOf(input);
int pos = -1;
int startIndex = 0;
//loop until you all positions of 'input' in 'line'
while ((pos = line.indexOf(input,startIndex)) != -1) {
//System.out.println(check);
// you need to construct a new string using substring and replacing character at position
encrypt = encrypt.substring(0, pos) + input + encrypt.substring(pos + 1);
//check = line.indexOf(input, check + 1);
startIndex = pos+1;//increment the startIndex,so we will start searching from next character
}
System.out.println(encrypt);
}
}
I have a numeric String i want to change the String first three character's by another character
Suppose I have a String like 0333XXXXXXX and +38333XXXXXXX. if the first character of String is +38 i want to replace it with "0" while remaining String remain the same Here is my code
private String modifyNumber(String num) {
if (num.startsWith("+38")) {
num.replaceFirst("+38", "0");}
return num;}
"+38" is not accepting in num.replaceFirst.
You can use string replace method. see below
String number = +9231235410;
String newNumber = number.replace("+92","0");
EDIT:
this one is base on your code
private String modifyNumber(String num) {
if (num.startsWith("+92")) {
num = num.replaceFirst("\\+(92)", "0");}
return num;}
Note:
In java, you need to have double backslash since the \ is a unique
java character.
Java strings are immutable method. you need to assign it to a variable to have the result. num = num.replaceFirst("\\+(\\d{2})", "0")
you can use substr() and concat with '0' like,
String str= "+919025858316";
String newstr ="";
if(str.substring(0,3).equals("+91"))
{
newstr = "0" + str.substring(3);
}
else
{
newstr = str;
}
System.out.println(newstr);
output is 09025858316
Check like this :
String num = "+921231231231"; // OR String num = "01231231231";
if(num.startsWith("+92")) {
String a = "0" + num.substring(3);
System.out.println("" + a);
}else{
System.out.println("" + num);
}
Update:
private String modifyNumber(String num) {
if(num.startsWith("+92")) {
num = "0" + num.substring(3);
}
return num;
}
you can just get the last 10 digit of the string and then you can add the zero.
might be that help you
String number= str.substring(Math.max(str.length() - 10, 0));
number ="0"+number;
from here you can get the correct phone number without any code.
might be this help you.Thanks
There is some standardization on mobile numbers in every country. The mobile number is 10 digit. Only here, the last 10 digits are mobile numbers and rest of the digits are country code so take the last 10 digit and add 0 to the first. Then, your problem will be resolved.
i.e,
String number = "+929918001800";
String newNumber = "0"+number.subString(number.length()-10,number.length());
I hope this one will help you :)
Are there any resources available in the java documentation, or elsewhere that can lead me in the right direction on this? Even just giving the method(s) would help greatly.
Let's say I prompt a user to enter an integer i greater than 0. Then, in the output, they get a string that is the length of the integer. The characters can range from "!" to "~" on the ASCII table (33-126).
For example:
"Enter an integer greater than 0: "
Input: 8
Output: &3lR(c$2
"Enter an integer greater than 0: "
Input: 4
Output: I*#f
Etc, etc...
I think I can figure out the rest myself, such as generating a random (a real random, not a pseudo-random), doing the necessary loop to print an error message if the input is less than or equal to 0. I would prefer method hints over code anyway.
Thank you.
Use a loop with StringBuilder:
String randomString(int lengthOfString){
int minChar = 33;
int maxChar = 126;
StringBuilder result = new StringBuilder();
for (int i = 0; i < lengthOfString; i++){
result.append((char) generateRandomBetweenTwoNumbers(minChar, maxChar));
}
return result.toString();
}
Once you use your random number generator you can just construct the String by converting the int's to char's:
String output = (char)40 + "" + (char)60....
Here's a way to do it using code a beginner would have seen; I don't recommend this.
import java.util.Random;
public class stack {
public static void main(String[] args) {
int length = 8;
char character = 0;
String output = "" + character;
Random random = new Random();
for (int i = 0; i < length; i++) {
character = (char) (random.nextInt(126 - 33 + 1) + 33);
output += character;
}
System.out.println(output);
}
}
I am a beginner programmer. This is what I have so far. The directions for the question are kind of difficult. Here is what I am trying to accomplish..
You will write a program that converts binary numbers to base 10 numbers. This program will ask the user to enter a binary number. You will have to verify that what is entered by the user only has 0s and 1s. In the case the user entered letters, you have to keep asking the user for another input. When the input is valid, you will convert the binary number to a base 10 number. Please use the Question1.java file provided in the A2.zip file.
Valid input - In order to check if the input is valid your program should call the CheckInputCorrect method, which takes a String as an input parameter and returns a boolean value. An input string is considered valid if it corresponds to a number in binary representation.
More specifically, in the CheckInputCorrect method, you should scan this string to make sure it only contains ‘0’ or ‘1’ characters. As soon as you find a character that is not ‘0’ or ‘1’, the method should returns false. If the method reaches the end of the input string (i.e. all characters are ‘0’ or ‘1’) the method should return true.
Converter - At this point we assume that the input string is valid (checked with the CheckInputCorrect method). To convert the input from binary to base 10, you must implement the BinaryToNumber method. The BinaryToNumber method should take as parameter a String and return an integer, which corresponds to converted value in base 10.
The binary conversion should work as follows. For each digit in the binary number, if the digit is ‘1’ you should add the corresponding decimal value ( 20 for the rightmost digit, 21 for the next digits to the left, 22 for the next one, and so on) to a variable that will hold the final result to be returned. This can be easily accomplished by using a loop.
1) Am I on the right path?
2) I don't exactly know what I am doing and need you to help me figure that out....
Update1:
When I run this vvvv: It says "Please enter a binary number for me to convert: and then a place for me to type in my answer but whatever i put it just returns another box for me to type in but stops and doesn't evaluated anything.
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
boolean BinaryNumber = false;
String inputString = "";
while (!BinaryNumber){
inputString = inputKeyboard.next();
BinaryNumber = CheckInputCorrect(inputString);
System.out.println("You have given me a " + BinaryNumber + "string of binary numbers.");
}
int finalNumber = BinaryToNumber(inputString);
System.out.println("Congratulations, your binary number is " + finalNumber + ".");
}
public static boolean CheckInputCorrect(String input)
{
for (int i = 0; i < input.length(); i++)
{
while (i < input.length());
if (input.charAt(i) != '0' && input.charAt(i) != '1')
{return false;}
i++;
}
return true;
}
public static int BinaryToNumber(String numberInput)
{
int total = 0;
for (int i = 0; i < numberInput.length(); i++){
if (numberInput.charAt(i)=='1')
{
total += (int)Math.pow(2,numberInput.length() - 1 - i);
}
}
return total;
}
}
Original:
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
int binarynumber;
int arraySize = {0,1};
int[] binaryinput = new int[arraySize];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a binary number");
binarynumber = in.nextInt();
if (binarynumber <0)
{
System.out.println("Error: Not a positive integer");
}
if (CheckInputCorrect) = true;
{
System.out.print(CheckInputCorrect);
}
public static boolean CheckInputCorrect(String input);
{
boolean b = true;
int x, y;
x = 0
y = 1
b = x || y
while (b >= 0 {
System.out.print("Please enter a binary number")
for (int i = 0; i < binarynumber.length; i++)
{
binaryinput[i] = in.nextInt();
if (binaryinput[i] = b.nextInt();
System.out.printl("Binary number is:" + binaryinput);
break outer;
if (binarynumber != b)
{
System.out.println("Error: Not a binary number")
}
return true;
}
}
public static int BinaryToNumber(String numberInput)
{
int remainder;
if (binarynumber <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number %2;
printBinaryform(number >> 1);
System.out.print(remainder);
return 0;
}
}
}
As mentioned in my comments, your updated code contains two errors
while (i < input.length()); is an infinite loop, because it has no body. Therefore i cannot be increased and will stay lower than input.length().
inputString = inputKeyboard.next(); request another input after the first one and the first input will be ignored.
This is a fixed and commented version of your updated code:
public class Question1 {
public static void main(String[] args) {
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
//boolean BinaryNumber = false; // not needed anymore
//String inputString = ""; // not needed too
while (!checkInputCorrect(inputUser)) { // there is no reason for using a boolean var here .. directly use the returned value of this method
System.out.println("You have given me an invalid input. Please enter a binary number: "); // changed this message a little bit
inputUser = inputKeyboard.nextLine(); // re-use the "old" variable inputUser here
}
int finalNumber = binaryToNumber(inputUser);
System.out.println("Congratulations, your decimal number is " + finalNumber + ".");
}
public static boolean checkInputCorrect(String input) { // method names should start with a lower case letter
for (int i = 0; i < input.length(); i++) {
//while (i < input.length()); // this loop is deadly. Please think about why
if (input.charAt(i) != '0' && input.charAt(i) != '1') {
return false;
}
//i++; // what is the purpose of this? The "for" loop will increment "i" for you
}
return true;
}
public static int binaryToNumber(String numberInput) { //method name ... lower case letter ;)
int total = 0;
for (int i = 0; i < numberInput.length(); i++) {
if (numberInput.charAt(i) == '1') {
total += (int) Math.pow(2, numberInput.length() - 1 - i);
}
}
return total;
}
}