I have new assignment and since I am new to JAVA I don't know how to make it work, I have searched this website frequently but all the solutions which were suggested didn't work out for me or I didn't use them properly, I would be grateful if someone helps me...
the code below is the most simple solution I could find but still doesn't work...
I want to get inputs like names from people and change them to numbers (int)...it says it is not possible to cast from string to int ... !!
package loveindex;
import java.util.Scanner;
//import java.math.BigInteger;
public class LoveIndex {
private static Scanner scan;
public static void main(String[] args) {
scan = new Scanner(System.in);
System.out.println("Testing Scanner, write something: ");
String testi = scan.nextLine();
System.out.println(testi);
System.out.println("Testing Scanner, write something: ");
String testi2 = scan.nextLine();
System.out.println(testi2);
int ascii = (int) testi;
int ascii = (int) testi2;
}
}
You Can Try This:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Testing Scanner, write something: ");
String testi = scan.nextLine();
char[] ascii1 = testi.toCharArray();
for(char ch:ascii1){
System.out.println((int)ch+" ");
}
System.out.println("Testing Scanner, write something: ");
String testi2 = scan.nextLine();
char[] ascii2 = testi2.toCharArray();
for(char ch:ascii2){
System.out.println((int)ch+" ");
}
scan.close();
}
Achieve the same in a concise way by employing Java 8's lambda function.
From your comment (at the accepted answer) you need the sum of the characters at the end?
String str = "name";
int sum = str.chars().reduce(0, Integer::sum);
You're attempting to assign a String to an int which the 2 of which are incompatible. You can get the ascii value of a single character
int ascii = testi.charAt(0);
You cannot convert string to ascii like that. You can convert a character to ascii
int ascii = (int)some_char;
First of all: Java doesn't use ASCII. It use Unicode (UTF-16, most of the time).
Second: You can make a function to convert your String characters to their Unicode representations, like this:
public static int[] convert(String str) {
int[] result = new int[str.length()];
for (int i = 0; i < str.length(); i++) {
result[i] = str.charAt(i);
}
return result;
}
Related
I have one goal:
1) Multiply character in String n-times (character, String, n [int] - from user input)
Example:
User input1 (String) : future
User input2 (char) : u
User input3 (int) : 2
Output: fuutuure
First i tried with char[] array but IndexOutOfBoundsException brought me back to reality. Second try-StringBuilder but its not working aswell-empty result window. Should I use StringBuilder (and if answer is yes-how?) ? Or there is other, better solution.
Thank you for help.
package Basics.Strings;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Ex4 {
static String giveAWord() {
Scanner scanWord = new Scanner(System.in);
System.out.println("Give a word");
String word = scanWord.nextLine();
return word;
}
static char giveALetter() {
Scanner scanALetter = new Scanner(System.in);
System.out.println("Give a letter");
char let = scanALetter.next().charAt(0);
return let;
}
static int giveANumber() {
Scanner scanNumber = new Scanner(System.in);
System.out.println("Give a number");
int numb = scanNumber.nextInt();
return numb;
}
static String multiplyLetter(String word, char letter, int number) {
StringBuilder sb= new StringBuilder();
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i)==letter) {
sb.append(i*number);
}
}
return sb.toString();
}
public static void main(String[] args) {
String word = giveAWord();
char letter = giveALetter();
int number = giveANumber();
System.out.println(multiplyLetter(word, letter, number));
}
}
There are several things in your multiplyLetter method that would make it not work.
First, you have to initialise the StringBuilder using the word so:
StringBuilder sb = new StringBuilder(word) ;
Else, your StringBuilder will be empty.
Second, you should use the insert(int pos, char c) method, so you can specify where you want tthe character inserted.
And last, you can't just multiply a char and an int and get away with it. If you want to repeatedly insert a character, I think you should use a loop.
So, in summary, try:
StringBuilder sb= new StringBuilder(word);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i)==letter) {
for ( int j = 0 ; j < number ; j++ ) {
sb.insert(i, letter);
i++ ;
}
}
}
Notice I added i++ inside the loop, as sb.length() will increase with each character inserted.
Also, maybe someone more experienced can provide with a more efficient way than just using a loop.
If you are using at least Java 11 (eleven) then the following will work:
String word = "future";
String letter = "u";
int count = 2;
String replacement = letter.repeat(count);
String result = word.replace(letter, replacement);
Note that only method repeat(int) was added in Java 11.
Method replace(CharSequence, CharSequence) was added in Java 5
Java 8 functional way:
String alterString(String input, Character charMatch, int times) {
return input.chars()
.mapToObj(c -> (Character) c) // converting int to char
.flatMap(c -> {
if (c == charMatch) {
Character[] ca = new Character[times];
Arrays.fill(ca, c);
return Arrays.stream(ca); // stream of char c repeated 'times' times
}
return Stream.of(c);
})
.collect(
// following is the string collecting using StringBuilder form stream of characters
Collector.of(
StringBuilder::new,
StringBuilder::append,
StringBuilder::append,
StringBuilder::toString,
);
);
}
A simple way to solve this problem is by using the following functions:
String#join
Collections#nCopies
String#replace
Demo:
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = kb.nextLine();
System.out.print("Enter the character: ");
String ch = kb.nextLine();
System.out.print("How many times to repeat?: ");
int n = kb.nextInt();
String result = str.replace(ch, String.join("", Collections.nCopies(n, ch)));
System.out.println("Result: " + result);
}
}
A sample run:
Enter the string: future
Enter the character: u
How many times to repeat?: 2
Result: fuutuure
My program is to accept words (given as number of test cases) and print them out in reversed order. The problem is that whatever input of array size I may give, it only accepts just one word (and rest as blank). Can anyone help me figure out why? Here's the code:
import java.util.*;
public class terrible {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int test = input.nextInt();
while(test>0){
String str = input.nextLine();char c[] = str.toCharArray();
for(int i=0;i<str.length();i++){
System.out.print(c[str.length()-i-1]);
}
System.out.println();
test--;
}
}
}
Certain versions of Java don't let you take an int and then a string as input from the same Scanner. You can create another Scanner, like
Scanner input2 = new Scanner(System.in);
and then do
String str = input2.nextLine();
This is what I have so far:
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
int x = str.length();
int y = str.charAt(x/2);
System.out.println(str.substring(y, x-1));
For some reason when I run this it's giving me an error.
Please HELP!
I'm still a beginner in this, and I only know how to use the basics in Java.
I don't know how to use arrays and other advanced stuff.
If someone can tell me how to solve this problem in the simplest way possible that would be great!
Thanks in advance! :)
int y = str.charAt(x/2); is not required, actually return character at mid position.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
int x = str.length();
System.out.println(str.substring(0, x/2)); // return part of full string starting from index 0 to mid index
}
Output
WooHoo
Woo
Assumption: even length string always
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
int x = str.length()/2;
System.out.println(str.substring(0, x));
Basically str.charAt(x/2) returns the middle character of the string and when you are storing it to an integer it will covert to its ascii value, which you dont want.
You can do like :
str.substring(0,(str.length())/2)
This looks like one of the problems from codingbat.com, the solution is pretty simple:
return str.substring(0, str.length() / 2);
String str="";
Scanner S=new Scanner(System.in);
str=S.nextLine();
int length=str.length();
if(length%2==0)
{
System.out.println(str.substring(0, length-(length/2)));
}
else
System.out.println(" ");
I have some problem when I ask the user to input some numbers and then I want to process them. Look at the code below please.
To make this program works properly I need to input two commas at the end and then it's ok. If I dont put 2 commas at the and then program doesnt want to finish or I get an error.
Can anyone help me with this? What should I do not to input those commas at the end
package com.kurs;
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
String gd = "4,5, 6, 85";
Scanner s = new Scanner(System.in).useDelimiter(", *");
System.out.println("Input some numbers");
System.out.println("delimiter to; " + s.delimiter());
int sum = 0;
while (s.hasNextInt()) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
s.close();
System.exit(0);
}
}
Your program hangs in s.hasNextInt().
From the documentation of Scanner class:
The next() and hasNext() methods and their primitive-type companion
methods (such as nextInt() and hasNextInt()) first skip any input that
matches the delimiter pattern, and then attempt to return the next
token. Both hasNext and next methods may block waiting for further
input.
In a few words, scanner is simply waiting for more input after the last integer, cause it needs to find your delimiter in the form of the regular expression ", *" to decide that the last integer is fully typed.
You can read more about your problem in this discussion:
Link to the discussion on stackoverflow
To solve such problem, you may change your program to read the whole input string and then split it with String.split() method. Try to use something like this:
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] tokens = sc.nextLine().split(", *");
int sum = 0;
for (String token : tokens) {
sum += Integer.valueOf(token);
}
System.out.println(sum);
}
}
Try allowing end of line to be a delimiter too:
Scanner s = new Scanner(System.in).useDelimiter(", *|[\r\n]+");
I changed your solution a bit and probably mine isn't the best one, but it seems to work:
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
int sum = 0;
if (s.hasNextLine()) {
// Remove all blank spaces
final String line = s.nextLine().replaceAll("\\s","");
// split into a list
final List<String> listNumbers = Arrays.asList(line.split(","));
for (String str : listNumbers) {
if (str != null && !str.equals("")) {
final Integer number = Integer.parseInt(str);
sum = sum + number;
}
}
}
System.out.println(sum);
look you can do some thing like this mmm.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
System.out.println("When did you to finish and get the total sum enter ,, and go");
boolean flag = true;
int sum = 0;
while (s.hasNextInt() && flag) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
}
I'm trying to my first program text to ASCII converter, but I have some problems, it's explained inside the code:
import java.util.Scanner;
public class AsciiConverter {
public static void main(String[] args){
System.out.println("Write some text here");
Scanner scanner = new Scanner(System.in).useDelimiter("\\n"); // Scans whole text
String myChars = scanner.next();
int lenght = myChars.length(); // Checking length of text to use it as "while" ending value
int i = -1;
int j = 0;
do{
String convert = myChars.substring(i++,j++); // taking first char, should be (0,1)...(1,2)... etc
int ascii = ('convert'/1); // I'm trying to do this, so it will show ascii code instead of letter, error: invalid character constant
System.out.print(ascii); // Should convert all text to ascii symbols
}
while(j < lenght );
scanner.close();
}
}
String x = "text"; // your scan text
for(int i =0; i< x.getLength(); x++){
System.out.println((int)x.charAt(i)); // A = 65, B = 66...etc...
}
(Maybe use Scanner.nextLine().)
import java.text.Normalizer;
import java.text.Normalizer.Form;
String ascii = Normalizer.normalize(myChars, Form.NFKD)
.replaceAll("\\P{ASCII}", "");
This splits all accented chars like ĉ into c and a zero length ^. And then all non-ascii (capital P = non-P) is removed.
Try this:
public static void main(String[] args){
System.out.println("Write some text here");
Scanner scanner = new Scanner(System.in).useDelimiter("\\n"); // Scans whole text
String myChars = scanner.next();
char[] charArray = myChars.toCharArray();
for (char character : charArray) {
System.out.println((int)character);
}
scanner.close();
}
This converts the string to a char array and then prints out the string representation of each character.
Replace this line
"int ascii = ('convert'/1);"
by
int ascii= (int)convert;
This should work.
This code will work
import java.util.Scanner;
public class AsciiConverter {
public static void main(String[] args){
System.out.println("Write some text here");
Scanner scanner = new Scanner(System.in).useDelimiter("\\n"); // Scans whole text
String myChars = scanner.next();
int lenght = myChars.length(); // Checking length of text to use it as "while" ending value
int i = -1;
int j = 0;
do{
String convert = myChars.substring(i++,j++); // taking first char, should be (0,1)...(1,2)... etc
int ascii= (int)convert; // I'm trying to do this, so it will show ascii code instead of letter, error: invalid character constant
System.out.print(ascii); // Should convert all text to ascii symbols
}
while(j < lenght );
scanner.close();
}
}
did you missed type casting the character to integer?
try this:
int ascii = (int) convert;