How to take array elements as input - java

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();

Related

My method.add(int) does not add the user input into my array

I am trying to create an Array that asks the user for it's length, and then asks the user to input many single words into the array one at a time. However my code sentences.add(s); does not add my "S" variable into my ArrayList called sentences.Could you please take a look at my code to see what I am doing incorrectly. EDIT When running, after entering the length of the array the program the program asks me to enter a word but immediately
prints on the line below it with two brackets [] and stops the program there. If anyone know why this was happing I would appreciate it so much!
import java.util.Scanner;
import java.util.ArrayList;
public class UsingWords
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an array length ");
int lengthArray = scan.nextInt();
ArrayList<String[]> sentences = new ArrayList<String[]>();
for (int i=0; i <= lengthArray; i++); {
System.out.println("Please enter a word: ");
String s = scan.nextLine();
sentences.add(s);
}
System.out.println(Arrays.toString(sentences));
}
}
It does not work because you declared an ArrayList of String[] and you try to add a String into it.
I.E. sentences should be a of ArrayList<String> type.
I have no idea why you are using arrays in combination with ArrayList.
I suspect you want something like this:
//remove the "[]" here
ArrayList<String> sentences = new ArrayList<String>();
for (int i=0; i <= lengthArray; i++); {
System.out.println("Please enter a word: ");
String s = scan.nextLine();
sentences.add(s);
}
//..and the Arrays.toString here
System.out.println(sentences);

Prevent going to next line after input in console

I have problem with my Java program. I am running the program on the console (CMD).
I would like, after I entered input, that the console stays on the same line (currently it goes to the next line automatically).
This is my current program:
int data[];
Scanner in = new Scanner(System.in);
data = new int[10];
System.out.println("Please Insert Numbers : ");
for(int i=0;i<5;i++)
{
data[i] = in.nextInt();
System.out.print("/t");
}
How can I return to the start of the line instead of going to the next?
Scanner in = new Scanner(System.in);
System.out.println("Please Insert Numbers Separated By Comma: ");
String input = in.nextLine();
input = input.replaceAll("\\s",""); //remove whitespaces
String[] numbers= input.split(","); //build string array using ',' as delimiter between numbers
int data[]= Arrays.asList(numbers).stream().mapToInt(Integer::parseInt).toArray(); //Available since Java8
Like Oscar Martinez said, you could read a string of numbers delimited by white space and build your integer array like this example (before parsing the string to int, I verify if the string can be converted to int or not using a regex ) :
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
int data[];
Scanner in = new Scanner(System.in);
data = new int[10];
System.out.println("Please Insert Numbers : ");
String line = in.nextLine();
String[] stringsNumber = line.split("\\s");
for(int i=0;i<stringsNumber.length;i++){
if(stringsNumber[i].matches("^\\d+$") && i<10){// \\d is a regex to verify if s is a number
data[i]= Integer.parseInt(stringsNumber[i]);
}
}
System.out.println(Arrays.toString(data));
}
}

String input in java

I am trying to take string input in java using Scanner, but before that I am taking an integer input. Here is my code.
import java.util.*;
class prc
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
int n=input.nextInt();
for(int i=1;i<=n;i++)
{
String str=input.nextLine();
System.out.println(str);
}
}
}
The problem is that if I give a number n first, then the number of string it is taking as inputs is n-1.
e.g if the number 1 is entered first, then it is taking no string inputs and nothing is printed.
Why is this happening ?
Thanks in Advance!
nextLine() reads everything up to and including the next newline character.
However, nextInt() only reads the characters that make up the integer, and if the integer is the last (or only) text in the line, you'll be left with only the newline character.
Therefore, you'll get a blank line in the subsequent nextLine(). The solution is to call nextLine() once before the loop (and discard its result).
Information regarding the code is mentioned in the comments written next to each line.
public static void main(String[] args) {
int num1 = sc.nextInt(); //take int input
double num2 = sc.nextDouble(); //take double input
long num3 = sc.nextLong(); //take long input
float num4 = sc.nextFloat(); //take float input
sc.nextLine(); //next line will throw error if you don't use this line of code
String str = sc.nextLine(); //take String input
}
import java.util.*;
class prc
{
public static void main(String[] args)
{
String strs[];
Scanner input = new Scanner(System.in);
int n = input.nextInt();
input.nextLine();
strs = new String[n];
for(int i = 1; i < n; i++)
{
strs[i] = input.nextLine();
System.out.println(strs[i]);
}
}
}

How to cast string to ascii value in java?

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;
}

Create a new string by Concatenating the last letter of the given set of strings in Java

I need to get a number of words from user, and then output a final word which is formed by the concatenation of the last letters of the words that the user has input.
Here is the code. But how do I bring these letters from the loop and concatenate them?
import java.util.Scanner;
public class newWord {
public static void main(String args[]) {
System.out.println("How many words are you going to enter?");
Scanner num = new Scanner(System.in);
int number = num.nextInt();
System.out.println("Please Enter the "+number+" words:");
for(int n=1;n<=number;n++)
{
Scanner words = new Scanner(System.in);
String thisword = words.nextLine();
char str2 = thisword.charAt(thisword.length()-1);
System.out.println(str2);
}
}
}
Hints only ... since this is obviously a learning exercise of some kind.
But how do I bring these letters from the loop and concatenate them?
You don't. You concatenate them within the loop.
String concatenation can be done using the String + operator or StringBuilder.
The rest is up to you. (Please ignore the dingbats who posted complete solutions and work it out for yourself. It will do you good!)
You can use StringBuilder class to concatenate latest characters in strings with append method.
I believe (correct me if I'm wrong) you are asking to take the last letter of each word and make that into one final word. All you need to do is take each of the final letters and add them to a String to hold them all. After the entire for loop, the variable appended should be your requested word.
public static void main(String args[]) {
System.out.println("How many words are you going to enter?");
Scanner num = new Scanner(System.in);
int number = num.nextInt();
System.out.println("Please Enter the "+number+" words:");
String appended = ""; // Added this
for(int n=1;n<=number;n++)
{
Scanner words = new Scanner(System.in);
String thisword = words.nextLine();
char str2 = thisword.charAt(thisword.length()-1);
appended +=str2; // Added this
System.out.println(str2);
}
}
Just you miss things to keep final value in a place and finally print
public static void main(String args[]) {
System.out.println("How many words are you going to enter?");
Scanner num = new Scanner(System.in);
int number = num.nextInt();
System.out.println("Please Enter the "+number+" words:");
StringBuffer sb = new StringBuffer();
for(int n=1;n<=number;n++)
{
Scanner words = new Scanner(System.in);
String thisword = words.nextLine();
char str2 = thisword.charAt(thisword.length()-1);
sb.append(str2);
}
System.out.println(sb.toString());
}
go through StringBuilder and StringBuffer classes you will get your answer..

Categories