I'm quite new to java programming so excuse the basic misunderstandings and interpretations of the fundamentals.
This program is supposed to ask the user for the size of an array, then ask the user for input n amount of times and then prints the array back to the user. So far, the first 2 parts work. The program asks for the size of the array and then prints "Enter element n: " based on how many times the user specified in part 1. However, i can't seem to figure out how to print back the string input back out (In my first for loop) the second for loop i tried does not work and just ends the program straight after the first for loop finishes executing. If anyone could help me it would be much appreciated and contribute to my learning of the basics of java. Cheers.
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter array size: ");
int arraySize = scanner.nextInt();
int[] array = new int[arraySize];
for (int i = 0; i<array.length; i++){
System.out.print("Enter element " + (i + 1) + ": ");
String element = scanner.next();
}
System.out.print(array[0]);
for (int i = 1; i < array.length; i++){
System.out.print(array[i]);
}
System.out.println("}");
}
You're not storing any input value into the array.
replace this line:
String element = scanner.next();
with the following one:
array[i] = scanner.nextInt();
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am feeling quite stupid at this point for not being able to figure out something that is most likely a simple fix. I keep getting the error "Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at searchSorting.main(searchSorting.java:15)" after inputting how many numbers I want to input. Others solutions to this problem just don't seem to apply to me somehow. Thanks for the help
import java.util.Scanner;
import java.util.Arrays;
public class searchSorting
{
public static void main (String[]args)
{
String line;
int number, search, item, array[], first, last, middle;
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to input?: ");
number = in.nextInt();
array = new int [number];
item = Integer.parseInt(in.nextLine());
double[] values = new double[item];
for (int i = 0; i < values.length; i++) {
System.out.print("Input number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
for (int index = 0; index < 5; index++)
System.out.print(values[index] + " ");
in.nextLine();
Arrays.sort(values);
System.out.println("Sorted number is: " + Arrays.toString(values));
System.out.println("Enter the number you are looking for?");
search = in.nextInt();
first = 0;
last = (item - 1);
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
System.out.println(item + " found at location " + (middle + 1) + ".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println(item + " is not found.\n");
}}
For more info check out Scanner and Integer documentation, it's an excellent resource.
Edit: Try removing line 15 and replacing item with number in the next line
You call this:
number = in.nextInt();
Assuming the user types 123 and ENTER, this call consumes the 123 and leaves the input stream positioned before the end-of-line character.
The next relevant code is
item = Integer.parseInt(in.nextLine());
The nextLine call advances the input stream past the end-of-line, returning all characters it passed on the way. Since the ENTER key was pressed immediately after 123, the returned value is the emoty string. Which is not an integer.
You need to review your strategy of sometimes scanning numbers (nextInt) and sometimes scanning rest-of-linr (nextLine). Mixing the two needs to be done quite carefully. You might be better advised to stick to the numerical methods (nextInt/nextDouble).
For example, replacing this
item = Integer.parseInt(in.nextLine());
by this
item = in.nextInt();
automatically handles the line-ending.
From discussion in comments:
I am still confused as to why it's having me input
the value a second time on the next line
Making assumptions about how you modified the code since your initial question: it's because you've written code that reads the number twice:
System.out.print("How many numbers you want to input?: ");
number = in.nextInt(); // **** first input ****
array = new int [number];
item = in.nextDouble(); // **** second input ****
double[] values = new double[item];
Each time you call for in.nextSomething() the Scanner is going to read more input. It should likely just be this:
System.out.print("How many numbers you want to input?: ");
number = in.nextInt();
array = new int [number];
double[] values = new double[number];
So, I am very new at coding but have a college assignment to create a Word Manipulator. I am supposed to get a string and an INT from the user and invert every Nth word, according to the int input.
I am following steps and am stuck with this error at line 38 (the start of my last FOR LOOP). The compiler is giving me an Not an Statement Error in this line but I cant see where I went wrong.
Could someone gimme a light, please?
ps: I am not allowed to use Token or inverse().
import java.util.Scanner;
public class assignment3 {
public static void main(String[] args) {
// BOTH INPUTS WERE TAKEN
Scanner input = new Scanner (System.in);
String stringInput;
int intInput;
System.out.println("Please enter a sentence");
stringInput = input.nextLine();
System.out.println("Please enter an integer from 1 to 10. \n We will invert every word in that position for you!");
intInput = input.nextInt();
int counter = 1;
// ALL CHARS NOW ARE LOWERCASE
String lowerCaseVersion = stringInput.toLowerCase();
// SPLIT THE STRING INTO ARRAY OF WORDS
String [] arrayOfWords = null;
String delimiter = " ";
arrayOfWords = lowerCaseVersion.split(delimiter);
for(int i=0; i< arrayOfWords.length; i++){
System.out.println(arrayOfWords[i]);
// THIS RETURNS AN ARRAY WITH ALL THE WORDS FROM THE INPUT
}
// IF THE INTEGER INPUT IS BIGGER THAN THE STRING.LENGTH, OUTPUT A MESSAGE
// THIS PART IS WORKING BUT I MIGHT WANT TO PUT IT IN A LOOP AND ASK FOR INPUT AGAIN
if (intInput > arrayOfWords.length){
System.out.println("There are not enough words in your sentence!");
}
// NOW I NEED TO REVERSE EVERY NTH WORD BASED ON THE USER INPUT
//THIS IS WHERE THE ERROR OCCURS
for(int i=(intInput-1); i<arrayOfWords.length; (i+intInput)){
char invertedWord[] = new char[arrayOfWords.length()];
for(int i=0; i < arrayOfWords.length();i++){
ch[i]=arrayOfWords.charAt(i);
}
for(int i=s.length()-1;i>=0;i--){
System.out.print(invertedWord[i]);
}
}
}
}
(i+intInput) isn't a statement. That's like saying 12. Perhaps you mean i=i+intInput or i+=intInput which assigns a value to a variable
well, for one thing, i dont see "s" (from s.length()) initiated anywhere in your code.
So I'm doing some random practice for an upcoming exam, and I don't know if it's the fact that I've been reviewing for hours and my brain isn't functioning, or something in this code is wrong.
I'm attempting to make a very simple java program that asks the user for the amount of numbers they wish to enter (totalNum), create an array that long, and then ask the user for each individual value. After it asks the user for each value in the array, it prints the array.
Here is my code:
import java.util.Scanner;
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i>totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++;
}
numbers.toString();
System.out.println(numbers);
}
}
When I run it it asks the user for the numbers I want to store, then prints [I#33909752 and stops. I've done dozens of programs like this and for the life of me I can't figure out where I went wrong.
Any help would be appreciated, thanks!
Your loop test is backwards. This
for (int i = 0; i>totalNum; i++) {
should be
for (int i = 0; i < totalNum; i++) {
as is, the test evaluates to false and the loop isn't entered. And, don't increment i in the loop body (that's what i++ does in the for). Finally,
System.out.println(numbers);
isn't going to print the array correctly, because arrays don't override Object.toString(). You can use Arrays.toString like
System.out.println(Arrays.toString(numbers));
i>totalNum is the problem. The for loop will not execute even once.
The for loop has three parts:
The action to perform before starting the loop
The condition
The action to perform after each loop
Your condition is i>totalNum, which is false for i=0 and totalNum=1. The loop won't execute even once.
The i++ is already mentioned in the loop, you do not need to include it in the loop body anymore.
The unexpected output is the caused by the default toString()-method of Array. Use Arrays.toString() for a readable output.
Your loop condition should be
for (int i = 0; i<totalNum; i++) {
and within loop don't increment variable i
use below for your desired result.
public class Practice1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("How many numbers would you like to store?");
int totalNum = s.nextInt();
int[] numbers= new int[totalNum];
for (int i = 0; i<totalNum; i++) {
System.out.println("Number" + i + " :");
numbers[i] = s.nextInt();
i++; //remove this
}
numbers.toString();
System.out.println(Arrays.toString(numbers));
}
}
I just wrote this basic program. It takes 5 values from the user and stores all of them in an array and tells the highest number.
import java.util.Scanner;
public class HighestNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int [] numbers = new int [5];
int max = numbers[0];
System.out.println("Enter " + numbers.length + " numbers:");
for (int i=0; i<numbers.length; i++) {
numbers[i] = input.nextInt();
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("The highest number is:" +max);
}
}
I'd like to take off the restriction of 5 numbers and allow the user to add as many numbers as he wants. How can I do that?
Appreciate the assistance. :)
Thanks
If the user knows the number of numbers in advance (before they enter the actual numbers):
Ask the user how many numbers they want to enter:
System.out.println("How many numbers?");
int numberOfNumbers = input.nextInt();
Use that as the array size:
int[] numbers = new int[numberOfNumbers];
If the user shouldn't need to know the number of numbers in advance (e.g. if they should be able to type "stop" after the last number) then you should consider using a List instead.
Alternatively, you could use an ArrayList and keep on adding elements until the user enters a blank line. Here is a tutorial on using ArrayList.
Some pseudocode could be:
numbers = new list
while true
line = readLine
if line == ""
then
break
else
numbers.add(convertToInteger(line))
...
The benefit of this approach is that the user does not need to even count how many numbers he/she wants to enter.
My teacher explained two dimensional arrays in literally two paragraphs. He didn't give me any information on how to create them besides that and now I have to do an assignment.
I've read up a lot about it and I somewhat understand how a 2D array is like an array of arrays, but I'm still completely and utterly confused about how to apply it.
The assignment itself is very simple. It asks me to create a program that will ask a user for ten Criminal Records, (name, crime, year). This program will store the records in a two-dimensional array and then sort them using the selection sort.
I know this is probably wrong, but here is what I have so far based on what I've read:
public static void main(String[] args)throws IOException {
//create array
String[][] Criminals = new String[10][3]; // create 3 columns, 10 rows
int i, j;
int smallest; //smallest is the current smallest element
int temp; //make an element swap
String line;
//loop to request to fill array
for (int row = 1; row < Criminals.length; row++){
for (int col = 1; col < Criminals[row].length; col++){
System.out.print("Enter a criminal name: ");
Criminals[row][col] = br.readLine();
}
}
}
So far, I'm just trying to get the input and store it.
(Please try to be patient and thorough with me! Coding isn't my strongest point, but I'm trying to learn.) Any help would be amazing! Thanks in advance. :)
It looks fine for the most part. You should index arrays starting from 0, not 1. Your current code works but I'm guessing you don't want the same prompt for all entries. Thus it may be a good idea to use a single loop instead:
for (int row = 0; row < Criminals.length; row++) {
System.out.print("Enter a criminal name: ");
Criminals[row][0] = br.readLine();
System.out.print("Enter a crime: ");
Criminals[row][1] = br.readLine();
System.out.print("Enter a year: ");
Criminals[row][2] = br.readLine();
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//create array
String[][] criminals = new String[10][3]; // create 3 columns, 10 rows
int i, j;
int smallest; //smallest is the current smallest element
int temp; //make an element swap
String line;
//loop to request to fill array
for (int row = 0; row < criminals.length; row++){
System.out.print("Enter a criminal name: ");
while(in.hasNext()){
criminals[row][0] = in.nextLine();
System.out.print("Enter a crime: ");
criminals[row][1] = in.nextLine();
System.out.print("Enter a year: ");
criminals[row][2] = in.nextLine();
}
}
}
}
This will print the commands you need from user and will store it in criminals. You may sort in the end. Since you didn't gave any information how you want it sorted, I will leave it for you to do it.
PS: I changed the 2d array name from Criminals to criminals, it's a java's good practice to not use capital words for attributes and variables (use it only for class names)