I'm new to Java & I don't even know if what I'm trying to do is actually doable in cmd but I want to know if there's a way to ask the user for an input while displaying something at the right of the input, something like:
enter weight: _ kg
specifying the unit I want the weight in for example
here is the code sample I have so far
import java.util.*;
public class ScannerPrompt {
public static void main(String[] args) {
int[] listOfIntegers = new int[10];
Scanner s = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
System.out.print("Enter num: ");
int num = s.nextInt();
listOfIntegers[i] = num;
}
}
}
We can use \r in a tricky way:
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String[] args) {
int i=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter num: __kg\r");
System.out.print("Enter num: ");
i = s.nextInt();
System.out.println("\n"+i);
}
}
How it works:
we print Enter num: __kg and \r to make cursor at the begining of the line
Now if we print something, it will overwrite the fist message because cursor is in fist position, so we overwrite with same letters but just the part that will make the cursor at the desired position. Hence we print Enter num:
Dont use println because it insert \n at the end, and dont test in an IDE but use the console of your system.
You could use carriage return \r to relocate the cursor to the start of line
System.out.printf("%20skg\rEnter num: ", " ");
Related
I'm trying to store name and address of persons in the form of 2d array, but when I run my code it accepts less values only. For example if I give the array 2 rows and 2 columns, it accepts only 3 values.
I've tried searching on other forums, couldn't get the proper answer.
I also changed the dimension values but it gives wrong result only.
import java.util.*;
class findme{
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
System.out.print("enter the number of person: ");
int per=scan.nextInt();
System.out.print("enter the number of address: ");
int addr=scan.nextInt();
String addrs[][]=new String[per][addr];
for(int i=0;i<per;i++){
for(int j=0;j<addr;j++){
addrs[i][j]=scan.nextLine();
}
}
}
}
You read 4 values but one is an empty line from when you press enter for int addr=scan.nextInt();
A quick fix is to read that empty line
import java.util.*;
class findme{
public static void main(String args[]){
Scanner scan=new Scanner(System.in);
System.out.print("enter the number of person: ");
int per=scan.nextInt();
System.out.print("enter the number of address: ");
int addr=scan.nextInt();
---> scan.nextLine();
String addrs[][]=new String[per][addr];
for(int i=0;i<per;i++){
for(int j=0;j<addr;j++){
addrs[i][j]=scan.nextLine();
}
}
}
}
Edit:
Or you can use scanner.skip Skip newline character while reading from Scanner class
In addition to the other answer here is how your code should look like:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of people: ");
int iPeople = scanner.nextInt();
System.out.print("Enter the number of address: ");
int iAdresses =scanner.nextInt();
scanner.nextLine();
String data[][] = new String[iPeople][iAdresses];
for(int i=0; i < iPeople; i++)
{
for(int j=0; j < iAdresses; j++)
{
System.out.printf("Enter %d address for person %d:%n", j + 1, i + 1);
data[i][j] = scanner.nextLine();
}
}
And try to follow these conventions:
Use proper Java naming conventions
Make your code more readable by providing appropriate empty lines between lines you feel are too cluttered or belong to different groups based on what operation are they trying to accomplish.
If you want to understand why, the behavior of nextLine is explain here : Java Scanner doesn't wait for user input
You can also replace nextLine by next to avoid this.
System.out.println("Please enter a coefficients of a polynomial’s terms:");
String coefficents = keyboard.nextLine();
String[] three = coefficents.split(" ");
int[] intArray1 = new int[three.length];
for (int i = 0; i < intArray1.length; i++) {
System.out.print(intArray1[i]);
}
//Does anyone know how i can make this work because right not it builds but when i run it, it gives me 0
//if someone could show me or explain to me what's wrong that would help
The problem was that you created the array intArray1 and you printed it without adding any elements to it. That's why it gives 0 as the result.
Instead of creating intArray1, print out the array three in the following way:
import java.util.Scanner;
public class test {
public static void main(String args[]){
Scanner user_input = new Scanner(System.in);
System.out.println("Please enter the coefficients of a polynomial’s terms:");
String coefficents = user_input.nextLine();
String[] three = coefficents.split(" ");
for (String i: three) {
System.out.print(i);
}
}
}
I have some problem when I ask the user to input some numbers and then I want to process them. Look at the code below please.
To make this program works properly I need to input two commas at the end and then it's ok. If I dont put 2 commas at the and then program doesnt want to finish or I get an error.
Can anyone help me with this? What should I do not to input those commas at the end
package com.kurs;
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
String gd = "4,5, 6, 85";
Scanner s = new Scanner(System.in).useDelimiter(", *");
System.out.println("Input some numbers");
System.out.println("delimiter to; " + s.delimiter());
int sum = 0;
while (s.hasNextInt()) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
s.close();
System.exit(0);
}
}
Your program hangs in s.hasNextInt().
From the documentation of Scanner class:
The next() and hasNext() methods and their primitive-type companion
methods (such as nextInt() and hasNextInt()) first skip any input that
matches the delimiter pattern, and then attempt to return the next
token. Both hasNext and next methods may block waiting for further
input.
In a few words, scanner is simply waiting for more input after the last integer, cause it needs to find your delimiter in the form of the regular expression ", *" to decide that the last integer is fully typed.
You can read more about your problem in this discussion:
Link to the discussion on stackoverflow
To solve such problem, you may change your program to read the whole input string and then split it with String.split() method. Try to use something like this:
import java.util.Scanner;
public class NumberFromUser {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] tokens = sc.nextLine().split(", *");
int sum = 0;
for (String token : tokens) {
sum += Integer.valueOf(token);
}
System.out.println(sum);
}
}
Try allowing end of line to be a delimiter too:
Scanner s = new Scanner(System.in).useDelimiter(", *|[\r\n]+");
I changed your solution a bit and probably mine isn't the best one, but it seems to work:
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
int sum = 0;
if (s.hasNextLine()) {
// Remove all blank spaces
final String line = s.nextLine().replaceAll("\\s","");
// split into a list
final List<String> listNumbers = Arrays.asList(line.split(","));
for (String str : listNumbers) {
if (str != null && !str.equals("")) {
final Integer number = Integer.parseInt(str);
sum = sum + number;
}
}
}
System.out.println(sum);
look you can do some thing like this mmm.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Input some numbers");
System.out.println("When did you to finish and get the total sum enter ,, and go");
boolean flag = true;
int sum = 0;
while (s.hasNextInt() && flag) {
int d = s.nextInt();
sum = sum + d;
}
System.out.println(sum);
}
Hi I'm writing a program that will analyse a block of text, specifically reading a file and counting the number of lines, words and numbers inside that file.
I have tried count the number of lines in a separate class within a method and then tried to call that method in the main class to print the total number of lines in the file, however this does not work as I expected and causes the program to hang when I have tried to call the line count method. Any help is greatly appreciated!
Main Class:
package cw;
import java.util.Scanner;
public class TextAnalyser {
public static void main(String[] args) {
LineCounter object = new LineCounter();
Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
int totalNumbers = 0;
int totalDigits = 0;
int totalWordCount = 0;
int totalLines = 0;
while (sc.hasNext()) {
totalWordCount++;
if (sc.hasNextInt()) {
totalDigits += sc.nextInt();
totalNumbers++;
}
else {
sc.next();
}
}
System.out.println("The total of all digits added = " + totalDigits);
System.out.println("The total number of digits in the file = " + totalNumbers);
System.out.println("The total number of words in the file = " + totalWordCount);
object.TotalLines();
}
}
Line counting class:
package cw;
import java.util.Scanner;
//Class that counts the lines in a file.
public class LineCounter {
public static void TotalLines() {
Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
System.out.println("hi");
int linetotal = 0;
while (sc.hasNextLine()) {
linetotal++;
}
System.out.println(linetotal);
}
}
hasNextLine() does only tell you IF there is a next line - it does not read it. So you are standing at the beginning and asking "is there a next line?" again and again and again... You should try actually reading it via nextLine();
just add this line of code :
while(sc.hasNextLine()){
String sentence = sc.nextLine();
linetotal++;
}
in your public static void TotalLines(){ method...
this way you actually get the next line, not only asking whether there exists another line in your while (which always returns true and you never exit the while loop!)
I'm trying to make a program that will ask for a number of people to go into an ArrayList and then pick a name out of it randomly. The code is working fine but the string asking for name input displays itself twice the first time you run it. Any clue why this happens?
What I want it to display:
Enter a name: ......
What it displays:
Enter a name:
Enter a name: ......
import java.util.*;
class RandomNumGen
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random random = new Random();
ArrayList<String> names = new ArrayList<String>();
int a, b;
System.out.print("\nEnter the number of people: ");
a = input.nextInt();
System.out.println();
for (int i = 0; i <= a; i++)
{
System.out.print("Enter a name: ");
names.add(input.nextLine());
}
b = random.nextInt(a);
System.out.print("\nRandom name: " +names.get(b)+ "\n");
}
}
The issue is that nextInt() just consumes an integer, but not the new-line character inputted when you press Enter.
To solve this you can add
input.nextLine();
after the call to nextInt() so it consumes the new-line character.
Another option would be reading a whole line, and then parsing its content (String) to a int:
a = Integer.parseInt(input.nextLine());