I want to make an ArrayList of a list of characters.
Right now I have this code:
Scanner scannerMcScannersonTM = new Scanner(System.in); //This is trademarked.
String[] inputs = new String[5];
List<List<char>> list = new ArrayList<List<char>>();
for(int i =0; i < inputs.length; i++){
System.out.println("Enter pair number " + (i+1) + " separated by a space");
inputs[i] = scannerMcScannersonTM.nextLine();
for(int j = 0; j < inputs[i].length(); i++){
list[i] = inputs[i].toChar(); //it is clear that I don't know what I am doing lol
}
}
Thanks for your help! :D
Scanner scannerMcScannersonTM = new Scanner(System.in); //This is trademarked.
//you do not need this if you know the size and not using inputs afterwards.
String[] inputs = new String[5];
// java collections can only contain non-primitive types, hence, use Character instead of char
List<List<Character>> list = new ArrayList<>();
for(int i=0; i < inputs.length; i++) {
System.out.println("Enter pair number " + (i+1) + " separated by a space");
String inputs[i] = scannerMcScannersonTM.nextLine();
// .toCharArray() method on string does exactly what it says.
// and Arrays.asList(.. an array ..) will convert the array to a List!
list.add(Arrays.asList(inputs[i].toCharArray()));
}
Related
I am writing some pretty basic java code. The idea is to use a loop to write up to 20 numbers into an array. I want to exit the loop when there are no values left. Right now, my code will write to the array, but I cannot get it to exit the loop without entering a non-integer value. I have read some other posts, but they tend to use string methods, which would make my code kind of bulky. I feel like there is a simple solution to this, but I can't seem to figure it out....
import java.util.Scanner;
public class getArray{
public static void main (String[] args){
Scanner scnr = new Scanner(System.in);
int[]newArray = new int[20];
int newArraySize = 0;
while (scnr.hasNextInt()){
newArray[newArraySize] = scnr.nextInt();
newArraySize += 1;
continue;
}
for (int i = 0; i < newArraySize; i++){
System.out.println("The " + i + " input is " + newArray[i]);
}
}
}
And yet another alternative. Allows for single numerical entry or white-space delimited multiple numerical entry, for example:
--> 1
--> 2
--> 10 11 12 13 14 15 16
--> 20
--> 21
Enter nothing to end data entry and view array contents:
Scanner scnr = new Scanner(System.in);
List<Integer> valuesList = new ArrayList<>();
System.out.println("Enter all the Integer values you would like");
System.out.println("stored into your int[] array. You can enter");
System.out.println("them either singular or multiple values on a");
System.out.println("single line spaced apart with a single white");
System.out.println("space. To stop numerical entry and view your");
System.out.println("array contents just enter nothing.");
System.out.println("============================================");
System.out.println();
String inputLine = "";
while (inputLine.isEmpty()) {
System.out.print("Enter a numerical value: --> ");
inputLine = scnr.nextLine().trim();
// If nothing is supplied then end the 'data entry' loop.
if (inputLine.isEmpty()) {
break;
}
//Is it a string line with multiple numerical values?
if (inputLine.contains(" ") && inputLine.replace(" ", "").matches("\\d+")) {
String[] values = inputLine.split("\\s+");
for (String vals : values) {
valuesList.add(Integer.valueOf(vals));
}
}
//Is it a string line with a single numerical value?
else if (inputLine.matches("\\d+")) {
valuesList.add(Integer.valueOf(inputLine));
}
// If entry is none of the above...
else {
System.err.println("Invalid numerical data supplied (" + inputLine + ")! Try again...");
}
inputLine = "";
}
System.out.println("============================================");
System.out.println();
// Convert List<Integer> to int[]...
int[] newArray = new int[valuesList.size()];
for (int i=0; i < valuesList.size(); i++) {
newArray[i] = valuesList.get(i);
}
// Display the int[] Array
for (int i = 0; i < newArray.length; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
If I understand correctly, then you want the input of numbers to be limited to the size of the array?
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (newArraySize < newArray.length && scnr.hasNextInt()) {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}
for (int i = 0; i < newArraySize; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
}
Your while loop condition should be as long as newArraySize is less than the actual size. Here is a fix with some modifications:
Scanner scnr = new Scanner(System.in);
int[]newArray = new int[20];
int newArraySize = 0;
while (newArraySize < newArray.length){
try {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}catch(Exception e){
scnr.nextLine();
}
}
for (int i = 0; i < newArraySize; i++){
System.out.println("The " + i + " input is " + newArray[i]);
}
A solution using Java Stream API:
Scanner sc = new Scanner(System.in);
System.out.println("Input 20 numbers: ");
int[] arr = IntStream.generate(sc::nextInt) // create infinite stream generating values supplied by method `nextInt` of the scanner instance
.limit(20) // take only 20 values from stream
.toArray(); // put them into array
System.out.println(Arrays.toString(arr)); // print array contents at once
Also, there's a utility method Arrays.setAll allowing to set array values via IntUnaryOperator:
int[] arr = new int[20];
Arrays.setAll(arr, (x) -> sc.nextInt());
While loop should have condition for Array Length, kindly try below code which will stop taking inputs after 21st input and array elements will be displayed.
import java.util.Scanner;
public class AarrayScanner {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int[] newArray = new int[20];
int newArraySize = 0;
while (scnr.hasNextInt() && newArraySize < newArray.length) {
newArray[newArraySize] = scnr.nextInt();
newArraySize++;
}
for (int i = 0; i < newArraySize; i++) {
System.out.println("The " + i + " input is " + newArray[i]);
}
}
}
I keep getting an error with my code specifically at
ArrayList<String> input[i]= (i + 1) + " " + ArrayList<String> input[i];
the error tells me "; expected" what am I doing wrong here?
Scanner scnr = new Scanner(System.in);
System.out.println("how many lines of text do you want to enter");
int numLines = 0;
numLines = scnr.nextInt();
System.out.println();
ArrayList lines = new ArrayList();
scnr.nextLine();
int i = 0;
do{
System.out.println("Enter your text: ");
String text = scnr.nextLine();
ArrayList<String> input = new ArrayList<String>();
i++;
for (i = 0; i < numLines; i++)
{
ArrayList<String> input[i]= (i + 1) + " " + ArrayList<String> input[i];
}
for (String element: ArrayList<String> Lines)
{
System.out.println(element);
}
} while(i != 0);
As you have
ArrayList<String> input = new ArrayList<String>();
within your loop, it means that it will get re-declared and initialised for every iteration of that loop, so move this declaration to before your do
Next, to add to this loop, use add method
String text = scnr.nextLine();
input.add (text);
To simplify, you do not need a do as you have a number of times that you want to loop
Scanner scnr = new Scanner(System.in);
System.out.println("how many lines of text do you want to enter");
int numLines = scnr.nextInt();
System.out.println();
scnr.nextLine();
ArrayList <String> lines = new ArrayList <> ();
for (int i = 0; i < numLines; i++) {
System.out.println("Enter word...");
String text = scnr.nextLine();
lines.add(text);
}
To print your list, you can then do
for (int x = 0; x < lines.size(); x++) {
System.out.println (lines.get(x));
}
output
how many lines of text do you want to enter
5
Enter word...
one
Enter word...
two
Enter word...
three
Enter word...
four
Enter word...
five
one
two
three
four
five
Write a program where the user types in a number of Strings which are stored in an array of Strings and then the program prints out all the longest Strings entered by the user.
HAVE A PROBLEM HOW TO PRINT ALL SAME LONGEST LENGTH() According to this sentence that required "the program prints out all the longest Strings"
PS. My code can only print out ONE longest length string NOT ALL longest String. How to fixed it.
public static void method4(){
Scanner console = new Scanner(System.in);
String[] list = new String[5];
int maxLength = 0;
String longestString = null;
String longestString1 = null;
for (int i = 0; i < list.length; i++) {
System.out.println("Enter a string 5 times: ");
list[i] = console.next();
if (list[i].length() > maxLength){
maxLength = list[i].length();
longestString = list[i];
}
}
System.out.println("Longest string: "+longestString+ "\n\t\t"+longestString1);
}
The problem with your code is: inside the loop that you are getting the user's input, you print the "longest string" at that moment.
This means that the 1st string that the user enters will be a "longest string" and will be printed because its length is compared to 0 and of course it is longer.
You must separate the input of the strings and the output (printing of the longest strings) in 2 separate loops. The 1st loop gets the strings and by comparing calculates the length of the longest string and the 2nd iterates through all the string and prints it only if its length is equal to the maximum length that was calculated in the 1st loop:
String[] list = new String[5];
int maxLength = 0;
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < list.length; i++) {
System.out.println("(" + (i + 1) + ") Enter a string: ");
list[i] = scanner.nextLine();
if (list[i].length() > maxLength){
maxLength = list[i].length();
}
}
scanner.close();
int counter = 0;
for (String s : list) {
if (s.length() == maxLength){
counter++;
System.out.println("(" + counter + ") Longest string: " + s + "\n");
}
}
You have to do it in two pass. First loop finds the max length of string. Then second loop can iterate and print only strings that have max length,
public static void method4(Scanner console){
String[] list = new String[5];
int maxLength = 0;
System.out.println("Enter a string 5 times: ");
for (int i = 0; i < list.length; i++) {
list[i] = console.next();
if (list[i].length() > maxLength){
maxLength = list[i].length();
}
}
for (int i = 0; i < list.length; i++) {
if (list[i].length() == maxLength) {
System.out.println("Longest string: "+list[i]);
}
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
method4(sc);
sc.close();
}
There are other approaches too where you can store the longest strings in a set as you encounter them and reset the set the moment you find a new longer string and finally print all the strings in the Set.
I am trying to get the value of string and integer so I can make use of that. I have taken the value and trying to store in array and then printing the value. For some reason I am not getting the value of string correctly. Can you please help me to make my code correct.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
int [] numbers = new int[r];
String names[] = new String[r];
for(int i=0; i<r; i++){
numbers[i] += sc.nextInt();
names[i] += sc.next();
}
System.out.println(Arrays.toString(numbers));
System.out.println(Arrays.toString(names));
}
Output : [2,2]
[nullAA, nullBB]
And also How can I get the indexes of both the arrays after print statement.
You are appending the default value of names[i] (null) to the value read from the Scanner.
Change
names[i] += sc.next();
to
names[i] = sc.next();
And if you want to print the indices of the arrays, use a loop :
for (int i = 0; i < r; i++)
System.out.print(i + " ");
System.out.println();
I have a working program which takes the first letter of a word then switches it to the back of the word and adds "ay to the end. It works fine but I am trying to store the original word and the newWord in a 2D array and output all contents of the array. I have tried but have come to a dead end.
import javax.swing.JOptionPane;
public class Decoder1App{
public static void main(String[]args){
String word="";
String newWord="";
String log[][] = new String[3][2];
for(int i=0;i<log.length;i++){
for(int j=0;j<log[i].length;j++){
Decoder1 D1 = new Decoder1();`enter code here`
word = JOptionPane.showInputDialog(null,"Please enter your word");
D1.setWord(word);
D1.compute();
newWord=D1.getNewWord();
}
}
JOptionPane.showMessageDialog(null,"The new word is " + newWord);
}
}
What exactly doesn't work?
Why are you using a 2d array?
If you must use a 2d array:
int numOfPairs = 10;
String[][] array = new String[numOfPairs][2];
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
array[i] = new String[2];
array[i][0] = "original word";
array[i][1] = "rearranged word";
}
}
Does this give you a hint?