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));
}
}
Related
I keep trying different kinds of code and I always come back to this. but it never seems to work. The last if statement is making the i's underlined red but I can't even understand why. The homework was to make a program that takes user input and put it into an array and see if the user input is already sorted. Please Help!
import java.util.Scanner;
public class Sorting
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the array size: ");
int a = input.nextInt();
System.out.println("Enter the numbers using spaces between each number: ");
int[] numbers = new int[a];
for (int i=0; i<numbers.length; i++)
{
numbers[i]=input.nextInt();
if(isSorted(numbers))
{
System.out.println("Sort is already sorted");
}
else
{
System.out.println("Sort is not sorted sorry");
}
}
}
public static boolean isSorted(int[] numbers)
{
for(int i = 0; i<numbers.length-1; i++);
{
if(numbers[i]>numbers[i+1])
{
return false;
}
}
return true;
}
}
Close the for loop before the if statement.
for(int i = 0; i<numbers.length-1; i++); //<===== remove the ';' here
I think you missed place the ; after the for loop and that cause your issue.
For some reason when I try to ask a user for names so I can add them to a list and sort them alphabetically, this code will not print anything out. It will not even get past the while loop, does anyone have any idea what the problem is? Also another question; how can you execute some code if the user presses the enter button when asked for input value, would it just be null? Thanks!
import java.util.Scanner;
import java.util.*;
public class project16u
{
public static void main(String[] args)
{
int n;
String input = "nothing";
String temp;
ArrayList<String> names = new ArrayList<String>();
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
while(!input.equals("done")){
input = s1.nextLine();
names.add(input);
}
for (int i = 0; i < names.size()-1; i++)
{
if (names.get(i).compareTo(names.get(i+1))>0)
{
temp = names.get(i);
names.add(i, names.get(i+1));
names.add(i+1, temp);
i=0;
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < names.size() - 1; i++)
{
System.out.print(names.get(i).toString() + ",");
}
System.out.print(names.get(names.size()-1));
}
}
add inserts the name at the requested index. Thus, in your case, you will have two copies of the same name in the list, rather than the one you intended.
You probably want to use set instead.
You may need to change the loop condition to
s1.hasNextLine() && !input.equals("done")
I am trying to make a functioning to do list with a limit of 10 elements, however I am having an issue with two major things in the to do list.
The first is that after I first compile and run the program and select to add elements to the list, that functions properly, but if I add two elements and the 'stop' sentinel, when I select the next option to print the to do list, I am presented with a list, showing my two elements and then the stop sentinel along with 7 null values in the list. So the first issue I am having is to get rid of the null values, I attempted using a counter as you can see in my code however that was not proving to be effective.
The next issue that I am having is that I am trying to make it so that you can add to the list, so once you select to add more things to the list, the new options the user writes, rewrites over them in the array and prints out the new values and not along with the old ones. I am assuming that can be done through some sort of recursion method but I am having a hard time figuring it out.
Any help would be greatly appreciated!
Thanks!
import java.util.Scanner;
public class ToDo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int MAX = 10;
String[] list = new String[MAX];
int choice = 0;
while (choice != 3) {
System.out.println();
System.out.println("Type 1 to add a new thing to your to do list.");
System.out.println("Type 2 to print the to do list.");
System.out.println("Type 3 to exit the program.");
System.out.print("Select an option: ");
choice = input.nextInt();
int count = 0;
if (choice == 1) {
System.out.println("Keep hitting enter after to do's, if you want to stop, type 'stop'.");
for (int i=0;i<MAX;i++) {
list[i] = input.nextLine();
if (list[i].equals("stop")) break;
count++;
}
}
if (choice == 2) {
for (int index = 0;index < list.length; index++) {
System.out.println(list[index]);
}
}
}
}
}
As I have mentioned in the comment, you can use an ArrayList instead of String[] to make your processing much easier.
But if you want to use the array itself, there are 3 minor issues with your code.
In your choice 1 for loop, start the loop from count,
for (int i=count;i<MAX;i++) {
list[i] = input.nextLine();
if (list[i].equals("stop")) break;
count++;
}
In your choice 2 for loop, end the loop before reaching count,
for (int index = 0;index < count; index++) {
System.out.println(list[index]);
}
And move your count initialization outside the while loop.
int count = 0;
But beware, if you decide to implement removing tasks, this could get complicated and using ArrayList would become much simpler.
Instead of using a fixed size array of Strings, use an ArrayList of Strings. Then you can add elements to it as you go.
Make sure to
import java.util.ArrayList;
Declaration syntax is
ArrayList<String> myList = new ArrayList<String>();
Add elements to your list with the add() method:
myList.add(input.nextLine())
You don't need that inner for loop, instead break out of the while loop of input options when you've iterated through it 10 times.
To solve your problem of "stop" being in your list, check that the input is "stop", and stop, before you attempt to add to the list.
It is better to use ArrayList but if you still want to stick to String[] then the following program will work for you:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int MAX = 10;
String[] list = new String[MAX];
int choice = 0;
while (choice != 3) {
System.out.println();
System.out.println("Type 1 to add a new thing to your to do list.");
System.out.println("Type 2 to print the to do list.");
System.out.println("Type 3 to exit the program.");
System.out.print("Select an option: ");
choice = input.nextInt();
String userEnteredItem;
if (choice == 1) {
System.out.println("Keep hitting enter after to do's, if you want to stop, type 'stop'.");
for (int i=0;i<MAX;i++) {
userEnteredItem = input.nextLine();
if(!userEnteredItem.isEmpty()) {
list[i] = userEnteredItem;
if (userEnteredItem.equals("stop")) {
break;
}
count++;
} else {
i--; // Do not increase index for empty item.
}
}
}
else if (choice == 2) {
for (int index = 0;index < count; index++) {
System.out.println(list[index]);
}
}
else {
input.close();
}
}
}
It keeps track of user items in static int count and it also closes the scanner when you do not need it.
I'm trying to make a "for" loop in which it asks the user to input 10 numbers and then only print the positives.
Having trouble controlling the amount of inputs. I keep getting infinite inputs until I add a negative number.
import java.util.Scanner;
public class ej1 {
public static void main(String args[]) {
int x;
for (x = 1; x >= 0; ) {
Scanner input = new Scanner(System.in);
System.out.print("Type a number: ");
x = input.nextInt();
}
}
}
From a syntax point of view, you've got several problems with this code.
The statement for (x = 1; x >= 0; ) will always loop, since x will always be larger than 0, specifically because you're not introducing any kind of condition in which you decrement x.
You're redeclaring the scanner over and over again. You should only declare it once, outside of the loop. You can reuse it as many times as you need.
You're going to want to use nextLine() after nextInt() to avoid some weird issues with the scanner.
Alternatively, you could use nextLine() and parse the line with Integer.parseInt.
That said, there are several ways to control this. Using a for loop is one approach, but things get finicky if you want to be sure that you only ever print out ten positive numbers, regardless of how many negative numbers are entered. With that, I propose using a while loop instead:
int i = 0;
Scanner scanner = new Scanner(System.in);
while(i < 10) {
System.out.print("Enter a value: ");
int value = scanner.nextInt();
scanner.nextLine();
if (value > 0) {
System.out.println("\nPositive value: " + value);
i++;
}
}
If you need to only enter in ten values, then move the increment statement outside of the if statement.
i++;
if (value > 0) {
System.out.println("\nPositive value: " + value);
}
As a hint: if you wanted to store the positive values for later reference, then you would have to use some sort of data structure to hold them in - like an array.
int[] positiveValues = new int[10];
You'd only ever add values to this particular array if the value read in was positive, and you could print them at the end all at once:
// at the top, import java.util.Arrays
System.out.println(Arrays.toString(positiveValues));
...or with a loop:
for(int i = 0; i < positiveValues.length; i++) {
System.out.println(positiveValues[i]);
}
Scanner scan = new Scanner(System.in);
int input=-1;
for(int i=0;i<10;i++)
{
input = sc.nextInt();
if(input>0)
System.out.println(input);
}
I'm having a problem with my while loop. The program asks the user for their name and after the user have made their input, the program asks how many times you would like to print the input.
I've been stuck on my while-loop for quite a time and can only make it work if I do something like: } while (antal > some random number)
package uppg2;
import java.util.Scanner;
public class Uppg2 {
public static void main(String[] args) {
Scanner name = new Scanner(System.in);
Scanner ant = new Scanner(System.in);
int antal;
String namn;
System.out.print("Whats your name?: ");
namn = name.nextLine();
System.out.print("How many times u wanna print ur name?: ");
antal = ant.nextInt();
do {
System.out.print(namn);
} while (????);
antal++;
namn = null;
antal = 0;
}
}
I personally would use a for loop like so:
for(int i = 0 ; i < antal; i++){
System.out.println(namn);
}
This would be rather a use-case for a for-loop like some others suggested. But when you insist on using a while loop:
int counter = 0; // a variable which counts how often the while loop has run
do {
System.out.print( namn ); // do what you want to do
counter++ // increase the counter
} while (counter < antal) // check if the desired number of iterations is reached
When you don't need the value of antal anymore when the loop is over, you can also do it without the counter variable and just reduce antal every loop and check if it has reached 0.
do {
System.out.print( namn );
antal--;
} while (antal > 0)
You could count antal down (antal--) until it is 1. Not sure if it is OK to destroy the value in antal though.
package uppg2;
import java.util.Scanner;
public class Uppg2 {
public static void main(String[] args) {
final Scanner in = new Scanner(System.in);
int antal;
String namn;
System.out.print("Whats your name?: ");
namn = in.nextLine();
System.out.print("How many times u wanna print ur name?: ");
antal = in.nextInt();
int i = 0;
while(i < antal){
System.out.print( namn );
i++;
}
in.close();
}
}
Tell me if that works. Basically, you need an increment counter to ensure that it only prints out the desired amount of times. Since we start counting at 0, we don't need to ensure that it goes till it equals the print time, but while it still is under it.
you would have to have a counter that is incremented inside of your do-while loop, and perform your comparison against that value
it would make your loop loop something like:
antal = ant.nextInt();
int i = 0;
do{
System.out.print( namn );
i++;
}while (i < antal);
note that because it's a do-while loop, you will always print the name at least once, even if the user enters zero. To prevent this, you would need to use a for or while loop, as described by other answerers, or use an if condition around the System.out.println call to check if antal is zero.
Also, if you don't care what antal is at the end, you can use TofuBeer's solution.
Here's a solution to a similar problem. See if you can't translate it into your problem:
// How many times to I want to do something?
int max = 40;
for (int i = 0; i < max; i++) {
// Do something!
}