[英]Java Scanners: How to keep the same line after an input
我有一小段代碼,我不知道如何解決。 就是這個:
System.out.print("y=");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("x+");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();
輸出為:y = 3一行,x + 4下一行。 我希望他們在同一條線上。 我該怎么做呢?
我不確定您要在那里做什么,但也許您只需要使用一個System.out.print? 在代碼底部的示例:
System.out.print("y= %d x+%d", m , b);
理解您的問題為什么會有點令人困惑。
但是,您可以嘗試以下代碼片段,看看它是否對您有用!
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class so1 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String arrayStr = br.readLine();
String[] auxStr = arrayStr.split(" ");
int[] arr = new int[2];
for(int i=0;i<auxStr.length;i++){
arr[i]= Integer.parseInt(auxStr[i]);
}
System.out.println("y="+arr[0] + " x+"+arr[1]);
}
}
這是您可以獲得的-
3 4
y=3 x+4
如果您覺得問題沒有用,請更新您的問題。 我將進行相應的更新。
程序看起來像這樣:
y=3<newline>
x+5<newline>
但您希望它看起來像:
y=3x+5
有問題的換行符來自於使用掃描儀和標准輸入的固有緩沖性質。 為了使掃描程序知道到達數字的末尾,必須有空格(空格,換行符等)。為了使程序從STDIN接收輸入,int的字符長度必須為大於緩沖區大小,或者必須按ENTER鍵。
TL; DR-僅使用基本標准就很難做到,甚至可能做不到。如果您真的想要輸出,則可能需要找到一個與控制台交互的庫並使用它。
但是,如果您重新構造輸入內容,則可能會得到幾乎一樣的效果:
enter intercept: 5<enter>
enter slope: 3<enter>
y=3x+5
您的代碼經過修改以產生該輸出:
System.out.print("enter intercept:");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("enter slope: ");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();
System.out.println("y="+m+"x+"+b);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.