I have a bit of a unique problem to solve and I'm stuck.
I need to design a program that does the following:
Inputs two series of numbers (integers) from the user.
Creates two lists based on each series.
The length of each list must be determined by the value of the first digit of each series.
The rest of the digits of each series of numbers becomes the contents of the list.
Where I'm getting stuck is in trying to isolate the first number of the series to use it to determine the length of the list.
I tried something here so let me know if this is what you're looking for. It would be better for you to provide your attempt first.
I also want to point out that Lists are for the most part dynamic. You don't have to worry about the size of them like a normal array.
Scanner sc = new Scanner(System.in);
ArrayList<Integer[]> addIt = new ArrayList<>();
boolean choice = false;
while(choice == false){
String line = sc.nextLine();
if(line.equalsIgnoreCase("n")){
break;
}
else{
String[] splitArr = line.split("\\s+");
Integer[] convertedArr = new Integer[splitArr.length];
for(int i = 0; i < convertedArr.length; i++){
convertedArr[i] = Integer.parseInt(splitArr[i]);
}
addIt.add(convertedArr);
}
}
This is assuming that you are separating each integer with a whitespace. If you are separating the numbers with something else just modify the split statement.
The user enters "n" to exit. With this little snippet of code, you store each array of Integer objects in a master ArrayList. Then you can do whatever you need to with the data. You can access the first element of each Integer object array to get the length. As you were confused how to isolate this value, the above snippet does that for you.
I would also advise you to add your parse statement in a try-catch block to provide error handling for invalid input that cannot be parsed to an integer.
This is one way of doing it with default arrays.
import java.util.Scanner;
public class ScanList {
public static void main(String[] args){
System.out.println("Array:");
Scanner s = new Scanner(System.in);
String line = s.nextLine();
String[] nums = line.split(",");
int[] result = new int[Integer.parseInt(nums[0])];
for(int i = 0; i<result.length;i++){
result[i]=Integer.parseInt(nums[i+1]);
}
for(int r:result){
System.out.println(r);
}
}
}
This is what I came up with:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Insert the first series of numbers: ");
String number1 = input.nextLine();
System.out.println("Insert the second series of numbers: ");
String number2 = input.nextLine();
String[] items = number1.split(" ");
String[] items2 = number2.split (" ");
List<String> itemList = new ArrayList<String>(Arrays.asList(items));
itemList.remove(0);
Collections.sort(itemList);
System.out.println(itemList);
} // End of main method
Related
I am trying to have the user set the name for how many numbers they set. for example if they set 3 the program asks for name 3 times and then sets those names to a different varible inside an array.
public static void main(String[] args) {
Scanner Num = new Scanner(System.in);
Scanner Name = new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int number = Num.nextInt();
int[] numbs = new int[number];
for (int i = 0; i < numbs.length; i++) {
System.out.println("What is your name");
String [] nameArray = Name.nextLine();
Just a small improvement over Titan's answer.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int numberOfTimes = sc.nextInt();
String[] names = new String[numberOfTimes];
sc.nextLine();
for (int i = 0; i < numberOfTimes; i++) {
System.out.println("What is your name");
names[i] = sc.nextLine();
}
System.out.println(Arrays.toString(names));
}
Starting point
Here are several things happening in your posted code:
You have two different Scanners, each reading from System.in
After prompting for user input (int number = Num.nextInt()), you're using that number to create an array of size "number"
When you call nextLine(), you are assigning the result to a string array (String []).
Working solution
Here's a variation which addresses those issues, with a few additions, too:
Use one Scanner, and give it a general name ("scanner", not "Num") since a scanner has nothing to do with one specific data type. Any scanner can read strings, integers, booleans, bytes, etc. Look in Javadoc for the full set of supported data types.
Check if user input is valid before trying to create an array – if user enters "-1" that's a valid integer value, but not valid for allocating an array – new int[-1]) would throw a java.lang.NegativeArraySizeException at runtime.
Use "next()" instead of "nextLine()" – with the rest of your example, using "nextLine()" results in skipping one line without direct interaction from the user (so the first "name" is always an empty string)
Assign the result of "next()" to a String (not String[]), matching the return type from the method
Use "System.out.print()" instead of "println()", a little tidier program output
Use lowercase names to follow Java naming conventions ("scanner", not "Scanner")
Scanner scanner = new Scanner(System.in);
System.out.print("How many names do you want to enter: ");
int times = scanner.nextInt();
if (times < 0) {
System.out.println("negative numbers not allowed");
} else {
String[] names = new String[times];
for (int i = 0; i < times; i++) {
System.out.print("What is your name: ");
names[i] = scanner.next();
}
System.out.println(Arrays.toString(names));
}
And here's a sample run:
How many names do you want to enter: 3
What is your name: one
What is your name: two
What is your name: three
[one, two, three]
Create a String array of number length outside the loop and initialize each index with name as input.
By the way you only need to create one Scanner object for input(Not needed to create various objects for different input).
Edit - There was no use of numbs array.
Scanner sc=new Scanner(System.in);
System.out.println("How many names do you want to enter: ");
int number = sc.nextInt();
String []nameArray=new String[number];
/*Since nextInt() does not read the newline character in your input
created by hitting "Enter"*/.
sc.nextLine();
for (int i = 0; i < number; i++) {
System.out.println("What is your name");
nameArray[i]=sc.nextLine();
}
sc.close(); //To prevent memory leak
I need to use scanner to get 2 inputs.
1st input is a sequence of integers that I need to store in ArrayList.
2nd input should go right after the first one and it's integer as well.
My question is - how do I stop accepting input for ArrayList and tell the machine to ask for a second number.
I ended with something like this but it does not of course work because it just keeps asking for integers for arraylist. And yes, I need to use ArrayList for the task, since I don't know how many integers there will be. I also haven't learned List interface yet so I need to use what I have in my disposal.
while (scanner.hasNextInt()) {
numbers.add(scanner.nextLine());
if (scanner.hasNextInt()) {
referenceNumber = scanner.nextInt();
}
}
I managed to solve it this way, though probably not optimal
String inputString = scanner.nextLine();
String[] inputArray = inputString.split(" ");
int[] numberArray = new int[inputArray.length];
for (int i = 0; i < inputArray.length; i++) {
numberArray[i] = Integer.parseInt(inputArray[i]);
}
if (scanner.hasNextInt()) {
referenceNumber = scanner.nextInt();
}
if your input sequence is something like 23 34 54 46 then you can use this
Scanner scanner = new Scanner(System.in);
String integers = scanner.nextLine();
StringTokenizer string = new StringTokenizer(integers);
ArrayList<Integer> list = new ArrayList<Integer>();
while(string.hasNextToken()){
list.add(Integer.parseInt(string.nextToken()));
}
I have written a small program to take number of elements from user and the price of those elements and then print the price.
But the 12th line of this code giving error "float cannot be converted into float[]", and I am not able to figure out how to resolve this. Please provide some help or any modification in the code if needed.
import java.util.Scanner;
public class Main{
public static void main( String args[]){
System.out.println("enter the number of elements :" );
Scanner s1= new Scanner(System.in);
int N = s1.nextInt();
System.out.println("enter the price of all the elements in ascending
order: ");
float[] price =new float[N];
for(int i=0; i<N;i++){
price=s1.nextFloat();
System.out.println(price);
}
}
}
In your code, price is an array
float[] price = ...
And an array of type T consists of elements, each of type T. So you need to assign an element of the array to a float e.g.
price[i] = myFloat;
Formatting and nomenclature are a must when you write code as it makes your code more readable and easy to understand. I have formatted your code and also updated for proper inputs.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
System.out.println("enter the number of elements :");
Scanner s1 = null;
try {
s1 = new Scanner(System.in);
int totalElements = s1.nextInt();
System.out.println("enter the price of all the elements in ascending order :");
float[] price = new float[totalElements];
for (int i = 0; i < totalElements; i++) {
price[i] = s1.nextFloat();
System.out.println(Arrays.toString(price));
}
} finally {
if (s1 != null) {
s1.close();
}
}
}
}
Please take care of below things:
Variable names should start with small case and follow camel casing.
Scanner whenever used needs to be closed.
Your error is resolved by assigning float to one position in array and not to the array. E.g. price[i] = s1.nextFloat();
To print an array, use the Arrays.toString() function.
Happy Coding
import java.util.Scanner;
public class Main{
public static void main( String args[]){
System.out.println("enter the number of elements :" );
Scanner s1= new Scanner(System.in);
int N = s1.nextInt();
System.out.println("enter the price of all the elements in ascending
order :");
float[] price =new float[N];
for(int i=0; i<N;i++){
price[i]=s1.nextFloat();
System.out.println(price[i]);
}
}
}
It should be like this because in the printing statement you've called the whole array that won't give you the element but the some numbers and alphabets thing and also the statement where you're reading the prices by scanner you are not telling the computer to put your price at which index of the array that's why it's giving this error.
I'm creating a console program in Java with an array, I need to enter all of my code on one line in the following format up to 100 times.
car_make_name : car_model_name : car_model_tax : car_model_price
It's two strings and two int variables, I have code written out but I don't know how to use .split to enter the correct information into the corresponding variable.
This is my code:
public class Main {
public static void main (String[] args)
{
//Arrays declared
String[] cars = new String[20];
String[] car_model_name = new String[20];
int[] car_model_tax = new int[20];
String[] car_make_name = new String[20];
int[] car_model_price = new int[20];
Scanner scan = new Scanner (System.in);
//Loop??
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.equals("quit", "QUIT", "Quit")) {
}
}
break;
for (int x = 0; x < cars.length; x++){
System.out.println("Enter details, separating each with a ':' ");
cars[x] = System.console().readLine();
}
}
}
First, you may prefer List but not array to store your information if you read input from console and you can't control the input length of your user.
Second, you may want to use String#split to split and convert it if necessary.
System.out.println("Enter details, separating each with a ':' ");
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.equals("quit")) {
break;
}
final String[] split = line.split(":");
// handle it
}
Third, A good book can improve your programming level so much.If you have no experience of programming, I recommend Head First Java. Otherwise, I recommend Thinking In Java.
I am working on a project for a class and I keep running into a problem. I am trying to terminate a program when the user types stop. If I remove text = input.nextLine(); the code works correctly however it does not stop when the user request. I also tried making a new scanner object, but that did not fix the problem. Any help with this problem would be appreciated.
Thank you.
class blah
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String text = ("");
while(!text.equals("stop"))
{
System.out.print("Insert the number of items, holder value and passing value:");
text = input.nextLine();
int items = input.nextInt();
int holder = input.nextInt();
int passing = input.nextInt();
killBot5000 josephus = new killBot5000(items,holder,passing);
josephus.execute();
}
}
}
The problem is that the input can be either a String stop or three integers
You could change your code to just accept a line of input, decide if it is stop and if not then split the line into three tokens which can be converted to ints.
while(!text.equals("stop"))
{
System.out.print("Insert the number of items, holder value and passing value:");
text = input.nextLine();
if (text.equalsIgnoreCase ("stop")) break;
String arr [] = text.split (" ");
int items = Integer.valueOf (arr[0]);
int holder = Integer.valueOf (arr[1]);
int passing = Integer.valueOf (arr[2]);
killBot5000 josephus = new killBot5000(items,holder,passing);
josephus.execute();
}